@@ -1,23 +1,20 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE FlexibleContexts #-}
1{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
2{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE NoMonomorphismRestriction #-}
5+{-# LANGUAGE NamedFieldPuns #-}
8{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
9{-# LANGUAGE RecordWildCards #-}
7{-# LANGUAGE RecordWildCards #-}
10{-# LANGUAGE UndecidableInstances #-}
8{-# LANGUAGE UndecidableInstances #-}
11−{-# LANGUAGE NamedFieldPuns #-}
13-------------------------------------------------------------------------------
10-------------------------------------------------------------------------------
15-- Module : Database.Bloodhound.Types
12-- Module : Database.Bloodhound.Types
16−-- Copyright : (C) 2014 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
17-- License : BSD-style (see the file LICENSE)
14-- License : BSD-style (see the file LICENSE)
18-- Maintainer : Chris Allen <cma@bitemyapp.com
15-- Maintainer : Chris Allen <cma@bitemyapp.com
19-- Stability : provisional
16-- Stability : provisional
20−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
22-- Data types for describing actions and data structures performed to interact
19-- Data types for describing actions and data structures performed to interact
23-- with Elasticsearch. The two main buckets your queries against Elasticsearch
20-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -45,10 +42,15 @@ module Database.Bloodhound.Types
45 , mkTermsAggregation
42 , mkTermsAggregation
46 , mkTermsScriptAggregation
43 , mkTermsScriptAggregation
47 , mkDateHistogram
44 , mkDateHistogram
45+ , mkCardinalityAggregation
48 , mkDocVersion
46 , mkDocVersion
48+ , mkExtendedStatsAggregation
49 , docVersionNumber
49 , docVersionNumber
51 , toDateHistogram
52 , toDateHistogram
52 , omitNulls
54 , omitNulls
@@ -59,6 +61,9 @@ module Database.Bloodhound.Types
60 , MonadBH(..)
62 , MonadBH(..)
61 , Version(..)
63 , Version(..)
62 , Status(..)
67 , Status(..)
63 , Existence(..)
68 , Existence(..)
64 , NullValue(..)
69 , NullValue(..)
@@ -66,8 +71,12 @@ module Database.Bloodhound.Types
66 , UpdatableIndexSetting(..)
71 , UpdatableIndexSetting(..)
67 , IndexSettingsSummary(..)
72 , IndexSettingsSummary(..)
68 , AllocationPolicy(..)
73 , AllocationPolicy(..)
69 , ReplicaBounds(..)
75 , ReplicaBounds(..)
70 , Bytes(..)
76 , Bytes(..)
71 , FSType(..)
80 , FSType(..)
72 , InitialShardCount(..)
81 , InitialShardCount(..)
73 , NodeAttrFilter(..)
82 , NodeAttrFilter(..)
@@ -111,8 +120,8 @@ module Database.Bloodhound.Types
111 , Pattern(..)
120 , Pattern(..)
112 , ShardResult(..)
121 , ShardResult(..)
113 , Hit(..)
122 , Hit(..)
114 , Filter(..)
124 , Filter(..)
116 , BoolMatch(..)
125 , BoolMatch(..)
117 , Term(..)
126 , Term(..)
118 , GeoPoint(..)
127 , GeoPoint(..)
@@ -139,8 +148,22 @@ module Database.Bloodhound.Types
139 , RegexpFlags(..)
148 , RegexpFlags(..)
140 , RegexpFlag(..)
149 , RegexpFlag(..)
141 , FieldName(..)
150 , FieldName(..)
142 , Script(..)
154 , Script(..)
155+ , ScriptLanguage(..)
143 , IndexName(..)
161 , IndexName(..)
162+ , IndexSelection(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
144 , TemplateName(..)
167 , TemplateName(..)
145 , TemplatePattern(..)
168 , TemplatePattern(..)
146 , MappingName(..)
169 , MappingName(..)
@@ -164,8 +187,19 @@ module Database.Bloodhound.Types
164 , BoolQuery(..)
187 , BoolQuery(..)
165 , BoostingQuery(..)
188 , BoostingQuery(..)
166 , CommonTermsQuery(..)
189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
198+ , FieldValueFactor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
167 , DisMaxQuery(..)
202 , DisMaxQuery(..)
169 , FuzzyLikeThisQuery(..)
203 , FuzzyLikeThisQuery(..)
170 , FuzzyLikeFieldQuery(..)
204 , FuzzyLikeFieldQuery(..)
171 , FuzzyQuery(..)
205 , FuzzyQuery(..)
@@ -181,10 +215,16 @@ module Database.Bloodhound.Types
181 , RangeQuery(..)
215 , RangeQuery(..)
182 , RegexpQuery(..)
216 , RegexpQuery(..)
183 , QueryString(..)
217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
184 , BooleanOperator(..)
221 , BooleanOperator(..)
185 , ZeroTermsQuery(..)
222 , ZeroTermsQuery(..)
186 , CutoffFrequency(..)
223 , CutoffFrequency(..)
187 , Analyzer(..)
224 , Analyzer(..)
188 , MaxExpansions(..)
228 , MaxExpansions(..)
189 , Lenient(..)
229 , Lenient(..)
190 , MatchQueryType(..)
230 , MatchQueryType(..)
@@ -231,16 +271,108 @@ module Database.Bloodhound.Types
231 , CollectionMode(..)
271 , CollectionMode(..)
232 , TermOrder(..)
272 , TermOrder(..)
233 , TermInclusion(..)
273 , TermInclusion(..)
274+ , SnapshotRepoSelection(..)
275+ , GenericSnapshotRepo(..)
277+ , SnapshotRepoConversionError(..)
278+ , SnapshotRepoType(..)
279+ , GenericSnapshotRepoSettings(..)
280+ , SnapshotRepoUpdateSettings(..)
281+ , defaultSnapshotRepoUpdateSettings
282+ , SnapshotRepoName(..)
283+ , SnapshotRepoPattern(..)
284+ , SnapshotVerification(..)
285+ , SnapshotNodeVerification(..)
292+ , NodeBreakersStats(..)
293+ , NodeBreakerStats(..)
295+ , NodeTransportStats(..)
297+ , NodeDataPathStats(..)
298+ , NodeFSTotalStats(..)
299+ , NodeNetworkStats(..)
300+ , NodeThreadPoolsStats(..)
301+ , NodeThreadPoolStats(..)
303+ , JVMBufferPoolStats(..)
306+ , NodeProcessStats(..)
309+ , NodeIndicesStats(..)
313+ , NodePluginInfo(..)
315+ , NodeTransportInfo(..)
316+ , BoundTransportAddress(..)
317+ , NodeNetworkInfo(..)
319+ , NetworkInterfaceName(..)
320+ , NodeNetworkInterface(..)
321+ , NodeThreadPoolsInfo(..)
322+ , NodeThreadPoolInfo(..)
323+ , ThreadPoolSize(..)
324+ , ThreadPoolType(..)
327+ , JVMGCCollector(..)
332+ , NodeProcessInfo(..)
333+ , FsSnapshotRepo(..)
334+ , SnapshotCreateSettings(..)
335+ , defaultSnapshotCreateSettings
336+ , SnapshotSelection(..)
337+ , SnapshotPattern(..)
339+ , SnapshotShardFailure(..)
343+ , SnapshotRestoreSettings(..)
344+ , defaultSnapshotRestoreSettings
345+ , RestoreRenamePattern(..)
346+ , RestoreRenameToken(..)
350+ , RestoreIndexSettings(..)
353+ , PhraseSuggester(..)
354+ , PhraseSuggesterHighlighter(..)
355+ , PhraseSuggesterCollate(..)
357+ , SuggestOptions(..)
358+ , SuggestResponse(..)
359+ , NamedSuggestionResponse(..)
360+ , DirectGenerators(..)
361+ , mkDirectGenerators
362+ , DirectGeneratorSuggestModeTypes (..)
235 , Aggregation(..)
364 , Aggregation(..)
236 , Aggregations
365 , Aggregations
237 , AggregationResults
366 , AggregationResults
238 , Bucket(..)
368 , Bucket(..)
239 , BucketAggregation(..)
369 , BucketAggregation(..)
240 , TermsAggregation(..)
370 , TermsAggregation(..)
241 , MissingAggregation(..)
371 , MissingAggregation(..)
242 , ValueCountAggregation(..)
372 , ValueCountAggregation(..)
243 , FilterAggregation(..)
373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
244 , DateHistogramAggregation(..)
376 , DateHistogramAggregation(..)
245 , DateRangeAggregation(..)
377 , DateRangeAggregation(..)
246 , DateRangeAggRange(..)
378 , DateRangeAggRange(..)
@@ -248,6 +380,9 @@ module Database.Bloodhound.Types
248 , DateMathAnchor(..)
380 , DateMathAnchor(..)
249 , DateMathModifier(..)
381 , DateMathModifier(..)
250 , DateMathUnit(..)
382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
252 , Highlights(..)
387 , Highlights(..)
253 , FieldHighlight(..)
388 , FieldHighlight(..)
@@ -261,647 +396,36 @@ module Database.Bloodhound.Types
261 , HighlightTag(..)
396 , HighlightTag(..)
262 , HitHighlight
397 , HitHighlight
264 , TermsResult(..)
400 , TermsResult(..)
265 , DateHistogramResult(..)
401 , DateHistogramResult(..)
266 , DateRangeResult(..)
402 , DateRangeResult(..)
268 , EsUsername(..)
405 , EsUsername(..)
269 , EsPassword(..)
406 , EsPassword(..)
272−import Control.Applicative
273−import Control.Monad.Catch
274−import Control.Monad.Except
275−import Control.Monad.Reader
276−import Control.Monad.State
277−import Control.Monad.Writer
279−import Data.Aeson.Types (Pair, Parser, emptyObject,
281−import qualified Data.ByteString.Lazy.Char8 as L
283−import Data.Hashable (Hashable)
284−import qualified Data.HashMap.Strict as HM
285−import Data.List (foldl', nub)
286−import Data.List.NonEmpty (NonEmpty (..), toList)
287−import qualified Data.Map.Strict as M
289−import Data.Scientific (Scientific)
290−import Data.Text (Text)
291−import qualified Data.Text as T
292−import Data.Time.Calendar
293−import Data.Time.Clock (NominalDiffTime, UTCTime)
294−import Data.Time.Clock.POSIX
295−import qualified Data.Traversable as DT
296−import Data.Typeable (Typeable)
297−import qualified Data.Vector as V
299−import GHC.Generics (Generic)
300−import Network.HTTP.Client
301−import qualified Network.HTTP.Types.Method as NHTM
303−import Database.Bloodhound.Types.Class
304−import Database.Bloodhound.Types.Internal
307−-- >>> :set -XOverloadedStrings
308−-- >>> import Database.Bloodhound
309−-- >>> let testServer = (Server "http://localhost:9200")
310−-- >>> let testIndex = IndexName "twitter"
311−-- >>> let testMapping = MappingName "tweet"
312−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
314−-- defaultIndexSettings is exported by Database.Bloodhound as well
315−-- no trailing slashes in servers, library handles building the path.
317−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
318−-- will be a noop. You can use the exported fields to customize it further, e.g.:
320−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
321−mkBHEnv :: Server -> Manager -> BHEnv
322−mkBHEnv s m = BHEnv s m return
324−newtype BH m a = BH {
325− unBH :: ReaderT BHEnv m a
326− } deriving ( Functor
340−instance MonadTrans BH where
343−instance (MonadReader r m) => MonadReader r (BH m) where
345− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
348−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
349− getBHEnv = BH getBHEnv
351−runBH :: BHEnv -> BH m a -> m a
352−runBH e f = runReaderT (unBH f) e
354−{-| 'Version' is embedded in 'Status' -}
355−data Version = Version { number :: Text
356− , build_hash :: Text
357− , build_timestamp :: UTCTime
358− , build_snapshot :: Bool
359− , lucene_version :: Text } deriving (Eq, Show, Generic, Typeable)
361−{-| 'Status' is a data type for describing the JSON body returned by
362− Elasticsearch when you query its status. This was deprecated in 1.2.0.
364− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
367−data Status = Status { ok :: Maybe Bool
370− , version :: Version
371− , tagline :: Text } deriving (Eq, Show, Generic)
373−{-| 'IndexSettings' is used to configure the shards and replicas when you create
374− an Elasticsearch Index.
376− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
380− IndexSettings { indexShards :: ShardCount
381− , indexReplicas :: ReplicaCount } deriving (Eq, Show, Generic, Typeable)
383−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
384−defaultIndexSettings :: IndexSettings
385−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
387−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
389− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
391−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
392− -- ^ The number of replicas each shard has.
393− | AutoExpandReplicas ReplicaBounds
394− | BlocksReadOnly Bool
395− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
397− -- ^ Set to True to disable read operations against the index.
399− -- ^ Set to True to disable write operations against the index.
400− | BlocksMetaData Bool
401− -- ^ Set to True to disable metadata operations against the index.
402− | RefreshInterval NominalDiffTime
403− -- ^ The async refresh interval of a shard
404− | IndexConcurrency Int
405− | FailOnMergeFailure Bool
406− | TranslogFlushThresholdOps Int
407− -- ^ When to flush on operations.
408− | TranslogFlushThresholdSize Bytes
409− -- ^ When to flush based on translog (bytes) size.
410− | TranslogFlushThresholdPeriod NominalDiffTime
411− -- ^ When to flush based on a period of not flushing.
412− | TranslogDisableFlush Bool
413− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
414− | CacheFilterMaxSize (Maybe Bytes)
415− -- ^ The maximum size of filter cache (per segment in shard).
416− | CacheFilterExpire (Maybe NominalDiffTime)
417− -- ^ The expire after access time for filter cache.
418− | GatewaySnapshotInterval NominalDiffTime
419− -- ^ The gateway snapshot interval (only applies to shared gateways).
420− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
421− -- ^ A node matching any rule will be allowed to host shards from the index.
422− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
423− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
424− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
425− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
426− | RoutingAllocationEnable AllocationPolicy
427− -- ^ Enables shard allocation for a specific index.
428− | RoutingAllocationShardsPerNode ShardCount
429− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
430− | RecoveryInitialShards InitialShardCount
431− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
432− | GCDeletes NominalDiffTime
433− | TTLDisablePurge Bool
434− -- ^ Disables temporarily the purge of expired docs.
435− | TranslogFSType FSType
436− | IndexCompoundFormat CompoundFormat
437− | IndexCompoundOnFlush Bool
438− | WarmerEnabled Bool
439− deriving (Eq, Show, Generic, Typeable)
441−data AllocationPolicy = AllocAll
442− -- ^ Allows shard allocation for all shards.
444− -- ^ Allows shard allocation only for primary shards.
446− -- ^ Allows shard allocation only for primary shards for new indices.
448− -- ^ No shard allocation is allowed
449− deriving (Eq, Show, Generic, Typeable)
451−data ReplicaBounds = ReplicasBounded Int Int
452− | ReplicasLowerBounded Int
454− deriving (Eq, Show, Generic, Typeable)
456−newtype Bytes = Bytes Int deriving (Eq, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
458−data FSType = FSSimple
459− | FSBuffered deriving (Eq, Show, Generic, Typeable, Ord)
461−data InitialShardCount = QuorumShards
462− | QuorumMinus1Shards
465− | ExplicitShards Int
466− deriving (Eq, Show, Generic, Typeable)
468−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
469− , nodeAttrFilterValues :: NonEmpty Text}
470− deriving (Eq, Show, Generic, Ord)
472−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Show, Ord, Generic, Typeable)
474−data CompoundFormat = CompoundFileFormat Bool
475− | MergeSegmentVsTotalIndex Double
476− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
477− deriving (Eq, Show, Generic, Typeable)
479−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
481−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
482− , sSummaryFixedSettings :: IndexSettings
483− , sSummaryUpdateable :: [UpdatableIndexSetting]}
484− deriving (Eq, Show, Generic, Typeable)
486−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
487−type Reply = Network.HTTP.Client.Response L.ByteString
488−type Method = NHTM.Method
490−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
492− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
494−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show, Generic, Typeable)
496−data FieldType = GeoPointType
502− | ByteType deriving (Eq, Show, Generic, Typeable)
504−data FieldDefinition =
505− FieldDefinition { fieldType :: FieldType } deriving (Eq, Show, Generic, Typeable)
507−{-| An 'IndexTemplate' defines a template that will automatically be
508− applied to new indices created. The templates include both
509− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
510− controls if the template will be applied to the index created.
511− Specify mappings as follows: @[toJSON TweetMapping, ...]@
513− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
516− IndexTemplate { templatePattern :: TemplatePattern
517− , templateSettings :: Maybe IndexSettings
518− , templateMappings :: [Value]
522− MappingField { mappingFieldName :: FieldName
523− , fieldDefinition :: FieldDefinition } deriving (Eq, Show, Generic, Typeable)
525−{-| Support for type reification of 'Mapping's is currently incomplete, for
526− now the mapping API verbiage expects a 'ToJSON'able blob.
528− Indexes have mappings, mappings are schemas for the documents contained in the
529− index. I'd recommend having only one mapping per index, always having a mapping,
530− and keeping different kinds of documents separated if possible.
532−data Mapping = Mapping { typeName :: TypeName
533− , mappingFields :: [MappingField] } deriving (Eq, Show, Generic, Typeable)
535−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
536− operation index, create, delete, and update. 'BulkIndex' behaves like an
537− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
539− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
542− BulkIndex IndexName MappingName DocId Value
543− | BulkCreate IndexName MappingName DocId Value
544− | BulkDelete IndexName MappingName DocId
545− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show, Generic, Typeable)
547−{-| 'EsResult' describes the standard wrapper JSON document that you see in
548− successful Elasticsearch lookups or lookups that couldn't find the document.
550−data EsResult a = EsResult { _index :: Text
553− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show, Generic, Typeable)
555−{-| 'EsResultFound' contains the document and its metadata inside of an
556− 'EsResult' when the document was successfully found.
558−data EsResultFound a = EsResultFound { _version :: DocVersion
559− , _source :: a } deriving (Eq, Show, Generic, Typeable)
561−{-| 'EsError' is the generic type that will be returned when there was a
562− problem. If you can't parse the expected response, its a good idea to
565−data EsError = EsError { errorStatus :: Int
566− , errorMessage :: Text } deriving (Eq, Show, Generic, Typeable)
568−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
569−returned by the ElasticSearch server. If you encounter this error, please
570−verify that your domain data types and FromJSON instances are working properly
571−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
572−sure that your mappings are correct, then this error may be an indication of an
573−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
574−and be sure to include the exception body.
576−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
577− deriving (Eq, Show, Generic, Typeable)
579−instance Exception EsProtocolException
581−data IndexAlias = IndexAlias { srcIndex :: IndexName
582− , indexAlias :: IndexAliasName } deriving (Eq, Show, Generic, Typeable)
584−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Show, Generic, ToJSON)
586−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
587− | RemoveAlias IndexAlias deriving (Show, Eq, Generic, Typeable)
589−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
590− , aliasCreateFilter :: Maybe Filter}
591− deriving (Show, Eq, Generic, Typeable)
593−data AliasRouting = AllAliasRouting RoutingValue
594− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
595− deriving (Show, Eq, Generic, Typeable)
597−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Show, Eq, Generic, Typeable)
599−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
601−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
603−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Show, Eq, Generic, Typeable)
605−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
606−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
607− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Show, Eq, Generic, Typeable)
609−{-| 'DocVersion' is an integer version number for a document between 1
610−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
612−newtype DocVersion = DocVersion {
613− docVersionNumber :: Int
614− } deriving (Eq, Show, Generic, Ord, ToJSON)
616−-- | Smart constructor for in-range doc version
617−mkDocVersion :: Int -> Maybe DocVersion
619− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
621− | otherwise = Nothing
624−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
625−own version numbers instead of ones from ES.
627−newtype ExternalDocVersion = ExternalDocVersion DocVersion
628− deriving (Eq, Show, Generic, Ord, Bounded, Enum, ToJSON)
630−{-| 'VersionControl' is specified when indexing documents as a
631−optimistic concurrency control.
633−data VersionControl = NoVersionControl
634− -- ^ Don't send a version. This is a pure overwrite.
635− | InternalVersion DocVersion
636− -- ^ Use the default ES versioning scheme. Only
637− -- index the document if the version is the same
638− -- as the one specified. Only applicable to
639− -- updates, as you should be getting Version from
641− | ExternalGT ExternalDocVersion
642− -- ^ Use your own version numbering. Only index
643− -- the document if the version is strictly higher
644− -- OR the document doesn't exist. The given
645− -- version will be used as the new version number
646− -- for the stored document. N.B. All updates must
647− -- increment this number, meaning there is some
648− -- global, external ordering of updates.
649− | ExternalGTE ExternalDocVersion
650− -- ^ Use your own version numbering. Only index
651− -- the document if the version is equal or higher
652− -- than the stored version. Will succeed if there
653− -- is no existing document. The given version will
654− -- be used as the new version number for the
655− -- stored document. Use with care, as this could
656− -- result in data loss.
657− | ForceVersion ExternalDocVersion
658− -- ^ The document will always be indexed and the
659− -- given version will be the new version. This is
660− -- typically used for correcting errors. Use with
661− -- care, as this could result in data loss.
662− deriving (Show, Eq, Generic, Ord)
664−{-| 'DocumentParent' is used to specify a parent document.
666−newtype DocumentParent = DocumentParent DocId
667− deriving (Eq, Show, Generic, Typeable)
669−{-| 'IndexDocumentSettings' are special settings supplied when indexing
670−a document. For the best backwards compatiblity when new fields are
671−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
673−data IndexDocumentSettings =
674− IndexDocumentSettings { idsVersionControl :: VersionControl
675− , idsParent :: Maybe DocumentParent
676− } deriving (Eq, Show, Generic, Typeable)
678−{-| Reasonable default settings. Chooses no version control and no parent.
680−defaultIndexDocumentSettings :: IndexDocumentSettings
681−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
683−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
684− dependent with later sorts acting as tie-breakers for earlier sorts.
686−type Sort = [SortSpec]
688−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
689− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
690− 'DistanceUnit' to express "nearness" to a single geographical point as a
693−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
695−data SortSpec = DefaultSortSpec DefaultSort
696− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show, Generic, Typeable)
698−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
699− 'mkSort' convenience function for when you want to specify only the most
702−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
705− DefaultSort { sortFieldName :: FieldName
706− , sortOrder :: SortOrder
708− , ignoreUnmapped :: Bool
709− , sortMode :: Maybe SortMode
710− , missingSort :: Maybe Missing
711− , nestedFilter :: Maybe Filter } deriving (Eq, Show, Generic, Typeable)
713−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
714− encoded into "asc" or "desc" when turned into JSON.
716−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
718−data SortOrder = Ascending
719− | Descending deriving (Eq, Show, Generic, Typeable)
721−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
722− sorted last, first, or using a custom value as a substitute.
724−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
726−data Missing = LastMissing
728− | CustomMissing Text deriving (Eq, Show, Generic, Typeable)
730−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
732−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
734−data SortMode = SortMin
737− | SortAvg deriving (Eq, Show, Generic, Typeable)
739−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
740− that you can concisely describe the usual kind of 'SortSpec's you want.
742−mkSort :: FieldName -> SortOrder -> DefaultSort
743−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
745−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
746− 'Query's cannot be cached.
748−type Cache = Bool -- caching on/off
749−defaultCache :: Cache
752−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
754−type PrefixValue = Text
756−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
757− JSON encoding baked in. Used all over the place.
759−data BooleanOperator = And | Or deriving (Eq, Show, Generic, Typeable)
761−{-| 'ShardCount' is part of 'IndexSettings'
763−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
765−{-| 'ReplicaCount' is part of 'IndexSettings'
767−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
769−{-| 'IndexName' is used to describe which index to query/create/delete
771−newtype IndexName = IndexName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
773−{-| 'TemplateName' is used to describe which template to query/create/delete
775−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
777−{-| 'TemplatePattern' represents a pattern which is matched against index names
779−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
781−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
782− the data in the indices.
784−newtype MappingName = MappingName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
786−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
787− Can be set by the user or created by ES itself. Often used in client
788− functions for poking at specific documents.
790−newtype DocId = DocId Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
792−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
794−newtype QueryString = QueryString Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
796−{-| 'FieldName' is used all over the place wherever a specific field within
797− a document needs to be specified, usually in 'Query's or 'Filter's.
799−newtype FieldName = FieldName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
802−{-| 'Script' is often used in place of 'FieldName' to specify more
409+ , AnalyzerDefinition(..)
803−complex ways of extracting a value from a document.
410+ , TokenizerDefinition(..)
804−-}
411+ , TokenFilterDefinition(..)
805−newtype Script = Script { scriptText :: Text } deriving (Eq, Show, Generic, Typeable)
412+ , CharFilterDefinition(..)
807−{-| 'CacheName' is used in 'RegexpFilter' for describing the
414+ , TokenChar(..)
808− 'CacheKey' keyed caching behavior.
415+ , Shingle(..)
809−-}
416+ , Language(..)
810−newtype CacheName = CacheName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
417+ ) where
812−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
419+import Bloodhound.Import
814−newtype CacheKey =
421+import Database.Bloodhound.Internal.Aggregation
815− CacheKey Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
422+import Database.Bloodhound.Internal.Analysis
816−newtype Existence =
423+import Database.Bloodhound.Internal.Client
817− Existence Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
424+import Database.Bloodhound.Internal.Highlight
818−newtype NullValue =
425+import Database.Bloodhound.Internal.Newtypes
819− NullValue Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
426+import Database.Bloodhound.Internal.Query
820−newtype CutoffFrequency =
427+import Database.Bloodhound.Internal.Sort
821− CutoffFrequency Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
428+import Database.Bloodhound.Internal.Suggest
823− Analyzer Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
824−newtype MaxExpansions =
825− MaxExpansions Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
827−{-| 'Lenient', if set to true, will cause format based failures to be
828− ignored. I don't know what the bloody default is, Elasticsearch
829− documentation didn't say what it was. Let me know if you figure it out.
832− Lenient Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
834− Tiebreaker Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
836− Boost Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
838− BoostTerms Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
840−{-| 'MinimumMatch' controls how many should clauses in the bool query should
841− match. Can be an absolute value (2) or a percentage (30%) or a
842− combination of both.
844−newtype MinimumMatch =
845− MinimumMatch Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
846−newtype DisableCoord =
847− DisableCoord Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
848−newtype IgnoreTermFrequency =
849− IgnoreTermFrequency Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
850−newtype MinimumTermFrequency =
851− MinimumTermFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
852−newtype MaxQueryTerms =
853− MaxQueryTerms Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
855− Fuzziness Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
857−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
858−newtype PrefixLength =
859− PrefixLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
861− TypeName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
862−newtype PercentMatch =
863− PercentMatch Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
865− StopWord Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
867− QueryPath Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
869−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
870− heavy, because all terms in the index need to be examined, just in case
871− they match. Leading wildcards can be disabled by setting
872− 'AllowLeadingWildcard' to false. -}
873−newtype AllowLeadingWildcard =
874− AllowLeadingWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
875−newtype LowercaseExpanded =
876− LowercaseExpanded Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
877−newtype EnablePositionIncrements =
878− EnablePositionIncrements Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
880−{-| By default, wildcard terms in a query are not analyzed.
881− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
883−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
885−{-| 'GeneratePhraseQueries' defaults to false.
887−newtype GeneratePhraseQueries =
888− GeneratePhraseQueries Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
890−{-| 'Locale' is used for string conversions - defaults to ROOT.
892−newtype Locale = Locale Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
893−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
894−newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
896−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
897− phrase matches. Default is 0.
899−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
900−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
901−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
903−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
904−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
906{-| 'unpackId' is a silly convenience function that gets used once.
430{-| 'unpackId' is a silly convenience function that gets used once.
@@ -909,8 +433,6 @@ unpackId :: DocId -> Text
909unpackId (DocId docId) = docId
433unpackId (DocId docId) = docId
911type TrackSortScores = Bool
435type TrackSortScores = Bool
912−newtype From = From Int deriving (Eq, Show, Generic, ToJSON)
913−newtype Size = Size Int deriving (Eq, Show, Generic, ToJSON)
915data Search = Search { queryBody :: Maybe Query
437data Search = Search { queryBody :: Maybe Query
916 , filterBody :: Maybe Filter
438 , filterBody :: Maybe Filter
@@ -922,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
922 , from :: From
444 , from :: From
923 , size :: Size
445 , size :: Size
924 , searchType :: SearchType
446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
925 , fields :: Maybe [FieldName]
448 , fields :: Maybe [FieldName]
449+ , scriptFields :: Maybe ScriptFields
926− , source :: Maybe Source } deriving (Eq, Show, Generic, Typeable)
450+ , source :: Maybe Source
451+ , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
452+ } deriving (Eq, Show)
455+instance ToJSON Search where
456+ toJSON (Search mquery sFilter sort searchAggs
457+ highlight sTrackSortScores sFrom sSize _ sAfter sFields
458+ sScriptFields sSource sSuggest) =
459+ omitNulls [ "query" .= query'
461+ , "aggregations" .= searchAggs
462+ , "highlight" .= highlight
465+ , "track_scores" .= sTrackSortScores
466+ , "search_after" .= sAfter
467+ , "fields" .= sFields
468+ , "script_fields" .= sScriptFields
469+ , "_source" .= sSource
470+ , "suggest" .= sSuggest]
472+ where query' = case sFilter of
477+ $ mkBoolQuery (maybeToList mquery)
928data SearchType = SearchTypeQueryThenFetch
480data SearchType = SearchTypeQueryThenFetch
929 | SearchTypeDfsQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
932− | SearchTypeQueryAndFetch
933− | SearchTypeDfsQueryAndFetch
934− deriving (Eq, Show, Generic, Typeable)
482+ deriving (Eq, Show)
936data Source =
484data Source =
938 | SourcePatterns PatternOrPatterns
486 | SourcePatterns PatternOrPatterns
939 | SourceIncludeExclude Include Exclude
487 | SourceIncludeExclude Include Exclude
940− deriving (Show, Eq, Generic, Typeable)
488+ deriving (Eq, Show)
942−data PatternOrPatterns = PopPattern Pattern
943− | PopPatterns [Pattern] deriving (Eq, Show, Generic, Typeable)
945−data Include = Include [Pattern] deriving (Eq, Show, Generic, Typeable)
946−data Exclude = Exclude [Pattern] deriving (Eq, Show, Generic, Typeable)
948−newtype Pattern = Pattern Text deriving (Eq, Show, Generic, Typeable)
950−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
951− , highlightFields :: [FieldHighlight]
952− } deriving (Show, Eq, Generic, Typeable)
954−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
955− deriving (Show, Eq, Generic, Typeable)
958−data HighlightSettings = Plain PlainHighlight
959− | Postings PostingsHighlight
960− | FastVector FastVectorHighlight
961− deriving (Show, Eq, Generic, Typeable)
962−data PlainHighlight =
963− PlainHighlight { plainCommon :: Maybe CommonHighlight
964− , plainNonPost :: Maybe NonPostings } deriving (Show, Eq, Generic, Typeable)
966− -- This requires that index_options are set to 'offset' in the mapping.
967−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq, Generic, Typeable)
969−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
970−data FastVectorHighlight =
971− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
972− , fvNonPostSettings :: Maybe NonPostings
973− , boundaryChars :: Maybe Text
974− , boundaryMaxScan :: Maybe Int
975− , fragmentOffset :: Maybe Int
976− , matchedFields :: [Text]
977− , phraseLimit :: Maybe Int
978− } deriving (Show, Eq, Generic, Typeable)
980−data CommonHighlight =
981− CommonHighlight { order :: Maybe Text
982− , forceSource :: Maybe Bool
983− , tag :: Maybe HighlightTag
984− , encoder :: Maybe HighlightEncoder
985− , noMatchSize :: Maybe Int
986− , highlightQuery :: Maybe Query
987− , requireFieldMatch :: Maybe Bool
988− } deriving (Show, Eq, Generic, Typeable)
990−-- Settings that are only applicable to FastVector and Plain highlighters.
992− NonPostings { fragmentSize :: Maybe Int
993− , numberOfFragments :: Maybe Int} deriving (Show, Eq, Generic, Typeable)
995−data HighlightEncoder = DefaultEncoder
997− deriving (Show, Eq, Generic, Typeable)
999−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1000−data HighlightTag = TagSchema Text
1001− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1002− deriving (Show, Eq, Generic, Typeable)
1006− TermQuery Term (Maybe Boost)
1007− | TermsQuery Text (NonEmpty Text)
1008− | QueryMatchQuery MatchQuery
1009− | QueryMultiMatchQuery MultiMatchQuery
1010− | QueryBoolQuery BoolQuery
1011− | QueryBoostingQuery BoostingQuery
1012− | QueryCommonTermsQuery CommonTermsQuery
1013− | ConstantScoreFilter Filter Boost
1014− | ConstantScoreQuery Query Boost
1015− | QueryDisMaxQuery DisMaxQuery
1016− | QueryFilteredQuery FilteredQuery
1017− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1018− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1019− | QueryFuzzyQuery FuzzyQuery
1020− | QueryHasChildQuery HasChildQuery
1021− | QueryHasParentQuery HasParentQuery
1022− | IdsQuery MappingName [DocId]
1023− | QueryIndicesQuery IndicesQuery
1024− | MatchAllQuery (Maybe Boost)
1025− | QueryMoreLikeThisQuery MoreLikeThisQuery
1026− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1027− | QueryNestedQuery NestedQuery
1028− | QueryPrefixQuery PrefixQuery
1029− | QueryQueryStringQuery QueryStringQuery
1030− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1031− | QueryRangeQuery RangeQuery
1032− | QueryRegexpQuery RegexpQuery
1033− deriving (Eq, Show, Generic, Typeable)
1036− RegexpQuery { regexpQueryField :: FieldName
1037− , regexpQuery :: Regexp
1038− , regexpQueryFlags :: RegexpFlags
1039− , regexpQueryBoost :: Maybe Boost
1040− } deriving (Eq, Show, Generic, Typeable)
1043− RangeQuery { rangeQueryField :: FieldName
1044− , rangeQueryRange :: RangeValue
1045− , rangeQueryBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1047−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1048−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1050−data SimpleQueryStringQuery =
1051− SimpleQueryStringQuery
1052− { simpleQueryStringQuery :: QueryString
1053− , simpleQueryStringField :: Maybe FieldOrFields
1054− , simpleQueryStringOperator :: Maybe BooleanOperator
1055− , simpleQueryStringAnalyzer :: Maybe Analyzer
1056− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1057− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1058− , simpleQueryStringLocale :: Maybe Locale
1059− } deriving (Eq, Show, Generic, Typeable)
1061−data SimpleQueryFlag =
1066− | SimpleQueryPrefix
1067− | SimpleQueryPhrase
1068− | SimpleQueryPrecedence
1069− | SimpleQueryEscape
1070− | SimpleQueryWhitespace
1073− | SimpleQuerySlop deriving (Eq, Show, Generic, Typeable)
1075−-- use_dis_max and tie_breaker when fields are plural?
1076−data QueryStringQuery =
1078− { queryStringQuery :: QueryString
1079− , queryStringDefaultField :: Maybe FieldName
1080− , queryStringOperator :: Maybe BooleanOperator
1081− , queryStringAnalyzer :: Maybe Analyzer
1082− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1083− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1084− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1085− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1086− , queryStringFuzziness :: Maybe Fuzziness
1087− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1088− , queryStringPhraseSlop :: Maybe PhraseSlop
1089− , queryStringBoost :: Maybe Boost
1090− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1091− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1092− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1093− , queryStringLenient :: Maybe Lenient
1094− , queryStringLocale :: Maybe Locale
1095− } deriving (Eq, Show, Generic, Typeable)
1097−mkQueryStringQuery :: QueryString -> QueryStringQuery
1098−mkQueryStringQuery qs =
1099− QueryStringQuery qs Nothing Nothing
1100− Nothing Nothing Nothing Nothing
1101− Nothing Nothing Nothing Nothing
1102− Nothing Nothing Nothing Nothing
1105−data FieldOrFields = FofField FieldName
1106− | FofFields (NonEmpty FieldName) deriving (Eq, Show, Generic, Typeable)
1110− { prefixQueryField :: FieldName
1111− , prefixQueryPrefixValue :: Text
1112− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1116− { nestedQueryPath :: QueryPath
1117− , nestedQueryScoreType :: ScoreType
1118− , nestedQuery :: Query } deriving (Eq, Show, Generic, Typeable)
1120−data MoreLikeThisFieldQuery =
1121− MoreLikeThisFieldQuery
1122− { moreLikeThisFieldText :: Text
1123− , moreLikeThisFieldFields :: FieldName
1124− -- default 0.3 (30%)
1125− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1126− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1127− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1128− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1129− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1130− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1131− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1132− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1133− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1134− , moreLikeThisFieldBoost :: Maybe Boost
1135− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1136− } deriving (Eq, Show, Generic, Typeable)
1138−data MoreLikeThisQuery =
1140− { moreLikeThisText :: Text
1141− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1142− -- default 0.3 (30%)
1143− , moreLikeThisPercentMatch :: Maybe PercentMatch
1144− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1145− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1146− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1147− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1148− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1149− , moreLikeThisMinWordLength :: Maybe MinWordLength
1150− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1151− , moreLikeThisBoostTerms :: Maybe BoostTerms
1152− , moreLikeThisBoost :: Maybe Boost
1153− , moreLikeThisAnalyzer :: Maybe Analyzer
1154− } deriving (Eq, Show, Generic, Typeable)
1158− { indicesQueryIndices :: [IndexName]
1159− , indicesQuery :: Query
1161− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show, Generic, Typeable)
1163−data HasParentQuery =
1165− { hasParentQueryType :: TypeName
1166− , hasParentQuery :: Query
1167− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1169−data HasChildQuery =
1171− { hasChildQueryType :: TypeName
1172− , hasChildQuery :: Query
1173− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1179− | ScoreTypeNone deriving (Eq, Show, Generic, Typeable)
1182− FuzzyQuery { fuzzyQueryField :: FieldName
1183− , fuzzyQueryValue :: Text
1184− , fuzzyQueryPrefixLength :: PrefixLength
1185− , fuzzyQueryMaxExpansions :: MaxExpansions
1186− , fuzzyQueryFuzziness :: Fuzziness
1187− , fuzzyQueryBoost :: Maybe Boost
1188− } deriving (Eq, Show, Generic, Typeable)
1190−data FuzzyLikeFieldQuery =
1191− FuzzyLikeFieldQuery
1192− { fuzzyLikeField :: FieldName
1193− -- anaphora is good for the soul.
1194− , fuzzyLikeFieldText :: Text
1195− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1196− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1197− , fuzzyLikeFieldFuzziness :: Fuzziness
1198− , fuzzyLikeFieldPrefixLength :: PrefixLength
1199− , fuzzyLikeFieldBoost :: Boost
1200− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1201− } deriving (Eq, Show, Generic, Typeable)
1203−data FuzzyLikeThisQuery =
1205− { fuzzyLikeFields :: [FieldName]
1206− , fuzzyLikeText :: Text
1207− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1208− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1209− , fuzzyLikeFuzziness :: Fuzziness
1210− , fuzzyLikePrefixLength :: PrefixLength
1211− , fuzzyLikeBoost :: Boost
1212− , fuzzyLikeAnalyzer :: Maybe Analyzer
1213− } deriving (Eq, Show, Generic, Typeable)
1215−data FilteredQuery =
1217− { filteredQuery :: Query
1218− , filteredFilter :: Filter } deriving (Eq, Show, Generic, Typeable)
1221− DisMaxQuery { disMaxQueries :: [Query]
1223− , disMaxTiebreaker :: Tiebreaker
1224− , disMaxBoost :: Maybe Boost
1225− } deriving (Eq, Show, Generic, Typeable)
1228− MatchQuery { matchQueryField :: FieldName
1229− , matchQueryQueryString :: QueryString
1230− , matchQueryOperator :: BooleanOperator
1231− , matchQueryZeroTerms :: ZeroTermsQuery
1232− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1233− , matchQueryMatchType :: Maybe MatchQueryType
1234− , matchQueryAnalyzer :: Maybe Analyzer
1235− , matchQueryMaxExpansions :: Maybe MaxExpansions
1236− , matchQueryLenient :: Maybe Lenient
1237− , matchQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1239−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1240− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1242−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1243−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1245−data MatchQueryType =
490+instance ToJSON Source where
1246− MatchPhrase
491+ toJSON NoSource = toJSON False
1247− | MatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
492+ toJSON (SourcePatterns patterns) = toJSON patterns
1248−
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1249−data MultiMatchQuery =
1250− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1251− , multiMatchQueryString :: QueryString
1252− , multiMatchQueryOperator :: BooleanOperator
1253− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1254− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1255− , multiMatchQueryType :: Maybe MultiMatchQueryType
1256− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1257− , multiMatchQueryAnalyzer :: Maybe Analyzer
1258− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1259− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show, Generic, Typeable)
1261−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1262− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1263− make a 'MultiMatchQuery'.
1266−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1267−mkMultiMatchQuery matchFields query =
1268− MultiMatchQuery matchFields query
1269− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1271−data MultiMatchQueryType =
1272− MultiMatchBestFields
1273− | MultiMatchMostFields
1274− | MultiMatchCrossFields
1276− | MultiMatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1279− BoolQuery { boolQueryMustMatch :: [Query]
1280− , boolQueryMustNotMatch :: [Query]
1281− , boolQueryShouldMatch :: [Query]
1282− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1283− , boolQueryBoost :: Maybe Boost
1284− , boolQueryDisableCoord :: Maybe DisableCoord
1285− } deriving (Eq, Show, Generic, Typeable)
1287−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1288−mkBoolQuery must mustNot should =
1289− BoolQuery must mustNot should Nothing Nothing Nothing
1291−data BoostingQuery =
1292− BoostingQuery { positiveQuery :: Query
1293− , negativeQuery :: Query
1294− , negativeBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1296−data CommonTermsQuery =
1297− CommonTermsQuery { commonField :: FieldName
1298− , commonQuery :: QueryString
1299− , commonCutoffFrequency :: CutoffFrequency
1300− , commonLowFreqOperator :: BooleanOperator
1301− , commonHighFreqOperator :: BooleanOperator
1302− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1303− , commonBoost :: Maybe Boost
1304− , commonAnalyzer :: Maybe Analyzer
1305− , commonDisableCoord :: Maybe DisableCoord
1306− } deriving (Eq, Show, Generic, Typeable)
1308−data CommonMinimumMatch =
1309− CommonMinimumMatchHighLow MinimumMatchHighLow
1310− | CommonMinimumMatch MinimumMatch
1311− deriving (Eq, Show, Generic, Typeable)
1313−data MinimumMatchHighLow =
1314− MinimumMatchHighLow { lowFreq :: MinimumMatch
1315− , highFreq :: MinimumMatch } deriving (Eq, Show, Generic, Typeable)
1317−data Filter = AndFilter [Filter] Cache
1318− | OrFilter [Filter] Cache
1319− | NotFilter Filter Cache
1321− | BoolFilter BoolMatch
1322− | ExistsFilter FieldName -- always cached
1323− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1324− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1325− | GeoDistanceRangeFilter GeoPoint DistanceRange
1326− | GeoPolygonFilter FieldName [LatLon]
1327− | IdsFilter MappingName [DocId]
1329− | MissingFilter FieldName Existence NullValue
1330− | PrefixFilter FieldName PrefixValue Cache
1331− | QueryFilter Query Cache
1332− | RangeFilter FieldName RangeValue RangeExecution Cache
1333− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1334− | TermFilter Term Cache
1335− deriving (Eq, Show, Generic, Typeable)
1337−data ZeroTermsQuery = ZeroTermsNone
1338− | ZeroTermsAll deriving (Eq, Show, Generic, Typeable)
1340−data RangeExecution = RangeExecutionIndex
1341− | RangeExecutionFielddata deriving (Eq, Show, Generic, Typeable)
1343−newtype Regexp = Regexp Text deriving (Eq, Show, Generic, Typeable, FromJSON)
1345−data RegexpFlags = AllRegexpFlags
1347− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show, Generic, Typeable)
1349−data RegexpFlag = AnyString
1354− | Interval deriving (Eq, Show, Generic, Typeable)
1356−newtype LessThan = LessThan Double deriving (Eq, Show, Generic, Typeable)
1357−newtype LessThanEq = LessThanEq Double deriving (Eq, Show, Generic, Typeable)
1358−newtype GreaterThan = GreaterThan Double deriving (Eq, Show, Generic, Typeable)
1359−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show, Generic, Typeable)
1361−newtype LessThanD = LessThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1362−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1363−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1364−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1366−data RangeValue = RangeDateLte LessThanEqD
1367− | RangeDateLt LessThanD
1368− | RangeDateGte GreaterThanEqD
1369− | RangeDateGt GreaterThanD
1370− | RangeDateGtLt GreaterThanD LessThanD
1371− | RangeDateGteLte GreaterThanEqD LessThanEqD
1372− | RangeDateGteLt GreaterThanEqD LessThanD
1373− | RangeDateGtLte GreaterThanD LessThanEqD
1374− | RangeDoubleLte LessThanEq
1375− | RangeDoubleLt LessThan
1376− | RangeDoubleGte GreaterThanEq
1377− | RangeDoubleGt GreaterThan
1378− | RangeDoubleGtLt GreaterThan LessThan
1379− | RangeDoubleGteLte GreaterThanEq LessThanEq
1380− | RangeDoubleGteLt GreaterThanEq LessThan
1381− | RangeDoubleGtLte GreaterThan LessThanEq
1382− deriving (Eq, Show, Generic, Typeable)
1384−rangeValueToPair :: RangeValue -> [Pair]
1385−rangeValueToPair rv = case rv of
1386− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1387− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1388− RangeDateLt (LessThanD t) -> ["lt" .= t]
1389− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1390− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1391− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1392− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1393− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1394− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1395− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1396− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1397− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1398− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1399− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1400− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1401− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1403−data Term = Term { termField :: Text
1404− , termValue :: Text } deriving (Eq, Show, Generic, Typeable)
1406−data BoolMatch = MustMatch Term Cache
1407− | MustNotMatch Term Cache
1408− | ShouldMatch [Term] Cache deriving (Eq, Show, Generic, Typeable)
1410−-- "memory" or "indexed"
1411−data GeoFilterType = GeoFilterMemory
1412− | GeoFilterIndexed deriving (Eq, Show, Generic, Typeable)
1414−data LatLon = LatLon { lat :: Double
1415− , lon :: Double } deriving (Eq, Show, Generic, Typeable)
1417−data GeoBoundingBox =
1418− GeoBoundingBox { topLeft :: LatLon
1419− , bottomRight :: LatLon } deriving (Eq, Show, Generic, Typeable)
1421−data GeoBoundingBoxConstraint =
495+data PatternOrPatterns = PopPattern Pattern
1422− GeoBoundingBoxConstraint { geoBBField :: FieldName
1423− , constraintBox :: GeoBoundingBox
1424− , bbConstraintcache :: Cache
1425− , geoType :: GeoFilterType
1426− } deriving (Eq, Show, Generic, Typeable)
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1428−data GeoPoint =
498+instance ToJSON PatternOrPatterns where
1429− GeoPoint { geoField :: FieldName
499+ toJSON (PopPattern pattern) = toJSON pattern
1430− , latLon :: LatLon} deriving (Eq, Show, Generic, Typeable)
500+ toJSON (PopPatterns patterns) = toJSON patterns
1432−data DistanceUnit = Miles
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
1433− | Yards
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1440− | NauticalMiles deriving (Eq, Show, Generic, Typeable)
1442−data DistanceType = Arc
505+instance ToJSON Include where
1443− | SloppyArc -- doesn't exist <1.0
506+ toJSON (Include patterns) = toJSON patterns
1444− | Plane deriving (Eq, Show, Generic, Typeable)
1446−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
508+instance ToJSON Exclude where
1447− | NoOptimizeBbox deriving (Eq, Show, Generic, Typeable)
509+ toJSON (Exclude patterns) = toJSON patterns
1449−data Distance =
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1450− Distance { coefficient :: Double
1451− , unit :: DistanceUnit } deriving (Eq, Show, Generic, Typeable)
1453−data DistanceRange =
513+instance ToJSON Pattern where
1454− DistanceRange { distanceFrom :: Distance
514+ toJSON (Pattern pattern) = toJSON pattern
1455− , distanceTo :: Distance } deriving (Eq, Show, Generic, Typeable)
1457data SearchResult a =
516data SearchResult a =
1458 SearchResult { took :: Int
517 SearchResult { took :: Int
@@ -1460,2034 +519,12 @@ data SearchResult a =
1460 , shards :: ShardResult
519 , shards :: ShardResult
1461 , searchHits :: SearchHits a
520 , searchHits :: SearchHits a
1462 , aggregations :: Maybe AggregationResults
521 , aggregations :: Maybe AggregationResults
1463− , scrollId :: Maybe ScrollId } deriving (Eq, Show, Generic, Typeable)
522+ , scrollId :: Maybe ScrollId
1464−
523+ -- ^ Only one Suggestion request / response per
1465−newtype ScrollId = ScrollId Text deriving (Eq, Show, Generic, Ord, ToJSON, FromJSON)
524+ -- Search is supported.
1466−
525+ , suggest :: Maybe NamedSuggestionResponse
1467−type Score = Maybe Double
526+ }
1468−
527+ deriving (Eq, Show)
1470− SearchHits { hitsTotal :: Int
1471− , maxScore :: Score
1472− , hits :: [Hit a] } deriving (Eq, Show, Generic, Typeable)
1475−instance Monoid (SearchHits a) where
1476− mempty = SearchHits 0 Nothing mempty
1477− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1478− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1482− Hit { hitIndex :: IndexName
1483− , hitType :: MappingName
1484− , hitDocId :: DocId
1485− , hitScore :: Score
1486− , hitSource :: Maybe a
1487− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show, Generic, Typeable)
1490− ShardResult { shardTotal :: Int
1491− , shardsSuccessful :: Int
1492− , shardsFailed :: Int } deriving (Eq, Show, Generic, Typeable)
1494−type HitHighlight = M.Map Text [Text]
1496−showText :: Show a => a -> Text
1497−showText = T.pack . show
1499−readMay :: Read a => String -> Maybe a
1500−readMay s = case reads s of
1501− (a, ""):_ -> Just a
1504−parseReadText :: Read a => Text -> Parser a
1505−parseReadText = maybe mzero return . readMay . T.unpack
1507−type Aggregations = M.Map Text Aggregation
1509−emptyAggregations :: Aggregations
1510−emptyAggregations = M.empty
1512−mkAggregations :: Text -> Aggregation -> Aggregations
1513−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1515−data TermOrder = TermOrder{ termSortField :: Text
1516− , termSortOrder :: SortOrder } deriving (Eq, Show, Generic, Typeable)
1518−data TermInclusion = TermInclusion Text
1519− | TermPattern Text Text deriving (Eq, Show, Generic, Typeable)
1521−data CollectionMode = BreadthFirst
1522− | DepthFirst deriving (Eq, Show, Generic, Typeable)
1524−data ExecutionHint = Ordinals
1526− | GlobalOrdinalsHash
1527− | GlobalOrdinalsLowCardinality
1528− | Map deriving (Eq, Show, Generic, Typeable)
1530−data TimeInterval = Weeks
1534− | Seconds deriving (Eq)
1536−data Interval = Year
1544− | FractionalInterval Float TimeInterval deriving (Eq, Show, Generic, Typeable)
1546−data Aggregation = TermsAgg TermsAggregation
1547− | DateHistogramAgg DateHistogramAggregation
1548− | ValueCountAgg ValueCountAggregation
1549− | FilterAgg FilterAggregation
1550− | DateRangeAgg DateRangeAggregation
1551− | MissingAgg MissingAggregation deriving (Eq, Show, Generic, Typeable)
1553−data MissingAggregation = MissingAggregation
1555− } deriving (Eq, Show, Generic, Typeable)
1557−data TermsAggregation = TermsAggregation { term :: Either Text Text
1558− , termInclude :: Maybe TermInclusion
1559− , termExclude :: Maybe TermInclusion
1560− , termOrder :: Maybe TermOrder
1561− , termMinDocCount :: Maybe Int
1562− , termSize :: Maybe Int
1563− , termShardSize :: Maybe Int
1564− , termCollectMode :: Maybe CollectionMode
1565− , termExecutionHint :: Maybe ExecutionHint
1566− , termAggs :: Maybe Aggregations
1567− } deriving (Eq, Show, Generic, Typeable)
1569−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1570− , dateInterval :: Interval
1571− , dateFormat :: Maybe Text
1572− -- pre and post deprecated in 1.5
1573− , datePreZone :: Maybe Text
1574− , datePostZone :: Maybe Text
1575− , datePreOffset :: Maybe Text
1576− , datePostOffset :: Maybe Text
1577− , dateAggs :: Maybe Aggregations
1578− } deriving (Eq, Show, Generic, Typeable)
1581−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1582− , draFormat :: Maybe Text
1583− , draRanges :: NonEmpty DateRangeAggRange
1584− } deriving (Eq, Show, Generic, Typeable)
1586−data DateRangeAggRange = DateRangeFrom DateMathExpr
1587− | DateRangeTo DateMathExpr
1588− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Show, Generic, Typeable)
1590−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1591−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Show, Generic, Typeable)
1594−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1595−data DateMathAnchor = DMNow
1596− | DMDate Day deriving (Eq, Show, Generic, Typeable)
1598−data DateMathModifier = AddTime Int DateMathUnit
1599− | SubtractTime Int DateMathUnit
1600− | RoundDownTo DateMathUnit deriving (Eq, Show, Generic, Typeable)
1602−data DateMathUnit = DMYear
1608− | DMSecond deriving (Eq, Show, Generic, Typeable)
1610−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1611−data ValueCountAggregation = FieldValueCount FieldName
1612− | ScriptValueCount Script deriving (Eq, Show, Generic, Typeable)
1614−-- | Single-bucket filter aggregations. See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html#search-aggregations-bucket-filter-aggregation> for more information.
1615−data FilterAggregation = FilterAggregation { faFilter :: Filter
1616− , faAggs :: Maybe Aggregations} deriving (Eq, Show, Generic, Typeable)
1618−mkTermsAggregation :: Text -> TermsAggregation
1619−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1621−mkTermsScriptAggregation :: Text -> TermsAggregation
1622−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1624−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1625−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1627−instance ToJSON Version where
1628− toJSON Version {..} = object ["number" .= number
1629− ,"build_hash" .= build_hash
1630− ,"build_timestamp" .= build_timestamp
1631− ,"build_snapshot" .= build_snapshot
1632− ,"lucene_version" .= lucene_version]
1634−instance FromJSON Version where
1635− parseJSON = withObject "Version" parse
1636− where parse o = Version
1638− <*> o .: "build_hash"
1639− <*> o .: "build_timestamp"
1640− <*> o .: "build_snapshot"
1641− <*> o .: "lucene_version"
1643−instance ToJSON TermOrder where
1644− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1646−instance ToJSON TermInclusion where
1647− toJSON (TermInclusion x) = toJSON x
1648− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1651−instance ToJSON CollectionMode where
1652− toJSON BreadthFirst = "breadth_first"
1653− toJSON DepthFirst = "depth_first"
1655−instance ToJSON ExecutionHint where
1656− toJSON Ordinals = "ordinals"
1657− toJSON GlobalOrdinals = "global_ordinals"
1658− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1659− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1662−instance ToJSON Interval where
1663− toJSON Year = "year"
1664− toJSON Quarter = "quarter"
1665− toJSON Month = "month"
1666− toJSON Week = "week"
1668− toJSON Hour = "hour"
1669− toJSON Minute = "minute"
1670− toJSON Second = "second"
1671− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1673−instance Show TimeInterval where
1680−instance ToJSON Aggregation where
1681− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1682− omitNulls ["terms" .= omitNulls [ toJSON' term,
1683− "include" .= include,
1684− "exclude" .= exclude,
1686− "min_doc_count" .= minDocCount,
1688− "shard_size" .= shardSize,
1689− "collect_mode" .= collectMode,
1690− "execution_hint" .= executionHint
1692− "aggs" .= termAggs ]
1694− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1696− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1697− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1698− "interval" .= interval,
1699− "format" .= format,
1700− "pre_zone" .= preZone,
1701− "post_zone" .= postZone,
1702− "pre_offset" .= preOffset,
1703− "post_offset" .= postOffset
1705− "aggs" .= dateHistoAggs ]
1706− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1707− where v = case a of
1708− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1709− (ScriptValueCount (Script s)) -> object ["script" .= s]
1710− toJSON (FilterAgg (FilterAggregation filt ags)) =
1711− omitNulls [ "filter" .= filt
1713− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1715− toJSON (MissingAgg (MissingAggregation{..})) =
1716− object ["missing" .= object ["field" .= maField]]
1718−instance ToJSON DateRangeAggregation where
1719− toJSON DateRangeAggregation {..} =
1720− omitNulls [ "field" .= draField
1721− , "format" .= draFormat
1722− , "ranges" .= toList draRanges
1725−instance ToJSON DateRangeAggRange where
1726− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1727− toJSON (DateRangeTo e) = object [ "to" .= e ]
1728− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1730−instance ToJSON DateMathExpr where
1731− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1732− where fmtA DMNow = "now"
1733− fmtA (DMDate date) = case toGregorian date of
1734− (y,m,d) -> showText y <> "-" <>
1735− showText m <> "-" <>
1737− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1738− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1739− fmtMod (RoundDownTo u) = "/" <> fmtU u
1745− fmtU DMMinute = "m"
1746− fmtU DMSecond = "s"
1749−type AggregationResults = M.Map Text Value
1751−class BucketAggregation a where
1752− key :: a -> BucketValue
1753− docCount :: a -> Int
1754− aggs :: a -> Maybe AggregationResults
1757−data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1759−data BucketValue = TextValue Text
1760− | ScientificValue Scientific
1761− | BoolValue Bool deriving (Show)
1763−data TermsResult = TermsResult { termKey :: BucketValue
1764− , termsDocCount :: Int
1765− , termsAggs :: Maybe AggregationResults } deriving (Show)
1767−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1768− , dateKeyStr :: Maybe Text
1769− , dateDocCount :: Int
1770− , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1772−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1773− , dateRangeFrom :: Maybe UTCTime
1774− , dateRangeFromAsString :: Maybe Text
1775− , dateRangeTo :: Maybe UTCTime
1776− , dateRangeToAsString :: Maybe Text
1777− , dateRangeDocCount :: Int
1778− , dateRangeAggs :: Maybe AggregationResults } deriving (Show, Eq, Generic, Typeable)
1780−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1781−toTerms t a = M.lookup t a >>= deserialize
1782− where deserialize = parseMaybe parseJSON
1784−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1785−toDateHistogram t a = M.lookup t a >>= deserialize
1786− where deserialize = parseMaybe parseJSON
1788−instance BucketAggregation TermsResult where
1790− docCount = termsDocCount
1793−instance BucketAggregation DateHistogramResult where
1794− key = TextValue . showText . dateKey
1795− docCount = dateDocCount
1796− aggs = dateHistogramAggs
1798−instance BucketAggregation DateRangeResult where
1799− key = TextValue . dateRangeKey
1800− docCount = dateRangeDocCount
1801− aggs = dateRangeAggs
1803−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1804− parseJSON (Object v) = Bucket <$>
1806− parseJSON _ = mempty
1808−instance FromJSON BucketValue where
1809− parseJSON (String t) = return $ TextValue t
1810− parseJSON (Number s) = return $ ScientificValue s
1811− parseJSON (Bool b) = return $ BoolValue b
1812− parseJSON _ = mempty
1814−instance FromJSON TermsResult where
1815− parseJSON (Object v) = TermsResult <$>
1817− v .: "doc_count" <*>
1818− v .:? "aggregations"
1819− parseJSON _ = mempty
1821−instance FromJSON DateHistogramResult where
1822− parseJSON (Object v) = DateHistogramResult <$>
1824− v .:? "key_as_string" <*>
1825− v .: "doc_count" <*>
1826− v .:? "aggregations"
1827− parseJSON _ = mempty
1829−instance FromJSON DateRangeResult where
1830− parseJSON = withObject "DateRangeResult" parse
1831− where parse v = DateRangeResult <$>
1833− (fmap posixMS <$> v .:? "from") <*>
1834− v .:? "from_as_string" <*>
1835− (fmap posixMS <$> v .:? "to") <*>
1836− v .:? "to_as_string" <*>
1837− v .: "doc_count" <*>
1838− v .:? "aggregations"
1840−instance FromJSON POSIXMS where
1841− parseJSON = withScientific "POSIXMS" (return . parse)
1842− where parse n = let n' = truncate n :: Integer
1843− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1845−instance Monoid Filter where
1846− mempty = IdentityFilter
1847− mappend a b = AndFilter [a, b] defaultCache
1849−instance Seminearring Filter where
1850− a <||> b = OrFilter [a, b] defaultCache
1852−instance ToJSON Filter where
1853− toJSON (AndFilter filters cache) =
1855− object [ "filters" .= fmap toJSON filters
1856− , "_cache" .= cache]]
1858− toJSON (OrFilter filters cache) =
1860− object [ "filters" .= fmap toJSON filters
1861− , "_cache" .= cache]]
1863− toJSON (NotFilter notFilter cache) =
1865− object ["filter" .= notFilter
1866− , "_cache" .= cache]]
1868− toJSON (IdentityFilter) =
1869− object ["match_all" .= object []]
1871− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1872− object ["term" .= object base]
1873− where base = [termFilterField .= termFilterValue,
1876− toJSON (ExistsFilter (FieldName fieldName)) =
1877− object ["exists" .= object
1878− ["field" .= fieldName]]
1880− toJSON (BoolFilter boolMatch) =
1881− object ["bool" .= boolMatch]
1883− toJSON (GeoBoundingBoxFilter bbConstraint) =
1884− object ["geo_bounding_box" .= bbConstraint]
1886− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1887− distance distanceType optimizeBbox cache) =
1888− object ["geo_distance" .=
1889− object ["distance" .= distance
1890− , "distance_type" .= distanceType
1891− , "optimize_bbox" .= optimizeBbox
1892− , distanceGeoField .= geoDistLatLon
1893− , "_cache" .= cache]]
1895− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1896− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1897− object ["geo_distance_range" .=
1898− object ["from" .= geoDistRangeDistFrom
1899− , "to" .= drDistanceTo
1900− , gddrField .= drLatLon]]
1902− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1903− object ["geo_polygon" .=
1904− object [geoPolygonFilterField .=
1905− object ["points" .= fmap toJSON latLons]]]
1907− toJSON (IdsFilter (MappingName mappingName) values) =
1909− object ["type" .= mappingName
1910− , "values" .= fmap unpackId values]]
1912− toJSON (LimitFilter limit) =
1913− object ["limit" .= object ["value" .= limit]]
1915− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1916− object ["missing" .=
1917− object ["field" .= fieldName
1918− , "existence" .= existence
1919− , "null_value" .= nullValue]]
1921− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1922− object ["prefix" .=
1923− object [fieldName .= fieldValue
1924− , "_cache" .= cache]]
1926− toJSON (QueryFilter query False) =
1927− object ["query" .= toJSON query ]
1928− toJSON (QueryFilter query True) =
1929− object ["fquery" .=
1930− object [ "query" .= toJSON query
1931− , "_cache" .= True ]]
1933− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1935− object [ fieldName .= object (rangeValueToPair rangeValue)
1936− , "execution" .= rangeExecution
1937− , "_cache" .= cache]]
1939− toJSON (RegexpFilter (FieldName fieldName)
1940− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1941− object ["regexp" .=
1942− object [fieldName .=
1943− object ["value" .= regexText
1944− , "flags" .= flags]
1945− , "_name" .= cacheName
1946− , "_cache" .= cache
1947− , "_cache_key" .= cacheKey]]
1949−instance FromJSON Filter where
1950− parseJSON = withObject "Filter" parse
1951− where parse o = andFilter `taggedWith` "and"
1952− <|> orFilter `taggedWith` "or"
1953− <|> notFilter `taggedWith` "not"
1954− <|> identityFilter `taggedWith` "match_all"
1955− <|> boolFilter `taggedWith` "bool"
1956− <|> existsFilter `taggedWith` "exists"
1957− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
1958− <|> geoDistanceFilter `taggedWith` "geo_distance"
1959− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
1960− <|> geoPolygonFilter `taggedWith` "geo_polygon"
1961− <|> idsFilter `taggedWith` "ids"
1962− <|> limitFilter `taggedWith` "limit"
1963− <|> missingFilter `taggedWith` "missing"
1964− <|> prefixFilter `taggedWith` "prefix"
1965− <|> queryFilter `taggedWith` "query"
1966− <|> fqueryFilter `taggedWith` "fquery"
1967− <|> rangeFilter `taggedWith` "range"
1968− <|> regexpFilter `taggedWith` "regexp"
1969− <|> termFilter `taggedWith` "term"
1970− where taggedWith parser k = parser =<< o .: k
1971− andFilter o = AndFilter <$> o .: "filters"
1972− <*> o .:? "_cache" .!= defaultCache
1973− orFilter o = OrFilter <$> o .: "filters"
1974− <*> o .:? "_cache" .!= defaultCache
1975− notFilter o = NotFilter <$> o .: "filter"
1976− <*> o .: "_cache" .!= defaultCache
1977− identityFilter :: Object -> Parser Filter
1979− | HM.null m = pure IdentityFilter
1980− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
1981− boolFilter = pure . BoolFilter
1982− existsFilter o = ExistsFilter <$> o .: "field"
1983− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1984− geoDistanceFilter o = do
1985− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
1987− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1988− GeoDistanceFilter gp <$> o .: "distance"
1989− <*> o .: "distance_type"
1990− <*> o .: "optimize_bbox"
1991− <*> o .:? "_cache" .!= defaultCache
1992− _ -> fail "Could not find GeoDistanceFilter field name"
1993− geoDistanceRangeFilter o = do
1994− case HM.toList (deleteSeveral ["from", "to"] o) of
1996− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1997− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1998− return (GeoDistanceRangeFilter gp rng)
1999− _ -> fail "Could not find GeoDistanceRangeFilter field name"
2000− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2001− idsFilter o = IdsFilter <$> o .: "type"
2003− limitFilter o = LimitFilter <$> o .: "value"
2004− missingFilter o = MissingFilter <$> o .: "field"
2005− <*> o .: "existence"
2006− <*> o .: "null_value"
2007− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2008− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2009− _ -> fail "Could not parse PrefixFilter"
2011− queryFilter q = pure (QueryFilter q False)
2012− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2013− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2014− [(fn, v)] -> RangeFilter (FieldName fn)
2016− <*> o .: "execution"
2017− <*> o .:? "_cache" .!= defaultCache
2018− _ -> fail "Could not find field name for RangeFilter"
2019− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2020− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2024− <*> o .:? "_cache" .!= defaultCache
2025− <*> o .: "_cache_key"
2026− _ -> fail "Could not find field name for RegexpFilter"
2027− termFilter o = case HM.toList (HM.delete "_cache" o) of
2028− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2029− <$> o .:? "_cache" .!= defaultCache
2030− _ -> fail "Could not find term field for TermFilter"
2032−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2033−fieldTagged f o = case HM.toList o of
2034− [(k, Object o')] -> f (FieldName k) o'
2035− _ -> fail "Expected object with 1 field-named key"
2037−instance ToJSON GeoPoint where
2038− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2039− object [ geoPointField .= geoPointLatLon ]
2042−instance ToJSON Query where
2043− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2045− object [termQueryField .= object merged]]
2047− base = [ "value" .= termQueryValue ]
2048− boosted = maybe [] (return . ("boost" .=)) boost
2049− merged = mappend base boosted
2051− toJSON (TermsQuery fieldName terms) =
2052− object [ "terms" .= object conjoined ]
2053− where conjoined = [fieldName .= terms]
2054− toJSON (IdsQuery idsQueryMappingName docIds) =
2055− object [ "ids" .= object conjoined ]
2056− where conjoined = [ "type" .= idsQueryMappingName
2057− , "values" .= fmap toJSON docIds ]
2059− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2060− object [ "query_string" .= qQueryStringQuery ]
2062− toJSON (QueryMatchQuery matchQuery) =
2063− object [ "match" .= matchQuery ]
2065− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2066− toJSON multiMatchQuery
2068− toJSON (QueryBoolQuery boolQuery) =
2069− object [ "bool" .= boolQuery ]
2071− toJSON (QueryBoostingQuery boostingQuery) =
2072− object [ "boosting" .= boostingQuery ]
2074− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2075− object [ "common" .= commonTermsQuery ]
2077− toJSON (ConstantScoreFilter csFilter boost) =
2078− object ["constant_score" .= object ["filter" .= csFilter
2079− , "boost" .= boost]]
2081− toJSON (ConstantScoreQuery query boost) =
2082− object ["constant_score" .= object ["query" .= query
2083− , "boost" .= boost]]
2085− toJSON (QueryDisMaxQuery disMaxQuery) =
2086− object [ "dis_max" .= disMaxQuery ]
2088− toJSON (QueryFilteredQuery qFilteredQuery) =
2089− object [ "filtered" .= qFilteredQuery ]
2091− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2092− object [ "fuzzy_like_this" .= fuzzyQuery ]
2094− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2095− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2097− toJSON (QueryFuzzyQuery fuzzyQuery) =
2098− object [ "fuzzy" .= fuzzyQuery ]
2100− toJSON (QueryHasChildQuery childQuery) =
2101− object [ "has_child" .= childQuery ]
2103− toJSON (QueryHasParentQuery parentQuery) =
2104− object [ "has_parent" .= parentQuery ]
2106− toJSON (QueryIndicesQuery qIndicesQuery) =
2107− object [ "indices" .= qIndicesQuery ]
2109− toJSON (MatchAllQuery boost) =
2110− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2112− toJSON (QueryMoreLikeThisQuery query) =
2113− object [ "more_like_this" .= query ]
2115− toJSON (QueryMoreLikeThisFieldQuery query) =
2116− object [ "more_like_this_field" .= query ]
2118− toJSON (QueryNestedQuery query) =
2119− object [ "nested" .= query ]
2121− toJSON (QueryPrefixQuery query) =
2122− object [ "prefix" .= query ]
2124− toJSON (QueryRangeQuery query) =
2125− object [ "range" .= query ]
2127− toJSON (QueryRegexpQuery query) =
2128− object [ "regexp" .= query ]
2130− toJSON (QuerySimpleQueryStringQuery query) =
2131− object [ "simple_query_string" .= query ]
2133−instance FromJSON Query where
2134− parseJSON v = withObject "Query" parse v
2135− where parse o = termQuery `taggedWith` "term"
2136− <|> termsQuery `taggedWith` "terms"
2137− <|> idsQuery `taggedWith` "ids"
2138− <|> queryQueryStringQuery `taggedWith` "query_string"
2139− <|> queryMatchQuery `taggedWith` "match"
2140− <|> queryMultiMatchQuery
2141− <|> queryBoolQuery `taggedWith` "bool"
2142− <|> queryBoostingQuery `taggedWith` "boosting"
2143− <|> queryCommonTermsQuery `taggedWith` "common"
2144− <|> constantScoreFilter `taggedWith` "constant_score"
2145− <|> constantScoreQuery `taggedWith` "constant_score"
2146− <|> queryDisMaxQuery `taggedWith` "dis_max"
2147− <|> queryFilteredQuery `taggedWith` "filtered"
2148− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2149− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2150− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2151− <|> queryHasChildQuery `taggedWith` "has_child"
2152− <|> queryHasParentQuery `taggedWith` "has_parent"
2153− <|> queryIndicesQuery `taggedWith` "indices"
2154− <|> matchAllQuery `taggedWith` "match_all"
2155− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2156− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2157− <|> queryNestedQuery `taggedWith` "nested"
2158− <|> queryPrefixQuery `taggedWith` "prefix"
2159− <|> queryRangeQuery `taggedWith` "range"
2160− <|> queryRegexpQuery `taggedWith` "regexp"
2161− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2162− where taggedWith parser k = parser =<< o .: k
2163− termQuery = fieldTagged $ \(FieldName fn) o ->
2164− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2165− termsQuery o = case HM.toList o of
2166− [(fn, vs)] -> do vals <- parseJSON vs
2168− x:xs -> return (TermsQuery fn (x :| xs))
2169− _ -> fail "Expected non empty list of values"
2170− _ -> fail "Expected object with 1 field-named key"
2171− idsQuery o = IdsQuery <$> o .: "type"
2173− queryQueryStringQuery = pure . QueryQueryStringQuery
2174− queryMatchQuery = pure . QueryMatchQuery
2175− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2176− queryBoolQuery = pure . QueryBoolQuery
2177− queryBoostingQuery = pure . QueryBoostingQuery
2178− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2179− constantScoreFilter o = case HM.lookup "filter" o of
2180− Just x -> ConstantScoreFilter <$> parseJSON x
2182− _ -> fail "Does not appear to be a ConstantScoreFilter"
2183− constantScoreQuery o = case HM.lookup "query" o of
2184− Just x -> ConstantScoreQuery <$> parseJSON x
2186− _ -> fail "Does not appear to be a ConstantScoreQuery"
2187− queryDisMaxQuery = pure . QueryDisMaxQuery
2188− queryFilteredQuery = pure . QueryFilteredQuery
2189− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2190− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2191− queryFuzzyQuery = pure . QueryFuzzyQuery
2192− queryHasChildQuery = pure . QueryHasChildQuery
2193− queryHasParentQuery = pure . QueryHasParentQuery
2194− queryIndicesQuery = pure . QueryIndicesQuery
2195− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2196− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2197− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2198− queryNestedQuery = pure . QueryNestedQuery
2199− queryPrefixQuery = pure . QueryPrefixQuery
2200− queryRangeQuery = pure . QueryRangeQuery
2201− queryRegexpQuery = pure . QueryRegexpQuery
2202− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2205−omitNulls :: [(Text, Value)] -> Value
2206−omitNulls = object . filter notNull where
2207− notNull (_, Null) = False
2208− notNull (_, Array a) = (not . V.null) a
2212−instance ToJSON SimpleQueryStringQuery where
2213− toJSON SimpleQueryStringQuery {..} =
2214− omitNulls (base ++ maybeAdd)
2215− where base = [ "query" .= simpleQueryStringQuery ]
2216− maybeAdd = [ "fields" .= simpleQueryStringField
2217− , "default_operator" .= simpleQueryStringOperator
2218− , "analyzer" .= simpleQueryStringAnalyzer
2219− , "flags" .= simpleQueryStringFlags
2220− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2221− , "locale" .= simpleQueryStringLocale ]
2223−instance FromJSON SimpleQueryStringQuery where
2224− parseJSON = withObject "SimpleQueryStringQuery" parse
2225− where parse o = SimpleQueryStringQuery <$> o .: "query"
2227− <*> o .:? "default_operator"
2228− <*> o .:? "analyzer"
2229− <*> (parseFlags <$> o .:? "flags")
2230− <*> o .:? "lowercase_expanded_terms"
2232− parseFlags (Just (x:xs)) = Just (x :| xs)
2233− parseFlags _ = Nothing
2235−instance ToJSON FieldOrFields where
2236− toJSON (FofField fieldName) =
2238− toJSON (FofFields fieldNames) =
2241−instance FromJSON FieldOrFields where
2242− parseJSON v = FofField <$> parseJSON v
2243− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2245−instance ToJSON SimpleQueryFlag where
2246− toJSON SimpleQueryAll = "ALL"
2247− toJSON SimpleQueryNone = "NONE"
2248− toJSON SimpleQueryAnd = "AND"
2249− toJSON SimpleQueryOr = "OR"
2250− toJSON SimpleQueryPrefix = "PREFIX"
2251− toJSON SimpleQueryPhrase = "PHRASE"
2252− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2253− toJSON SimpleQueryEscape = "ESCAPE"
2254− toJSON SimpleQueryWhitespace = "WHITESPACE"
2255− toJSON SimpleQueryFuzzy = "FUZZY"
2256− toJSON SimpleQueryNear = "NEAR"
2257− toJSON SimpleQuerySlop = "SLOP"
2259−instance FromJSON SimpleQueryFlag where
2260− parseJSON = withText "SimpleQueryFlag" parse
2261− where parse "ALL" = pure SimpleQueryAll
2262− parse "NONE" = pure SimpleQueryNone
2263− parse "AND" = pure SimpleQueryAnd
2264− parse "OR" = pure SimpleQueryOr
2265− parse "PREFIX" = pure SimpleQueryPrefix
2266− parse "PHRASE" = pure SimpleQueryPhrase
2267− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2268− parse "ESCAPE" = pure SimpleQueryEscape
2269− parse "WHITESPACE" = pure SimpleQueryWhitespace
2270− parse "FUZZY" = pure SimpleQueryFuzzy
2271− parse "NEAR" = pure SimpleQueryNear
2272− parse "SLOP" = pure SimpleQuerySlop
2273− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2275−instance ToJSON RegexpQuery where
2276− toJSON (RegexpQuery (FieldName rqQueryField)
2277− (Regexp regexpQueryQuery) rqQueryFlags
2279− object [ rqQueryField .= omitNulls base ]
2280− where base = [ "value" .= regexpQueryQuery
2281− , "flags" .= rqQueryFlags
2282− , "boost" .= rqQueryBoost ]
2284−instance FromJSON RegexpQuery where
2285− parseJSON = withObject "RegexpQuery" parse
2286− where parse = fieldTagged $ \fn o ->
2292−instance ToJSON QueryStringQuery where
2293− toJSON (QueryStringQuery qsQueryString
2294− qsDefaultField qsOperator
2295− qsAnalyzer qsAllowWildcard
2296− qsLowercaseExpanded qsEnablePositionIncrements
2297− qsFuzzyMaxExpansions qsFuzziness
2298− qsFuzzyPrefixLength qsPhraseSlop
2299− qsBoost qsAnalyzeWildcard
2300− qsGeneratePhraseQueries qsMinimumShouldMatch
2301− qsLenient qsLocale) =
2304− base = [ "query" .= qsQueryString
2305− , "default_field" .= qsDefaultField
2306− , "default_operator" .= qsOperator
2307− , "analyzer" .= qsAnalyzer
2308− , "allow_leading_wildcard" .= qsAllowWildcard
2309− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2310− , "enable_position_increments" .= qsEnablePositionIncrements
2311− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2312− , "fuzziness" .= qsFuzziness
2313− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2314− , "phrase_slop" .= qsPhraseSlop
2315− , "boost" .= qsBoost
2316− , "analyze_wildcard" .= qsAnalyzeWildcard
2317− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2318− , "minimum_should_match" .= qsMinimumShouldMatch
2319− , "lenient" .= qsLenient
2320− , "locale" .= qsLocale ]
2322−instance FromJSON QueryStringQuery where
2323− parseJSON = withObject "QueryStringQuery" parse
2324− where parse o = QueryStringQuery
2326− <*> o .:? "default_field"
2327− <*> o .:? "default_operator"
2328− <*> o .:? "analyzer"
2329− <*> o .:? "allow_leading_wildcard"
2330− <*> o .:? "lowercase_expanded_terms"
2331− <*> o .:? "enable_position_increments"
2332− <*> o .:? "fuzzy_max_expansions"
2333− <*> o .:? "fuzziness"
2334− <*> o .:? "fuzzy_prefix_length"
2335− <*> o .:? "phrase_slop"
2337− <*> o .:? "analyze_wildcard"
2338− <*> o .:? "auto_generate_phrase_queries"
2339− <*> o .:? "minimum_should_match"
2340− <*> o .:? "lenient"
2343−instance ToJSON RangeQuery where
2344− toJSON (RangeQuery (FieldName fieldName) range boost) =
2345− object [ fieldName .= object conjoined ]
2346− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2348−instance FromJSON RangeQuery where
2349− parseJSON = withObject "RangeQuery" parse
2350− where parse = fieldTagged $ \fn o ->
2352− <$> parseJSON (Object o)
2355−instance FromJSON RangeValue where
2356− parseJSON = withObject "RangeValue" parse
2357− where parse o = parseDate o
2359− parseDate o = do lt <- o .:? "lt"
2363− case (lt, lte, gt, gte) of
2364− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2365− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2366− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2367− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2368− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2369− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2370− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2371− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2372− (Nothing, Nothing, Nothing, Nothing) -> mzero
2373− parseDouble o = do lt <- o .:? "lt"
2377− case (lt, lte, gt, gte) of
2378− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2379− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2380− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2381− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2382− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2383− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2384− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2385− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2386− (Nothing, Nothing, Nothing, Nothing) -> mzero
2388−instance ToJSON PrefixQuery where
2389− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2390− object [ fieldName .= omitNulls base ]
2391− where base = [ "value" .= queryValue
2392− , "boost" .= boost ]
2394−instance FromJSON PrefixQuery where
2395− parseJSON = withObject "PrefixQuery" parse
2396− where parse = fieldTagged $ \fn o ->
2401−instance ToJSON NestedQuery where
2402− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2403− object [ "path" .= nqPath
2404− , "score_mode" .= nqScoreType
2405− , "query" .= nqQuery ]
2407−instance FromJSON NestedQuery where
2408− parseJSON = withObject "NestedQuery" parse
2409− where parse o = NestedQuery
2411− <*> o .: "score_mode"
2414−instance ToJSON MoreLikeThisFieldQuery where
2415− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2416− percent mtf mqt stopwords mindf maxdf
2417− minwl maxwl boostTerms boost analyzer) =
2418− object [ fieldName .= omitNulls base ]
2419− where base = [ "like_text" .= text
2420− , "percent_terms_to_match" .= percent
2421− , "min_term_freq" .= mtf
2422− , "max_query_terms" .= mqt
2423− , "stop_words" .= stopwords
2424− , "min_doc_freq" .= mindf
2425− , "max_doc_freq" .= maxdf
2426− , "min_word_length" .= minwl
2427− , "max_word_length" .= maxwl
2428− , "boost_terms" .= boostTerms
2430− , "analyzer" .= analyzer ]
2432−instance FromJSON MoreLikeThisFieldQuery where
2433− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2434− where parse = fieldTagged $ \fn o ->
2435− MoreLikeThisFieldQuery
2436− <$> o .: "like_text"
2438− <*> o .:? "percent_terms_to_match"
2439− <*> o .:? "min_term_freq"
2440− <*> o .:? "max_query_terms"
2441− <*> (optionalNE =<< o .:? "stop_words")
2442− <*> o .:? "min_doc_freq"
2443− <*> o .:? "max_doc_freq"
2444− <*> o .:? "min_word_length"
2445− <*> o .:? "max_word_length"
2446− <*> o .:? "boost_terms"
2448− <*> o .:? "analyzer"
2449− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2451−instance ToJSON MoreLikeThisQuery where
2452− toJSON (MoreLikeThisQuery text fields percent
2453− mtf mqt stopwords mindf maxdf
2454− minwl maxwl boostTerms boost analyzer) =
2456− where base = [ "like_text" .= text
2457− , "fields" .= fields
2458− , "percent_terms_to_match" .= percent
2459− , "min_term_freq" .= mtf
2460− , "max_query_terms" .= mqt
2461− , "stop_words" .= stopwords
2462− , "min_doc_freq" .= mindf
2463− , "max_doc_freq" .= maxdf
2464− , "min_word_length" .= minwl
2465− , "max_word_length" .= maxwl
2466− , "boost_terms" .= boostTerms
2468− , "analyzer" .= analyzer ]
2470−instance FromJSON MoreLikeThisQuery where
2471− parseJSON = withObject "MoreLikeThisQuery" parse
2472− where parse o = MoreLikeThisQuery
2473− <$> o .: "like_text"
2474− <*> (optionalNE =<< o .:? "fields")
2475− <*> o .:? "percent_terms_to_match"
2476− <*> o .:? "min_term_freq"
2477− <*> o .:? "max_query_terms"
2478− <*> (optionalNE =<< o .:? "stop_words")
2479− <*> o .:? "min_doc_freq"
2480− <*> o .:? "max_doc_freq"
2481− <*> o .:? "min_word_length"
2482− <*> o .:? "max_word_length"
2483− <*> o .:? "boost_terms"
2485− <*> o .:? "analyzer"
2486− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2488−instance ToJSON IndicesQuery where
2489− toJSON (IndicesQuery indices query noMatch) =
2490− omitNulls [ "indices" .= indices
2491− , "no_match_query" .= noMatch
2492− , "query" .= query ]
2494−instance FromJSON IndicesQuery where
2495− parseJSON = withObject "IndicesQuery" parse
2496− where parse o = IndicesQuery
2497− <$> o .:? "indices" .!= []
2499− <*> o .:? "no_match_query"
2501−instance ToJSON HasParentQuery where
2502− toJSON (HasParentQuery queryType query scoreType) =
2503− omitNulls [ "parent_type" .= queryType
2504− , "score_type" .= scoreType
2505− , "query" .= query ]
2507−instance FromJSON HasParentQuery where
2508− parseJSON = withObject "HasParentQuery" parse
2509− where parse o = HasParentQuery
2510− <$> o .: "parent_type"
2512− <*> o .:? "score_type"
2514−instance ToJSON HasChildQuery where
2515− toJSON (HasChildQuery queryType query scoreType) =
2516− omitNulls [ "query" .= query
2517− , "score_type" .= scoreType
2518− , "type" .= queryType ]
2520−instance FromJSON HasChildQuery where
2521− parseJSON = withObject "HasChildQuery" parse
2522− where parse o = HasChildQuery
2525− <*> o .:? "score_type"
2527−instance ToJSON FuzzyQuery where
2528− toJSON (FuzzyQuery (FieldName fieldName) queryText
2529− prefixLength maxEx fuzziness boost) =
2530− object [ fieldName .= omitNulls base ]
2531− where base = [ "value" .= queryText
2532− , "fuzziness" .= fuzziness
2533− , "prefix_length" .= prefixLength
2535− , "max_expansions" .= maxEx ]
2537−instance FromJSON FuzzyQuery where
2538− parseJSON = withObject "FuzzyQuery" parse
2539− where parse = fieldTagged $ \fn o ->
2542− <*> o .: "prefix_length"
2543− <*> o .: "max_expansions"
2544− <*> o .: "fuzziness"
2547−instance ToJSON FuzzyLikeFieldQuery where
2548− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2549− fieldText maxTerms ignoreFreq fuzziness prefixLength
2551− object [ fieldName .=
2552− omitNulls [ "like_text" .= fieldText
2553− , "max_query_terms" .= maxTerms
2554− , "ignore_tf" .= ignoreFreq
2555− , "fuzziness" .= fuzziness
2556− , "prefix_length" .= prefixLength
2557− , "analyzer" .= analyzer
2558− , "boost" .= boost ]]
2560−instance FromJSON FuzzyLikeFieldQuery where
2561− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2562− where parse = fieldTagged $ \fn o ->
2563− FuzzyLikeFieldQuery fn
2564− <$> o .: "like_text"
2565− <*> o .: "max_query_terms"
2566− <*> o .: "ignore_tf"
2567− <*> o .: "fuzziness"
2568− <*> o .: "prefix_length"
2570− <*> o .:? "analyzer"
2572−instance ToJSON FuzzyLikeThisQuery where
2573− toJSON (FuzzyLikeThisQuery fields text maxTerms
2574− ignoreFreq fuzziness prefixLength boost analyzer) =
2576− where base = [ "fields" .= fields
2577− , "like_text" .= text
2578− , "max_query_terms" .= maxTerms
2579− , "ignore_tf" .= ignoreFreq
2580− , "fuzziness" .= fuzziness
2581− , "prefix_length" .= prefixLength
2582− , "analyzer" .= analyzer
2583− , "boost" .= boost ]
2585−instance FromJSON FuzzyLikeThisQuery where
2586− parseJSON = withObject "FuzzyLikeThisQuery" parse
2587− where parse o = FuzzyLikeThisQuery
2588− <$> o .:? "fields" .!= []
2589− <*> o .: "like_text"
2590− <*> o .: "max_query_terms"
2591− <*> o .: "ignore_tf"
2592− <*> o .: "fuzziness"
2593− <*> o .: "prefix_length"
2595− <*> o .:? "analyzer"
2597−instance ToJSON FilteredQuery where
2598− toJSON (FilteredQuery query fFilter) =
2599− object [ "query" .= query
2600− , "filter" .= fFilter ]
2602−instance FromJSON FilteredQuery where
2603− parseJSON = withObject "FilteredQuery" parse
2604− where parse o = FilteredQuery
2608−instance ToJSON DisMaxQuery where
2609− toJSON (DisMaxQuery queries tiebreaker boost) =
2611− where base = [ "queries" .= queries
2613− , "tie_breaker" .= tiebreaker ]
2615−instance FromJSON DisMaxQuery where
2616− parseJSON = withObject "DisMaxQuery" parse
2617− where parse o = DisMaxQuery
2618− <$> o .:? "queries" .!= []
2619− <*> o .: "tie_breaker"
2622−instance ToJSON CommonTermsQuery where
2623− toJSON (CommonTermsQuery (FieldName fieldName)
2624− (QueryString query) cf lfo hfo msm
2625− boost analyzer disableCoord) =
2626− object [fieldName .= omitNulls base ]
2627− where base = [ "query" .= query
2628− , "cutoff_frequency" .= cf
2629− , "low_freq_operator" .= lfo
2630− , "minimum_should_match" .= msm
2632− , "analyzer" .= analyzer
2633− , "disable_coord" .= disableCoord
2634− , "high_freq_operator" .= hfo ]
2636−instance FromJSON CommonTermsQuery where
2637− parseJSON = withObject "CommonTermsQuery" parse
2638− where parse = fieldTagged $ \fn o ->
2639− CommonTermsQuery fn
2641− <*> o .: "cutoff_frequency"
2642− <*> o .: "low_freq_operator"
2643− <*> o .: "high_freq_operator"
2644− <*> o .:? "minimum_should_match"
2646− <*> o .:? "analyzer"
2647− <*> o .:? "disable_coord"
2649−instance ToJSON CommonMinimumMatch where
2650− toJSON (CommonMinimumMatch mm) = toJSON mm
2651− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2652− object [ "low_freq" .= lowF
2653− , "high_freq" .= highF ]
2655−instance FromJSON CommonMinimumMatch where
2656− parseJSON v = parseMinimum v
2657− <|> parseMinimumHighLow v
2658− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2659− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2660− MinimumMatchHighLow
2661− <$> o .: "low_freq"
2662− <*> o .: "high_freq")
2665−instance ToJSON BoostingQuery where
2666− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2667− object [ "positive" .= bqPositiveQuery
2668− , "negative" .= bqNegativeQuery
2669− , "negative_boost" .= bqNegativeBoost ]
2671−instance FromJSON BoostingQuery where
2672− parseJSON = withObject "BoostingQuery" parse
2673− where parse o = BoostingQuery
2674− <$> o .: "positive"
2675− <*> o .: "negative"
2676− <*> o .: "negative_boost"
2678−instance ToJSON BoolQuery where
2679− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2681− where base = [ "must" .= mustM
2682− , "must_not" .= notM
2683− , "should" .= shouldM
2684− , "minimum_should_match" .= bqMin
2686− , "disable_coord" .= disableCoord ]
2688−instance FromJSON BoolQuery where
2689− parseJSON = withObject "BoolQuery" parse
2690− where parse o = BoolQuery
2691− <$> o .:? "must" .!= []
2692− <*> o .:? "must_not" .!= []
2693− <*> o .:? "should" .!= []
2694− <*> o .:? "minimum_should_match"
2696− <*> o .:? "disable_coord"
2698−instance ToJSON MatchQuery where
2699− toJSON (MatchQuery (FieldName fieldName)
2700− (QueryString mqQueryString) booleanOperator
2701− zeroTermsQuery cutoffFrequency matchQueryType
2702− analyzer maxExpansions lenient boost) =
2703− object [ fieldName .= omitNulls base ]
2704− where base = [ "query" .= mqQueryString
2705− , "operator" .= booleanOperator
2706− , "zero_terms_query" .= zeroTermsQuery
2707− , "cutoff_frequency" .= cutoffFrequency
2708− , "type" .= matchQueryType
2709− , "analyzer" .= analyzer
2710− , "max_expansions" .= maxExpansions
2711− , "lenient" .= lenient
2712− , "boost" .= boost ]
2714−instance FromJSON MatchQuery where
2715− parseJSON = withObject "MatchQuery" parse
2716− where parse = fieldTagged $ \fn o ->
2719− <*> o .: "operator"
2720− <*> o .: "zero_terms_query"
2721− <*> o .:? "cutoff_frequency"
2723− <*> o .:? "analyzer"
2724− <*> o .:? "max_expansions"
2725− <*> o .:? "lenient"
2728−instance ToJSON MultiMatchQuery where
2729− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2730− ztQ tb mmqt cf analyzer maxEx lenient) =
2731− object ["multi_match" .= omitNulls base]
2732− where base = [ "fields" .= fmap toJSON fields
2734− , "operator" .= boolOp
2735− , "zero_terms_query" .= ztQ
2736− , "tiebreaker" .= tb
2738− , "cutoff_frequency" .= cf
2739− , "analyzer" .= analyzer
2740− , "max_expansions" .= maxEx
2741− , "lenient" .= lenient ]
2743−instance FromJSON MultiMatchQuery where
2744− parseJSON = withObject "MultiMatchQuery" parse
2745− where parse raw = do o <- raw .: "multi_match"
2747− <$> o .:? "fields" .!= []
2749− <*> o .: "operator"
2750− <*> o .: "zero_terms_query"
2751− <*> o .:? "tiebreaker"
2753− <*> o .:? "cutoff_frequency"
2754− <*> o .:? "analyzer"
2755− <*> o .:? "max_expansions"
2756− <*> o .:? "lenient"
2758−instance ToJSON MultiMatchQueryType where
2759− toJSON MultiMatchBestFields = "best_fields"
2760− toJSON MultiMatchMostFields = "most_fields"
2761− toJSON MultiMatchCrossFields = "cross_fields"
2762− toJSON MultiMatchPhrase = "phrase"
2763− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2765−instance FromJSON MultiMatchQueryType where
2766− parseJSON = withText "MultiMatchPhrasePrefix" parse
2767− where parse "best_fields" = pure MultiMatchBestFields
2768− parse "most_fields" = pure MultiMatchMostFields
2769− parse "cross_fields" = pure MultiMatchCrossFields
2770− parse "phrase" = pure MultiMatchPhrase
2771− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2772− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2774−instance ToJSON BooleanOperator where
2775− toJSON And = String "and"
2776− toJSON Or = String "or"
2778−instance FromJSON BooleanOperator where
2779− parseJSON = withText "BooleanOperator" parse
2780− where parse "and" = pure And
2781− parse "or" = pure Or
2782− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2784−instance ToJSON ZeroTermsQuery where
2785− toJSON ZeroTermsNone = String "none"
2786− toJSON ZeroTermsAll = String "all"
2788−instance FromJSON ZeroTermsQuery where
2789− parseJSON = withText "ZeroTermsQuery" parse
2790− where parse "none" = pure ZeroTermsNone
2791− parse "all" = pure ZeroTermsAll
2792− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2794−instance ToJSON MatchQueryType where
2795− toJSON MatchPhrase = "phrase"
2796− toJSON MatchPhrasePrefix = "phrase_prefix"
2798−instance FromJSON MatchQueryType where
2799− parseJSON = withText "MatchQueryType" parse
2800− where parse "phrase" = pure MatchPhrase
2801− parse "phrase_prefix" = pure MatchPhrasePrefix
2802− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2804−instance FromJSON Status where
2805− parseJSON (Object v) = Status <$>
2811− parseJSON _ = empty
2814−instance ToJSON IndexSettings where
2815− toJSON (IndexSettings s r) = object ["settings" .=
2817− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2821−instance FromJSON IndexSettings where
2822− parseJSON = withObject "IndexSettings" parse
2823− where parse o = do s <- o .: "settings"
2825− IndexSettings <$> i .: "number_of_shards"
2826− <*> i .: "number_of_replicas"
2828−instance ToJSON UpdatableIndexSetting where
2829− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2830− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2831− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2832− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2833− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2834− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2835− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2836− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2837− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2838− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2839− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2840− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2841− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2842− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2843− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2844− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2845− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2846− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2847− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2848− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2849− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2850− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2851− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2852− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2853− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2854− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2855− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2856− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2858−instance FromJSON UpdatableIndexSetting where
2859− parseJSON = withObject "UpdatableIndexSetting" parse
2860− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2861− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2862− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2863− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2864− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2865− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2866− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2867− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2868− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2869− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2870− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2871− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2872− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2873− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2874− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2875− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2876− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2877− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2878− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2879− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2880− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2881− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2882− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2883− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2884− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2885− <|> blocksRead `taggedAt` ["blocks", "read"]
2886− <|> blocksWrite `taggedAt` ["blocks", "write"]
2887− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2888− where taggedAt f ks = taggedAt' f (Object o) ks
2889− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON =<< unStringlyTypeJSON v))
2890− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
2891− taggedAt' f v' ks) v
2892− numberOfReplicas = pure . NumberOfReplicas
2893− autoExpandReplicas = pure . AutoExpandReplicas
2894− refreshInterval = pure . RefreshInterval . ndtJSON
2895− indexConcurrency = pure . IndexConcurrency
2896− failOnMergeFailure = pure . FailOnMergeFailure
2897− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
2898− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
2899− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
2900− translogDisableFlush = pure . TranslogDisableFlush
2901− cacheFilterMaxSize = pure . CacheFilterMaxSize
2902− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
2903− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
2904− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
2905− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
2906− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
2907− routingAllocationEnable = pure . RoutingAllocationEnable
2908− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
2909− recoveryInitialShards = pure . RecoveryInitialShards
2910− gcDeletes = pure . GCDeletes . ndtJSON
2911− ttlDisablePurge = pure . TTLDisablePurge
2912− translogFSType = pure . TranslogFSType
2913− compoundFormat = pure . IndexCompoundFormat
2914− compoundOnFlush = pure . IndexCompoundOnFlush
2915− warmerEnabled = pure . WarmerEnabled
2916− blocksReadOnly = pure . BlocksReadOnly
2917− blocksRead = pure . BlocksRead
2918− blocksWrite = pure . BlocksWrite
2919− blocksMetaData = pure . BlocksMetaData
2921−instance FromJSON IndexSettingsSummary where
2922− parseJSON = withObject "IndexSettingsSummary" parse
2923− where parse o = case HM.toList o of
2924− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
2926− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
2927− _ -> fail "Expected single-key object with index name"
2928− redundant (NumberOfReplicas _) = True
2929− redundant _ = False
2931−-- | For some reason in the settings API, all leaf values get returned
2932−-- as strings. This function attepmts to recover from this for all
2933−-- non-recursive JSON types. If nothing can be done or the same value
2934−-- would be return, it returns 'mzero'
2935−unStringlyTypeJSON :: MonadPlus m => Value -> m Value
2936−unStringlyTypeJSON (String "true") = return (Bool True)
2937−unStringlyTypeJSON (String "false") = return (Bool False)
2938−unStringlyTypeJSON (String "null") = return Null
2939−unStringlyTypeJSON (String t) = case readMay (T.unpack t) of
2940− Just n -> return (Number n)
2942−unStringlyTypeJSON _ = mzero
2945−parseSettings :: Object -> Parser [UpdatableIndexSetting]
2946−parseSettings o = do
2948− -- slice the index object into singleton hashmaps and try to parse each
2949− parses <- forM (HM.toList o') $ \(k, v) -> do
2950− -- blocks are now nested into the "index" key, which is not how they're serialized
2951− let atRoot = Object (HM.singleton k v)
2952− let atIndex = Object (HM.singleton "index" atRoot)
2953− optional (parseJSON atRoot <|> parseJSON atIndex)
2954− return (catMaybes parses)
2956−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2957−oPath (k :| []) v = object [k .= v]
2958−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2960−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2961−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2962− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2964−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
2965−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
2966− where parse o = case HM.toList o of
2967− [] -> fail "Expected non-empty list of NodeAttrFilters"
2968− x:xs -> DT.mapM (uncurry parse') (x :| xs)
2969− parse' n = withText "Text" $ \t ->
2970− case T.splitOn "," t of
2971− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
2972− [] -> fail "Expected non-empty list of filter values"
2974−instance ToJSON ReplicaBounds where
2975− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2976− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2977− toJSON ReplicasUnbounded = Bool False
2979−instance FromJSON ReplicaBounds where
2980− parseJSON v = withText "ReplicaBounds" parseText v
2981− <|> withBool "ReplicaBounds" parseBool v
2982− where parseText t = case T.splitOn "-" t of
2983− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
2984− [a, b] -> ReplicasBounded <$> parseReadText a
2985− <*> parseReadText b
2986− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
2987− parseBool False = pure ReplicasUnbounded
2988− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
2990−instance ToJSON AllocationPolicy where
2991− toJSON AllocAll = String "all"
2992− toJSON AllocPrimaries = String "primaries"
2993− toJSON AllocNewPrimaries = String "new_primaries"
2994− toJSON AllocNone = String "none"
2996−instance FromJSON AllocationPolicy where
2997− parseJSON = withText "AllocationPolicy" parse
2998− where parse "all" = pure AllocAll
2999− parse "primaries" = pure AllocPrimaries
3000− parse "new_primaries" = pure AllocNewPrimaries
3001− parse "none" = pure AllocNone
3002− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3004−instance ToJSON InitialShardCount where
3005− toJSON QuorumShards = String "quorum"
3006− toJSON QuorumMinus1Shards = String "quorum-1"
3007− toJSON FullShards = String "full"
3008− toJSON FullMinus1Shards = String "full-1"
3009− toJSON (ExplicitShards x) = toJSON x
3011−instance FromJSON InitialShardCount where
3012− parseJSON v = withText "InitialShardCount" parseText v
3013− <|> ExplicitShards <$> parseJSON v
3014− where parseText "quorum" = pure QuorumShards
3015− parseText "quorum-1" = pure QuorumMinus1Shards
3016− parseText "full" = pure FullShards
3017− parseText "full-1" = pure FullMinus1Shards
3018− parseText _ = mzero
3020−instance ToJSON FSType where
3021− toJSON FSSimple = "simple"
3022− toJSON FSBuffered = "buffered"
3024−instance FromJSON FSType where
3025− parseJSON = withText "FSType" parse
3026− where parse "simple" = pure FSSimple
3027− parse "buffered" = pure FSBuffered
3028− parse t = fail ("Invalid FSType: " <> show t)
3030−instance ToJSON CompoundFormat where
3031− toJSON (CompoundFileFormat x) = Bool x
3032− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3034−instance FromJSON CompoundFormat where
3035− parseJSON v = CompoundFileFormat <$> parseJSON v
3036− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3038−instance ToJSON NominalDiffTimeJSON where
3039− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3041−instance FromJSON NominalDiffTimeJSON where
3042− parseJSON = withText "NominalDiffTime" parse
3043− where parse t = case T.takeEnd 1 t of
3044− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3045− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3047−instance ToJSON IndexTemplate where
3048− toJSON (IndexTemplate p s m) = merge
3049− (object [ "template" .= p
3050− , "mappings" .= foldl' merge (object []) m
3054− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3056− merge _ _ = undefined
3058−instance (FromJSON a) => FromJSON (EsResult a) where
3059− parseJSON jsonVal@(Object v) = do
3060− found <- v .:? "found" .!= False
3062− then parseJSON jsonVal
3063− else return Nothing
3064− EsResult <$> v .: "_index" <*>
3068− parseJSON _ = empty
3070−instance (FromJSON a) => FromJSON (EsResultFound a) where
3071− parseJSON (Object v) = EsResultFound <$>
3072− v .: "_version" <*>
3074− parseJSON _ = empty
3076−instance FromJSON EsError where
3077− parseJSON (Object v) = EsError <$>
3080− parseJSON _ = empty
3082−instance FromJSON IndexAliasesSummary where
3083− parseJSON = withObject "IndexAliasesSummary" parse
3084− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3085− go ixn = withObject "index aliases" $ \ia -> do
3086− aliases <- ia .:? "aliases" .!= mempty
3087− forM (HM.toList aliases) $ \(aName, v) -> do
3088− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3089− IndexAliasSummary indexAlias <$> parseJSON v
3092−instance ToJSON IndexAliasAction where
3093− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3094− where Object iaObj = toJSON ia
3095− Object optsObj = toJSON opts
3096− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3097− where Object iaObj = toJSON ia
3099−instance ToJSON IndexAlias where
3100− toJSON IndexAlias {..} = object ["index" .= srcIndex
3101− , "alias" .= indexAlias
3104−instance ToJSON IndexAliasCreate where
3105− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3106− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3107− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3109−instance ToJSON AliasRouting where
3110− toJSON (AllAliasRouting v) = object ["routing" .= v]
3111− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3112− where prs = [("search_routing" .=) <$> srch
3113− ,("index_routing" .=) <$> idx]
3115−instance FromJSON AliasRouting where
3116− parseJSON = withObject "AliasRouting" parse
3117− where parse o = parseAll o <|> parseGranular o
3118− parseAll o = AllAliasRouting <$> o .: "routing"
3119− parseGranular o = do
3120− sr <- o .:? "search_routing"
3121− ir <- o .:? "index_routing"
3122− if isNothing sr && isNothing ir
3123− then fail "Both search_routing and index_routing can't be blank"
3124− else return (GranularAliasRouting sr ir)
3126−instance FromJSON IndexAliasCreate where
3127− parseJSON v = withObject "IndexAliasCreate" parse v
3128− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3131−instance ToJSON SearchAliasRouting where
3132− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3134−instance FromJSON SearchAliasRouting where
3135− parseJSON = withText "SearchAliasRouting" parse
3136− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3138−instance ToJSON Search where
3139− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3140− omitNulls [ "query" .= query
3141− , "filter" .= sFilter
3143− , "aggregations" .= searchAggs
3144− , "highlight" .= highlight
3147− , "track_scores" .= sTrackSortScores
3148− , "fields" .= sFields
3149− , "_source" .= sSource]
3152−instance ToJSON Source where
3153− toJSON NoSource = toJSON False
3154− toJSON (SourcePatterns patterns) = toJSON patterns
3155− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3157−instance ToJSON PatternOrPatterns where
3158− toJSON (PopPattern pattern) = toJSON pattern
3159− toJSON (PopPatterns patterns) = toJSON patterns
3161−instance ToJSON Include where
3162− toJSON (Include patterns) = toJSON patterns
3164−instance ToJSON Exclude where
3165− toJSON (Exclude patterns) = toJSON patterns
3167−instance ToJSON Pattern where
3168− toJSON (Pattern pattern) = toJSON pattern
3171−instance ToJSON FieldHighlight where
3172− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3173− object [ fName .= fSettings ]
3174− toJSON (FieldHighlight (FieldName fName) Nothing) =
3175− object [ fName .= emptyObject ]
3177−instance ToJSON Highlights where
3178− toJSON (Highlights global fields) =
3179− omitNulls (("fields" .= fields)
3180− : highlightSettingsPairs global)
3182−instance ToJSON HighlightSettings where
3183− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3185−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3186−highlightSettingsPairs Nothing = []
3187−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3188−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3189−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3192−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3193−plainHighPairs Nothing = []
3194−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3195− [ "type" .= String "plain"]
3196− ++ commonHighlightPairs plCom
3197− ++ nonPostingsToPairs plNonPost
3199−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3200−postHighPairs Nothing = []
3201−postHighPairs (Just (PostingsHighlight pCom)) =
3202− ("type" .= String "postings")
3203− : commonHighlightPairs pCom
3205−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3206−fastVectorHighPairs Nothing = []
3207−fastVectorHighPairs (Just
3208− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3209− fvBoundMaxScan fvFragOff fvMatchedFields
3211− [ "type" .= String "fvh"
3212− , "boundary_chars" .= fvBoundChars
3213− , "boundary_max_scan" .= fvBoundMaxScan
3214− , "fragment_offset" .= fvFragOff
3215− , "matched_fields" .= fvMatchedFields
3216− , "phraseLimit" .= fvPhraseLim]
3217− ++ commonHighlightPairs fvCom
3218− ++ nonPostingsToPairs fvNonPostSettings
3220−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3221−deleteSeveral ks hm = foldr HM.delete hm ks
3223−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3224−commonHighlightPairs Nothing = []
3225−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3226− chNoMatchSize chHighlightQuery
3227− chRequireFieldMatch)) =
3228− [ "order" .= chScore
3229− , "force_source" .= chForceSource
3230− , "encoder" .= chEncoder
3231− , "no_match_size" .= chNoMatchSize
3232− , "highlight_query" .= chHighlightQuery
3233− , "require_fieldMatch" .= chRequireFieldMatch]
3234− ++ highlightTagToPairs chTag
3237−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3238−nonPostingsToPairs Nothing = []
3239−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3240− [ "fragment_size" .= npFragSize
3241− , "number_of_fragments" .= npNumOfFrags]
3243−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3244−parseNEJSON [] = fail "Expected non-empty list"
3245−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3248−instance ToJSON HighlightEncoder where
3249− toJSON DefaultEncoder = String "default"
3250− toJSON HTMLEncoder = String "html"
3252−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3253−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3254−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3255− , "post_tags" .= post]
3256−highlightTagToPairs Nothing = []
3258−instance ToJSON SortSpec where
3259− toJSON (DefaultSortSpec
3260− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3261− dsSortMode dsMissingSort dsNestedFilter)) =
3262− object [dsSortFieldName .= omitNulls base] where
3263− base = [ "order" .= dsSortOrder
3264− , "ignore_unmapped" .= dsIgnoreUnmapped
3265− , "mode" .= dsSortMode
3266− , "missing" .= dsMissingSort
3267− , "nested_filter" .= dsNestedFilter ]
3269− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3270− object [ "unit" .= units
3271− , field .= gdsLatLon
3272− , "order" .= gdsSortOrder ]
3275−instance ToJSON SortOrder where
3276− toJSON Ascending = String "asc"
3277− toJSON Descending = String "desc"
3280−instance ToJSON SortMode where
3281− toJSON SortMin = String "min"
3282− toJSON SortMax = String "max"
3283− toJSON SortSum = String "sum"
3284− toJSON SortAvg = String "avg"
3287−instance ToJSON Missing where
3288− toJSON LastMissing = String "_last"
3289− toJSON FirstMissing = String "_first"
3290− toJSON (CustomMissing txt) = String txt
3293−instance ToJSON ScoreType where
3294− toJSON ScoreTypeMax = "max"
3295− toJSON ScoreTypeAvg = "avg"
3296− toJSON ScoreTypeSum = "sum"
3297− toJSON ScoreTypeNone = "none"
3299−instance FromJSON ScoreType where
3300− parseJSON = withText "ScoreType" parse
3301− where parse "max" = pure ScoreTypeMax
3302− parse "avg" = pure ScoreTypeAvg
3303− parse "sum" = pure ScoreTypeSum
3304− parse "none" = pure ScoreTypeNone
3305− parse t = fail ("Unexpected ScoreType: " <> show t)
3307−instance ToJSON Distance where
3308− toJSON (Distance dCoefficient dUnit) =
3309− String boltedTogether where
3310− coefText = showText dCoefficient
3311− (String unitText) = toJSON dUnit
3312− boltedTogether = mappend coefText unitText
3314−instance FromJSON Distance where
3315− parseJSON = withText "Distance" parse
3316− where parse t = Distance <$> parseCoeff nT
3317− <*> parseJSON (String unitT)
3318− where (nT, unitT) = T.span validForNumber t
3319− -- may be a better way to do this
3320− validForNumber '-' = True
3321− validForNumber '.' = True
3322− validForNumber 'e' = True
3323− validForNumber c = isNumber c
3324− parseCoeff "" = fail "Empty string cannot be parsed as number"
3325− parseCoeff s = return (read (T.unpack s))
3327−instance ToJSON DistanceUnit where
3328− toJSON Miles = String "mi"
3329− toJSON Yards = String "yd"
3330− toJSON Feet = String "ft"
3331− toJSON Inches = String "in"
3332− toJSON Kilometers = String "km"
3333− toJSON Meters = String "m"
3334− toJSON Centimeters = String "cm"
3335− toJSON Millimeters = String "mm"
3336− toJSON NauticalMiles = String "nmi"
3339−instance FromJSON DistanceUnit where
3340− parseJSON = withText "DistanceUnit" parse
3341− where parse "mi" = pure Miles
3342− parse "yd" = pure Yards
3343− parse "ft" = pure Feet
3344− parse "in" = pure Inches
3345− parse "km" = pure Kilometers
3346− parse "m" = pure Meters
3347− parse "cm" = pure Centimeters
3348− parse "mm" = pure Millimeters
3349− parse "nmi" = pure NauticalMiles
3350− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3352−instance ToJSON DistanceType where
3353− toJSON Arc = String "arc"
3354− toJSON SloppyArc = String "sloppy_arc"
3355− toJSON Plane = String "plane"
3357−instance FromJSON DistanceType where
3358− parseJSON = withText "DistanceType" parse
3359− where parse "arc" = pure Arc
3360− parse "sloppy_arc" = pure SloppyArc
3361− parse "plane" = pure Plane
3362− parse t = fail ("Unrecognized DistanceType: " <> show t)
3365−instance ToJSON OptimizeBbox where
3366− toJSON NoOptimizeBbox = String "none"
3367− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3369−instance FromJSON OptimizeBbox where
3370− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3371− <|> parseOptimize v
3372− where parseNoOptimize "none" = pure NoOptimizeBbox
3373− parseNoOptimize _ = mzero
3374− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3376−instance ToJSON GeoBoundingBoxConstraint where
3377− toJSON (GeoBoundingBoxConstraint
3378− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3379− object [gbbcGeoBBField .= gbbcConstraintBox
3380− , "_cache" .= cache
3383−instance FromJSON GeoBoundingBoxConstraint where
3384− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3385− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3386− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3388− <*> o .:? "_cache" .!= defaultCache
3390− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3392−instance ToJSON GeoFilterType where
3393− toJSON GeoFilterMemory = String "memory"
3394− toJSON GeoFilterIndexed = String "indexed"
3396−instance FromJSON GeoFilterType where
3397− parseJSON = withText "GeoFilterType" parse
3398− where parse "memory" = pure GeoFilterMemory
3399− parse "indexed" = pure GeoFilterIndexed
3400− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3402−instance ToJSON GeoBoundingBox where
3403− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3404− object ["top_left" .= gbbTopLeft
3405− , "bottom_right" .= gbbBottomRight]
3407−instance FromJSON GeoBoundingBox where
3408− parseJSON = withObject "GeoBoundingBox" parse
3409− where parse o = GeoBoundingBox
3410− <$> o .: "top_left"
3411− <*> o .: "bottom_right"
3413−instance ToJSON LatLon where
3414− toJSON (LatLon lLat lLon) =
3415− object ["lat" .= lLat
3418−instance FromJSON LatLon where
3419− parseJSON = withObject "LatLon" parse
3420− where parse o = LatLon <$> o .: "lat"
3423−-- index for smaller ranges, fielddata for longer ranges
3424−instance ToJSON RangeExecution where
3425− toJSON RangeExecutionIndex = "index"
3426− toJSON RangeExecutionFielddata = "fielddata"
3429−instance FromJSON RangeExecution where
3430− parseJSON = withText "RangeExecution" parse
3431− where parse "index" = pure RangeExecutionIndex
3432− parse "fielddata" = pure RangeExecutionFielddata
3433− parse t = error ("Unrecognized RangeExecution " <> show t)
3435−instance ToJSON RegexpFlags where
3436− toJSON AllRegexpFlags = String "ALL"
3437− toJSON NoRegexpFlags = String "NONE"
3438− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3439− where flagStrs = map flagStr . nub $ h:fs
3440− flagStr AnyString = "ANYSTRING"
3441− flagStr Automaton = "AUTOMATON"
3442− flagStr Complement = "COMPLEMENT"
3443− flagStr Empty = "EMPTY"
3444− flagStr Intersection = "INTERSECTION"
3445− flagStr Interval = "INTERVAL"
3447−instance FromJSON RegexpFlags where
3448− parseJSON = withText "RegexpFlags" parse
3449− where parse "ALL" = pure AllRegexpFlags
3450− parse "NONE" = pure NoRegexpFlags
3451− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3453−instance FromJSON RegexpFlag where
3454− parseJSON = withText "RegexpFlag" parse
3455− where parse "ANYSTRING" = pure AnyString
3456− parse "AUTOMATON" = pure Automaton
3457− parse "COMPLEMENT" = pure Complement
3458− parse "EMPTY" = pure Empty
3459− parse "INTERSECTION" = pure Intersection
3460− parse "INTERVAL" = pure Interval
3461− parse f = fail ("Unknown RegexpFlag: " <> show f)
3463−instance ToJSON Term where
3464− toJSON (Term field value) = object ["term" .= object
3467−instance FromJSON Term where
3468− parseJSON = withObject "Term" parse
3469− where parse o = do termObj <- o .: "term"
3470− case HM.toList termObj of
3471− [(fn, v)] -> Term fn <$> parseJSON v
3472− _ -> fail "Expected object with 1 field-named key"
3474−instance ToJSON BoolMatch where
3475− toJSON (MustMatch term cache) = object ["must" .= term,
3477− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3479− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3482−instance FromJSON BoolMatch where
3483− parseJSON = withObject "BoolMatch" parse
3484− where parse o = mustMatch `taggedWith` "must"
3485− <|> mustNotMatch `taggedWith` "must_not"
3486− <|> shouldMatch `taggedWith` "should"
3487− where taggedWith parser k = parser =<< o .: k
3488− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3489− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3490− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3492instance (FromJSON a) => FromJSON (SearchResult a) where
529instance (FromJSON a) => FromJSON (SearchResult a) where
3493 parseJSON (Object v) = SearchResult <$>
530 parseJSON (Object v) = SearchResult <$>
@@ -3496,71 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3496 v .: "_shards" <*>
533 v .: "_shards" <*>
3497 v .: "hits" <*>
534 v .: "hits" <*>
3498 v .:? "aggregations" <*>
535 v .:? "aggregations" <*>
3499− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
3500− parseJSON _ = empty
537+ v .:? "suggest"
3502−instance (FromJSON a) => FromJSON (SearchHits a) where
3503− parseJSON (Object v) = SearchHits <$>
3505− v .: "max_score" <*>
3507− parseJSON _ = empty
3509−instance (FromJSON a) => FromJSON (Hit a) where
3510− parseJSON (Object v) = Hit <$>
3515− v .:? "_source" <*>
3517 parseJSON _ = empty
538 parseJSON _ = empty
3519−instance FromJSON ShardResult where
540+newtype ScrollId =
3520− parseJSON (Object v) = ShardResult <$>
541+ ScrollId Text
3521− v .: "total" <*>
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
3522− v .: "successful" <*>
3524− parseJSON _ = empty
3527−instance FromJSON DocVersion where
3530− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3532−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3533−instance FromJSON ReplicaCount where
3534− parseJSON v = parseAsInt v
3535− <|> parseAsString v
3536− where parseAsInt = fmap ReplicaCount . parseJSON
3537− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3539−instance FromJSON ShardCount where
3540− parseJSON v = parseAsInt v
3541− <|> parseAsString v
3542− where parseAsInt = fmap ShardCount . parseJSON
3543− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3545−instance Bounded DocVersion where
3546− minBound = DocVersion 1
3547− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3549−instance Enum DocVersion where
3551− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3552− | otherwise = succError "DocVersion"
3554− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3555− | otherwise = predError "DocVersion"
3557− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3558− fromEnum = docVersionNumber
3559− enumFrom = boundedEnumFrom
3560− enumFromThen = boundedEnumFromThen
3562−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3563−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Show, Eq)
3565−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3566−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Show, Eq)