@@ -1,10 +1,8 @@
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 #-}
@@ -12,11 +10,11 @@
12-------------------------------------------------------------------------------
10-------------------------------------------------------------------------------
14-- Module : Database.Bloodhound.Types
12-- Module : Database.Bloodhound.Types
15−-- Copyright : (C) 2014 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
16-- License : BSD-style (see the file LICENSE)
14-- License : BSD-style (see the file LICENSE)
17-- Maintainer : Chris Allen <cma@bitemyapp.com
15-- Maintainer : Chris Allen <cma@bitemyapp.com
18-- Stability : provisional
16-- Stability : provisional
19−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
21-- Data types for describing actions and data structures performed to interact
19-- Data types for describing actions and data structures performed to interact
22-- with Elasticsearch. The two main buckets your queries against Elasticsearch
20-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -44,16 +42,28 @@ module Database.Bloodhound.Types
44 , mkTermsAggregation
42 , mkTermsAggregation
45 , mkTermsScriptAggregation
43 , mkTermsScriptAggregation
46 , mkDateHistogram
44 , mkDateHistogram
45+ , mkCardinalityAggregation
47 , mkDocVersion
46 , mkDocVersion
48+ , mkExtendedStatsAggregation
48 , docVersionNumber
49 , docVersionNumber
50 , toDateHistogram
52 , toDateHistogram
51 , omitNulls
54 , omitNulls
54− , BHEnv(..)
57+ , BHEnv
55 , MonadBH(..)
62 , MonadBH(..)
56 , Version(..)
63 , Version(..)
57 , Status(..)
67 , Status(..)
58 , Existence(..)
68 , Existence(..)
59 , NullValue(..)
69 , NullValue(..)
@@ -61,8 +71,12 @@ module Database.Bloodhound.Types
61 , UpdatableIndexSetting(..)
71 , UpdatableIndexSetting(..)
62 , IndexSettingsSummary(..)
72 , IndexSettingsSummary(..)
63 , AllocationPolicy(..)
73 , AllocationPolicy(..)
64 , ReplicaBounds(..)
75 , ReplicaBounds(..)
65 , Bytes(..)
76 , Bytes(..)
66 , FSType(..)
80 , FSType(..)
67 , InitialShardCount(..)
81 , InitialShardCount(..)
68 , NodeAttrFilter(..)
82 , NodeAttrFilter(..)
@@ -74,6 +88,7 @@ module Database.Bloodhound.Types
74 , EsResult(..)
88 , EsResult(..)
75 , EsResultFound(..)
89 , EsResultFound(..)
76 , EsError(..)
90 , EsError(..)
91+ , EsProtocolException(..)
77 , IndexAlias(..)
92 , IndexAlias(..)
78 , IndexAliasName(..)
93 , IndexAliasName(..)
79 , IndexAliasAction(..)
94 , IndexAliasAction(..)
@@ -105,8 +120,8 @@ module Database.Bloodhound.Types
105 , Pattern(..)
120 , Pattern(..)
106 , ShardResult(..)
121 , ShardResult(..)
107 , Hit(..)
122 , Hit(..)
108 , Filter(..)
124 , Filter(..)
110 , BoolMatch(..)
125 , BoolMatch(..)
111 , Term(..)
126 , Term(..)
112 , GeoPoint(..)
127 , GeoPoint(..)
@@ -133,8 +148,22 @@ module Database.Bloodhound.Types
133 , RegexpFlags(..)
148 , RegexpFlags(..)
134 , RegexpFlag(..)
149 , RegexpFlag(..)
135 , FieldName(..)
150 , FieldName(..)
136 , Script(..)
154 , Script(..)
155+ , ScriptLanguage(..)
137 , IndexName(..)
161 , IndexName(..)
162+ , IndexSelection(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
138 , TemplateName(..)
167 , TemplateName(..)
139 , TemplatePattern(..)
168 , TemplatePattern(..)
140 , MappingName(..)
169 , MappingName(..)
@@ -158,8 +187,19 @@ module Database.Bloodhound.Types
158 , BoolQuery(..)
187 , BoolQuery(..)
159 , BoostingQuery(..)
188 , BoostingQuery(..)
160 , CommonTermsQuery(..)
189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
198+ , FieldValueFactor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
161 , DisMaxQuery(..)
202 , DisMaxQuery(..)
163 , FuzzyLikeThisQuery(..)
203 , FuzzyLikeThisQuery(..)
164 , FuzzyLikeFieldQuery(..)
204 , FuzzyLikeFieldQuery(..)
165 , FuzzyQuery(..)
205 , FuzzyQuery(..)
@@ -175,10 +215,16 @@ module Database.Bloodhound.Types
175 , RangeQuery(..)
215 , RangeQuery(..)
176 , RegexpQuery(..)
216 , RegexpQuery(..)
177 , QueryString(..)
217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
178 , BooleanOperator(..)
221 , BooleanOperator(..)
179 , ZeroTermsQuery(..)
222 , ZeroTermsQuery(..)
180 , CutoffFrequency(..)
223 , CutoffFrequency(..)
181 , Analyzer(..)
224 , Analyzer(..)
182 , MaxExpansions(..)
228 , MaxExpansions(..)
183 , Lenient(..)
229 , Lenient(..)
184 , MatchQueryType(..)
230 , MatchQueryType(..)
@@ -225,15 +271,108 @@ module Database.Bloodhound.Types
225 , CollectionMode(..)
271 , CollectionMode(..)
226 , TermOrder(..)
272 , TermOrder(..)
227 , 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 (..)
229 , Aggregation(..)
364 , Aggregation(..)
230 , Aggregations
365 , Aggregations
231 , AggregationResults
366 , AggregationResults
232 , Bucket(..)
368 , Bucket(..)
233 , BucketAggregation(..)
369 , BucketAggregation(..)
234 , TermsAggregation(..)
370 , TermsAggregation(..)
371+ , MissingAggregation(..)
235 , ValueCountAggregation(..)
372 , ValueCountAggregation(..)
236 , FilterAggregation(..)
373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
237 , DateHistogramAggregation(..)
376 , DateHistogramAggregation(..)
238 , DateRangeAggregation(..)
377 , DateRangeAggregation(..)
239 , DateRangeAggRange(..)
378 , DateRangeAggRange(..)
@@ -241,6 +380,9 @@ module Database.Bloodhound.Types
241 , DateMathAnchor(..)
380 , DateMathAnchor(..)
242 , DateMathModifier(..)
381 , DateMathModifier(..)
243 , DateMathUnit(..)
382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
245 , Highlights(..)
387 , Highlights(..)
246 , FieldHighlight(..)
388 , FieldHighlight(..)
@@ -254,645 +396,36 @@ module Database.Bloodhound.Types
254 , HighlightTag(..)
396 , HighlightTag(..)
255 , HitHighlight
397 , HitHighlight
257 , TermsResult(..)
400 , TermsResult(..)
258 , DateHistogramResult(..)
401 , DateHistogramResult(..)
259 , DateRangeResult(..)
402 , DateRangeResult(..)
260− ) where
403+ , TopHitResult(..)
262−import Control.Applicative
405+ , EsUsername(..)
263−import Control.Monad.Catch
406+ , EsPassword(..)
264−import Control.Monad.Except
407+
265−import Control.Monad.Reader
408+ , Analysis(..)
266−import Control.Monad.State
409+ , AnalyzerDefinition(..)
267−import Control.Monad.Writer
410+ , TokenizerDefinition(..)
268−import Data.Aeson
411+ , TokenFilterDefinition(..)
269−import Data.Aeson.Types (Pair, Parser, emptyObject,
412+ , CharFilterDefinition(..)
270− parseMaybe)
413+ , Ngram(..)
271−import qualified Data.ByteString.Lazy.Char8 as L
414+ , TokenChar(..)
272−import Data.Char
415+ , Shingle(..)
273−import Data.Hashable (Hashable)
416+ , Language(..)
274−import qualified Data.HashMap.Strict as HM
417+ ) where
275−import Data.List (foldl', nub)
418+
276−import Data.List.NonEmpty (NonEmpty (..), toList)
419+import Bloodhound.Import
277−import qualified Data.Map.Strict as M
420+
278−import Data.Maybe
421+import Database.Bloodhound.Internal.Aggregation
279−import Data.Text (Text)
422+import Database.Bloodhound.Internal.Analysis
280−import qualified Data.Text as T
423+import Database.Bloodhound.Internal.Client
281−import Data.Time.Calendar
424+import Database.Bloodhound.Internal.Highlight
282−import Data.Time.Clock (NominalDiffTime, UTCTime)
425+import Database.Bloodhound.Internal.Newtypes
283−import Data.Time.Clock.POSIX
426+import Database.Bloodhound.Internal.Query
284−import qualified Data.Traversable as DT
427+import Database.Bloodhound.Internal.Sort
285−import Data.Typeable (Typeable)
428+import Database.Bloodhound.Internal.Suggest
286−import qualified Data.Vector as V
288−import GHC.Generics (Generic)
289−import Network.HTTP.Client
290−import qualified Network.HTTP.Types.Method as NHTM
292−import Database.Bloodhound.Types.Class
295−-- >>> :set -XOverloadedStrings
296−-- >>> import Database.Bloodhound
297−-- >>> let testServer = (Server "http://localhost:9200")
298−-- >>> let testIndex = IndexName "twitter"
299−-- >>> let testMapping = MappingName "tweet"
300−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
302−-- defaultIndexSettings is exported by Database.Bloodhound as well
303−-- no trailing slashes in servers, library handles building the path.
305−{-| Common environment for Elasticsearch calls. Connections will be
306− pipelined according to the provided HTTP connection manager.
308−data BHEnv = BHEnv { bhServer :: Server
309− , bhManager :: Manager
312−{-| All API calls to Elasticsearch operate within
313− MonadBH. The idea is that it can be easily embedded in your
314− own monad transformer stack. A default instance for a ReaderT and
315− alias 'BH' is provided for the simple case.
317−class (Functor m, Applicative m, MonadIO m) => MonadBH m where
320−newtype BH m a = BH {
321− unBH :: ReaderT BHEnv m a
322− } deriving ( Functor
336−instance MonadTrans BH where
339−instance (MonadReader r m) => MonadReader r (BH m) where
341− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
344−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
345− getBHEnv = BH getBHEnv
348−instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where
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−data IndexAlias = IndexAlias { srcIndex :: IndexName
569− , indexAlias :: IndexAliasName } deriving (Eq, Show, Generic, Typeable)
571−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Show, Generic, ToJSON)
573−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
574− | RemoveAlias IndexAlias deriving (Show, Eq, Generic, Typeable)
576−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
577− , aliasCreateFilter :: Maybe Filter}
578− deriving (Show, Eq, Generic, Typeable)
580−data AliasRouting = AllAliasRouting RoutingValue
581− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
582− deriving (Show, Eq, Generic, Typeable)
584−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Show, Eq, Generic, Typeable)
586−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
588−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
590−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Show, Eq, Generic, Typeable)
592−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
593−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
594− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Show, Eq, Generic, Typeable)
596−{-| 'DocVersion' is an integer version number for a document between 1
597−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
599−newtype DocVersion = DocVersion {
600− docVersionNumber :: Int
601− } deriving (Eq, Show, Generic, Ord, ToJSON)
603−-- | Smart constructor for in-range doc version
604−mkDocVersion :: Int -> Maybe DocVersion
606− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
608− | otherwise = Nothing
611−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
612−own version numbers instead of ones from ES.
614−newtype ExternalDocVersion = ExternalDocVersion DocVersion
615− deriving (Eq, Show, Generic, Ord, Bounded, Enum, ToJSON)
617−{-| 'VersionControl' is specified when indexing documents as a
618−optimistic concurrency control.
620−data VersionControl = NoVersionControl
621− -- ^ Don't send a version. This is a pure overwrite.
622− | InternalVersion DocVersion
623− -- ^ Use the default ES versioning scheme. Only
624− -- index the document if the version is the same
625− -- as the one specified. Only applicable to
626− -- updates, as you should be getting Version from
628− | ExternalGT ExternalDocVersion
629− -- ^ Use your own version numbering. Only index
630− -- the document if the version is strictly higher
631− -- OR the document doesn't exist. The given
632− -- version will be used as the new version number
633− -- for the stored document. N.B. All updates must
634− -- increment this number, meaning there is some
635− -- global, external ordering of updates.
636− | ExternalGTE ExternalDocVersion
637− -- ^ Use your own version numbering. Only index
638− -- the document if the version is equal or higher
639− -- than the stored version. Will succeed if there
640− -- is no existing document. The given version will
641− -- be used as the new version number for the
642− -- stored document. Use with care, as this could
643− -- result in data loss.
644− | ForceVersion ExternalDocVersion
645− -- ^ The document will always be indexed and the
646− -- given version will be the new version. This is
647− -- typically used for correcting errors. Use with
648− -- care, as this could result in data loss.
649− deriving (Show, Eq, Generic, Ord)
651−{-| 'DocumentParent' is used to specify a parent document.
653−newtype DocumentParent = DocumentParent DocId
654− deriving (Eq, Show, Generic, Typeable)
656−{-| 'IndexDocumentSettings' are special settings supplied when indexing
657−a document. For the best backwards compatiblity when new fields are
658−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
660−data IndexDocumentSettings =
661− IndexDocumentSettings { idsVersionControl :: VersionControl
662− , idsParent :: Maybe DocumentParent
663− } deriving (Eq, Show, Generic, Typeable)
665−{-| Reasonable default settings. Chooses no version control and no parent.
667−defaultIndexDocumentSettings :: IndexDocumentSettings
668−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
670−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
671− dependent with later sorts acting as tie-breakers for earlier sorts.
673−type Sort = [SortSpec]
675−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
676− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
677− 'DistanceUnit' to express "nearness" to a single geographical point as a
680−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
682−data SortSpec = DefaultSortSpec DefaultSort
683− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show, Generic, Typeable)
685−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
686− 'mkSort' convenience function for when you want to specify only the most
689−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
692− DefaultSort { sortFieldName :: FieldName
693− , sortOrder :: SortOrder
695− , ignoreUnmapped :: Bool
696− , sortMode :: Maybe SortMode
697− , missingSort :: Maybe Missing
698− , nestedFilter :: Maybe Filter } deriving (Eq, Show, Generic, Typeable)
700−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
701− encoded into "asc" or "desc" when turned into JSON.
703−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
705−data SortOrder = Ascending
706− | Descending deriving (Eq, Show, Generic, Typeable)
708−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
709− sorted last, first, or using a custom value as a substitute.
711−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
713−data Missing = LastMissing
715− | CustomMissing Text deriving (Eq, Show, Generic, Typeable)
717−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
719−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
721−data SortMode = SortMin
724− | SortAvg deriving (Eq, Show, Generic, Typeable)
726−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
727− that you can concisely describe the usual kind of 'SortSpec's you want.
729−mkSort :: FieldName -> SortOrder -> DefaultSort
730−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
732−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
733− 'Query's cannot be cached.
735−type Cache = Bool -- caching on/off
736−defaultCache :: Cache
739−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
741−type PrefixValue = Text
743−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
744− JSON encoding baked in. Used all over the place.
746−data BooleanOperator = And | Or deriving (Eq, Show, Generic, Typeable)
748−{-| 'ShardCount' is part of 'IndexSettings'
750−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
752−{-| 'ReplicaCount' is part of 'IndexSettings'
754−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
756−{-| 'Server' is used with the client functions to point at the ES instance
758−newtype Server = Server Text deriving (Eq, Show, Generic, Typeable)
760−{-| 'IndexName' is used to describe which index to query/create/delete
762−newtype IndexName = IndexName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
764−{-| 'TemplateName' is used to describe which template to query/create/delete
766−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
768−{-| 'TemplatePattern' represents a pattern which is matched against index names
770−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
772−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
773− the data in the indices.
775−newtype MappingName = MappingName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
777−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
778− Can be set by the user or created by ES itself. Often used in client
779− functions for poking at specific documents.
781−newtype DocId = DocId Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
783−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
785−newtype QueryString = QueryString Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
787−{-| 'FieldName' is used all over the place wherever a specific field within
788− a document needs to be specified, usually in 'Query's or 'Filter's.
790−newtype FieldName = FieldName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
793−{-| 'Script' is often used in place of 'FieldName' to specify more
794−complex ways of extracting a value from a document.
796−newtype Script = Script { scriptText :: Text } deriving (Eq, Show, Generic, Typeable)
798−{-| 'CacheName' is used in 'RegexpFilter' for describing the
799− 'CacheKey' keyed caching behavior.
801−newtype CacheName = CacheName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
803−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
806− CacheKey Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
808− Existence Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
810− NullValue Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
811−newtype CutoffFrequency =
812− CutoffFrequency Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
814− Analyzer Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
815−newtype MaxExpansions =
816− MaxExpansions Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
818−{-| 'Lenient', if set to true, will cause format based failures to be
819− ignored. I don't know what the bloody default is, Elasticsearch
820− documentation didn't say what it was. Let me know if you figure it out.
823− Lenient Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
825− Tiebreaker Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
827− Boost Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
829− BoostTerms Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
831−{-| 'MinimumMatch' controls how many should clauses in the bool query should
832− match. Can be an absolute value (2) or a percentage (30%) or a
833− combination of both.
835−newtype MinimumMatch =
836− MinimumMatch Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
837−newtype DisableCoord =
838− DisableCoord Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
839−newtype IgnoreTermFrequency =
840− IgnoreTermFrequency Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
841−newtype MinimumTermFrequency =
842− MinimumTermFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
843−newtype MaxQueryTerms =
844− MaxQueryTerms Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
846− Fuzziness Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
848−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
849−newtype PrefixLength =
850− PrefixLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
852− TypeName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
853−newtype PercentMatch =
854− PercentMatch Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
856− StopWord Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
858− QueryPath Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
860−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
861− heavy, because all terms in the index need to be examined, just in case
862− they match. Leading wildcards can be disabled by setting
863− 'AllowLeadingWildcard' to false. -}
864−newtype AllowLeadingWildcard =
865− AllowLeadingWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
866−newtype LowercaseExpanded =
867− LowercaseExpanded Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
868−newtype EnablePositionIncrements =
869− EnablePositionIncrements Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
871−{-| By default, wildcard terms in a query are not analyzed.
872− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
874−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
876−{-| 'GeneratePhraseQueries' defaults to false.
878−newtype GeneratePhraseQueries =
879− GeneratePhraseQueries Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
881−{-| 'Locale' is used for string conversions - defaults to ROOT.
883−newtype Locale = Locale Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
884−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
885−newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
887−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
888− phrase matches. Default is 0.
890−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
891−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
892−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
894−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
895−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
897{-| 'unpackId' is a silly convenience function that gets used once.
430{-| 'unpackId' is a silly convenience function that gets used once.
@@ -900,8 +433,6 @@ unpackId :: DocId -> Text
900unpackId (DocId docId) = docId
433unpackId (DocId docId) = docId
902type TrackSortScores = Bool
435type TrackSortScores = Bool
903−newtype From = From Int deriving (Eq, Show, Generic, ToJSON)
904−newtype Size = Size Int deriving (Eq, Show, Generic, ToJSON)
906data Search = Search { queryBody :: Maybe Query
437data Search = Search { queryBody :: Maybe Query
907 , filterBody :: Maybe Filter
438 , filterBody :: Maybe Filter
@@ -913,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
913 , from :: From
444 , from :: From
914 , size :: Size
445 , size :: Size
915 , searchType :: SearchType
446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
916 , fields :: Maybe [FieldName]
448 , fields :: Maybe [FieldName]
449+ , scriptFields :: Maybe ScriptFields
917− , 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)
919data SearchType = SearchTypeQueryThenFetch
480data SearchType = SearchTypeQueryThenFetch
920 | SearchTypeDfsQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
923− | SearchTypeQueryAndFetch
924− | SearchTypeDfsQueryAndFetch
925− deriving (Eq, Show, Generic, Typeable)
482+ deriving (Eq, Show)
927data Source =
484data Source =
929 | SourcePatterns PatternOrPatterns
486 | SourcePatterns PatternOrPatterns
930 | SourceIncludeExclude Include Exclude
487 | SourceIncludeExclude Include Exclude
931− deriving (Show, Eq, Generic, Typeable)
488+ deriving (Eq, Show)
933−data PatternOrPatterns = PopPattern Pattern
934− | PopPatterns [Pattern] deriving (Eq, Show, Generic, Typeable)
936−data Include = Include [Pattern] deriving (Eq, Show, Generic, Typeable)
937−data Exclude = Exclude [Pattern] deriving (Eq, Show, Generic, Typeable)
939−newtype Pattern = Pattern Text deriving (Eq, Show, Generic, Typeable)
941−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
942− , highlightFields :: [FieldHighlight]
943− } deriving (Show, Eq, Generic, Typeable)
945−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
946− deriving (Show, Eq, Generic, Typeable)
949−data HighlightSettings = Plain PlainHighlight
950− | Postings PostingsHighlight
951− | FastVector FastVectorHighlight
952− deriving (Show, Eq, Generic, Typeable)
953−data PlainHighlight =
954− PlainHighlight { plainCommon :: Maybe CommonHighlight
955− , plainNonPost :: Maybe NonPostings } deriving (Show, Eq, Generic, Typeable)
957− -- This requires that index_options are set to 'offset' in the mapping.
958−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq, Generic, Typeable)
960−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
961−data FastVectorHighlight =
962− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
963− , fvNonPostSettings :: Maybe NonPostings
964− , boundaryChars :: Maybe Text
965− , boundaryMaxScan :: Maybe Int
966− , fragmentOffset :: Maybe Int
967− , matchedFields :: [Text]
968− , phraseLimit :: Maybe Int
969− } deriving (Show, Eq, Generic, Typeable)
971−data CommonHighlight =
972− CommonHighlight { order :: Maybe Text
973− , forceSource :: Maybe Bool
974− , tag :: Maybe HighlightTag
975− , encoder :: Maybe HighlightEncoder
976− , noMatchSize :: Maybe Int
977− , highlightQuery :: Maybe Query
978− , requireFieldMatch :: Maybe Bool
979− } deriving (Show, Eq, Generic, Typeable)
981−-- Settings that are only applicable to FastVector and Plain highlighters.
983− NonPostings { fragmentSize :: Maybe Int
984− , numberOfFragments :: Maybe Int} deriving (Show, Eq, Generic, Typeable)
986−data HighlightEncoder = DefaultEncoder
988− deriving (Show, Eq, Generic, Typeable)
990−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
991−data HighlightTag = TagSchema Text
992− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
993− deriving (Show, Eq, Generic, Typeable)
997− TermQuery Term (Maybe Boost)
998− | TermsQuery Text (NonEmpty Text)
999− | QueryMatchQuery MatchQuery
1000− | QueryMultiMatchQuery MultiMatchQuery
1001− | QueryBoolQuery BoolQuery
1002− | QueryBoostingQuery BoostingQuery
1003− | QueryCommonTermsQuery CommonTermsQuery
1004− | ConstantScoreFilter Filter Boost
1005− | ConstantScoreQuery Query Boost
1006− | QueryDisMaxQuery DisMaxQuery
1007− | QueryFilteredQuery FilteredQuery
1008− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1009− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1010− | QueryFuzzyQuery FuzzyQuery
1011− | QueryHasChildQuery HasChildQuery
1012− | QueryHasParentQuery HasParentQuery
1013− | IdsQuery MappingName [DocId]
1014− | QueryIndicesQuery IndicesQuery
1015− | MatchAllQuery (Maybe Boost)
1016− | QueryMoreLikeThisQuery MoreLikeThisQuery
1017− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1018− | QueryNestedQuery NestedQuery
1019− | QueryPrefixQuery PrefixQuery
1020− | QueryQueryStringQuery QueryStringQuery
1021− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1022− | QueryRangeQuery RangeQuery
1023− | QueryRegexpQuery RegexpQuery
1024− deriving (Eq, Show, Generic, Typeable)
1027− RegexpQuery { regexpQueryField :: FieldName
1028− , regexpQuery :: Regexp
1029− , regexpQueryFlags :: RegexpFlags
1030− , regexpQueryBoost :: Maybe Boost
1031− } deriving (Eq, Show, Generic, Typeable)
1034− RangeQuery { rangeQueryField :: FieldName
1035− , rangeQueryRange :: RangeValue
1036− , rangeQueryBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1038−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1039−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1041−data SimpleQueryStringQuery =
1042− SimpleQueryStringQuery
1043− { simpleQueryStringQuery :: QueryString
1044− , simpleQueryStringField :: Maybe FieldOrFields
1045− , simpleQueryStringOperator :: Maybe BooleanOperator
1046− , simpleQueryStringAnalyzer :: Maybe Analyzer
1047− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1048− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1049− , simpleQueryStringLocale :: Maybe Locale
1050− } deriving (Eq, Show, Generic, Typeable)
1052−data SimpleQueryFlag =
1057− | SimpleQueryPrefix
1058− | SimpleQueryPhrase
1059− | SimpleQueryPrecedence
1060− | SimpleQueryEscape
1061− | SimpleQueryWhitespace
1064− | SimpleQuerySlop deriving (Eq, Show, Generic, Typeable)
1066−-- use_dis_max and tie_breaker when fields are plural?
1067−data QueryStringQuery =
1069− { queryStringQuery :: QueryString
1070− , queryStringDefaultField :: Maybe FieldName
1071− , queryStringOperator :: Maybe BooleanOperator
1072− , queryStringAnalyzer :: Maybe Analyzer
1073− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1074− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1075− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1076− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1077− , queryStringFuzziness :: Maybe Fuzziness
1078− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1079− , queryStringPhraseSlop :: Maybe PhraseSlop
1080− , queryStringBoost :: Maybe Boost
1081− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1082− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1083− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1084− , queryStringLenient :: Maybe Lenient
1085− , queryStringLocale :: Maybe Locale
1086− } deriving (Eq, Show, Generic, Typeable)
1088−mkQueryStringQuery :: QueryString -> QueryStringQuery
1089−mkQueryStringQuery qs =
1090− QueryStringQuery qs Nothing Nothing
1091− Nothing Nothing Nothing Nothing
1092− Nothing Nothing Nothing Nothing
1093− Nothing Nothing Nothing Nothing
1096−data FieldOrFields = FofField FieldName
1097− | FofFields (NonEmpty FieldName) deriving (Eq, Show, Generic, Typeable)
1101− { prefixQueryField :: FieldName
1102− , prefixQueryPrefixValue :: Text
1103− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1107− { nestedQueryPath :: QueryPath
1108− , nestedQueryScoreType :: ScoreType
1109− , nestedQuery :: Query } deriving (Eq, Show, Generic, Typeable)
1111−data MoreLikeThisFieldQuery =
1112− MoreLikeThisFieldQuery
1113− { moreLikeThisFieldText :: Text
1114− , moreLikeThisFieldFields :: FieldName
1115− -- default 0.3 (30%)
1116− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1117− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1118− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1119− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1120− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1121− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1122− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1123− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1124− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1125− , moreLikeThisFieldBoost :: Maybe Boost
1126− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1127− } deriving (Eq, Show, Generic, Typeable)
1129−data MoreLikeThisQuery =
1131− { moreLikeThisText :: Text
1132− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1133− -- default 0.3 (30%)
1134− , moreLikeThisPercentMatch :: Maybe PercentMatch
1135− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1136− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1137− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1138− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1139− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1140− , moreLikeThisMinWordLength :: Maybe MinWordLength
1141− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1142− , moreLikeThisBoostTerms :: Maybe BoostTerms
1143− , moreLikeThisBoost :: Maybe Boost
1144− , moreLikeThisAnalyzer :: Maybe Analyzer
1145− } deriving (Eq, Show, Generic, Typeable)
1149− { indicesQueryIndices :: [IndexName]
1150− , indicesQuery :: Query
1152− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show, Generic, Typeable)
1154−data HasParentQuery =
1156− { hasParentQueryType :: TypeName
1157− , hasParentQuery :: Query
1158− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1160−data HasChildQuery =
1162− { hasChildQueryType :: TypeName
1163− , hasChildQuery :: Query
1164− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1170− | ScoreTypeNone deriving (Eq, Show, Generic, Typeable)
1173− FuzzyQuery { fuzzyQueryField :: FieldName
1174− , fuzzyQueryValue :: Text
1175− , fuzzyQueryPrefixLength :: PrefixLength
1176− , fuzzyQueryMaxExpansions :: MaxExpansions
1177− , fuzzyQueryFuzziness :: Fuzziness
1178− , fuzzyQueryBoost :: Maybe Boost
1179− } deriving (Eq, Show, Generic, Typeable)
1181−data FuzzyLikeFieldQuery =
1182− FuzzyLikeFieldQuery
1183− { fuzzyLikeField :: FieldName
1184− -- anaphora is good for the soul.
1185− , fuzzyLikeFieldText :: Text
1186− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1187− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1188− , fuzzyLikeFieldFuzziness :: Fuzziness
1189− , fuzzyLikeFieldPrefixLength :: PrefixLength
1190− , fuzzyLikeFieldBoost :: Boost
1191− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1192− } deriving (Eq, Show, Generic, Typeable)
1194−data FuzzyLikeThisQuery =
1196− { fuzzyLikeFields :: [FieldName]
1197− , fuzzyLikeText :: Text
1198− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1199− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1200− , fuzzyLikeFuzziness :: Fuzziness
1201− , fuzzyLikePrefixLength :: PrefixLength
1202− , fuzzyLikeBoost :: Boost
1203− , fuzzyLikeAnalyzer :: Maybe Analyzer
1204− } deriving (Eq, Show, Generic, Typeable)
1206−data FilteredQuery =
1208− { filteredQuery :: Query
1209− , filteredFilter :: Filter } deriving (Eq, Show, Generic, Typeable)
1212− DisMaxQuery { disMaxQueries :: [Query]
1214− , disMaxTiebreaker :: Tiebreaker
1215− , disMaxBoost :: Maybe Boost
1216− } deriving (Eq, Show, Generic, Typeable)
1219− MatchQuery { matchQueryField :: FieldName
1220− , matchQueryQueryString :: QueryString
1221− , matchQueryOperator :: BooleanOperator
1222− , matchQueryZeroTerms :: ZeroTermsQuery
1223− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1224− , matchQueryMatchType :: Maybe MatchQueryType
1225− , matchQueryAnalyzer :: Maybe Analyzer
1226− , matchQueryMaxExpansions :: Maybe MaxExpansions
1227− , matchQueryLenient :: Maybe Lenient
1228− , matchQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1230−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
490+instance ToJSON Source where
1231− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
491+ toJSON NoSource = toJSON False
1232−-}
492+ toJSON (SourcePatterns patterns) = toJSON patterns
1233−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1234−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1236−data MatchQueryType =
1238− | MatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1240−data MultiMatchQuery =
1241− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1242− , multiMatchQueryString :: QueryString
1243− , multiMatchQueryOperator :: BooleanOperator
1244− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1245− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1246− , multiMatchQueryType :: Maybe MultiMatchQueryType
1247− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1248− , multiMatchQueryAnalyzer :: Maybe Analyzer
1249− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1250− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show, Generic, Typeable)
1252−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1253− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1254− make a 'MultiMatchQuery'.
1257−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1258−mkMultiMatchQuery matchFields query =
1259− MultiMatchQuery matchFields query
1260− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1262−data MultiMatchQueryType =
1263− MultiMatchBestFields
1264− | MultiMatchMostFields
1265− | MultiMatchCrossFields
1267− | MultiMatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1270− BoolQuery { boolQueryMustMatch :: [Query]
1271− , boolQueryMustNotMatch :: [Query]
1272− , boolQueryShouldMatch :: [Query]
1273− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1274− , boolQueryBoost :: Maybe Boost
1275− , boolQueryDisableCoord :: Maybe DisableCoord
1276− } deriving (Eq, Show, Generic, Typeable)
1278−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1279−mkBoolQuery must mustNot should =
1280− BoolQuery must mustNot should Nothing Nothing Nothing
1282−data BoostingQuery =
1283− BoostingQuery { positiveQuery :: Query
1284− , negativeQuery :: Query
1285− , negativeBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1287−data CommonTermsQuery =
1288− CommonTermsQuery { commonField :: FieldName
1289− , commonQuery :: QueryString
1290− , commonCutoffFrequency :: CutoffFrequency
1291− , commonLowFreqOperator :: BooleanOperator
1292− , commonHighFreqOperator :: BooleanOperator
1293− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1294− , commonBoost :: Maybe Boost
1295− , commonAnalyzer :: Maybe Analyzer
1296− , commonDisableCoord :: Maybe DisableCoord
1297− } deriving (Eq, Show, Generic, Typeable)
1299−data CommonMinimumMatch =
1300− CommonMinimumMatchHighLow MinimumMatchHighLow
1301− | CommonMinimumMatch MinimumMatch
1302− deriving (Eq, Show, Generic, Typeable)
1304−data MinimumMatchHighLow =
1305− MinimumMatchHighLow { lowFreq :: MinimumMatch
1306− , highFreq :: MinimumMatch } deriving (Eq, Show, Generic, Typeable)
1308−data Filter = AndFilter [Filter] Cache
1309− | OrFilter [Filter] Cache
1310− | NotFilter Filter Cache
1312− | BoolFilter BoolMatch
1313− | ExistsFilter FieldName -- always cached
1314− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1315− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1316− | GeoDistanceRangeFilter GeoPoint DistanceRange
1317− | GeoPolygonFilter FieldName [LatLon]
1318− | IdsFilter MappingName [DocId]
1320− | MissingFilter FieldName Existence NullValue
1321− | PrefixFilter FieldName PrefixValue Cache
1322− | QueryFilter Query Cache
1323− | RangeFilter FieldName RangeValue RangeExecution Cache
1324− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1325− | TermFilter Term Cache
1326− deriving (Eq, Show, Generic, Typeable)
1328−data ZeroTermsQuery = ZeroTermsNone
1329− | ZeroTermsAll deriving (Eq, Show, Generic, Typeable)
1331−data RangeExecution = RangeExecutionIndex
1332− | RangeExecutionFielddata deriving (Eq, Show, Generic, Typeable)
1334−newtype Regexp = Regexp Text deriving (Eq, Show, Generic, FromJSON)
1336−data RegexpFlags = AllRegexpFlags
1338− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show, Generic, Typeable)
1340−data RegexpFlag = AnyString
1345− | Interval deriving (Eq, Show, Generic, Typeable)
1347−newtype LessThan = LessThan Double deriving (Eq, Show, Generic, Typeable)
1348−newtype LessThanEq = LessThanEq Double deriving (Eq, Show, Generic, Typeable)
1349−newtype GreaterThan = GreaterThan Double deriving (Eq, Show, Generic, Typeable)
1350−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show, Generic, Typeable)
1352−newtype LessThanD = LessThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1353−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1354−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1355−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1357−data RangeValue = RangeDateLte LessThanEqD
1358− | RangeDateLt LessThanD
1359− | RangeDateGte GreaterThanEqD
1360− | RangeDateGt GreaterThanD
1361− | RangeDateGtLt GreaterThanD LessThanD
1362− | RangeDateGteLte GreaterThanEqD LessThanEqD
1363− | RangeDateGteLt GreaterThanEqD LessThanD
1364− | RangeDateGtLte GreaterThanD LessThanEqD
1365− | RangeDoubleLte LessThanEq
1366− | RangeDoubleLt LessThan
1367− | RangeDoubleGte GreaterThanEq
1368− | RangeDoubleGt GreaterThan
1369− | RangeDoubleGtLt GreaterThan LessThan
1370− | RangeDoubleGteLte GreaterThanEq LessThanEq
1371− | RangeDoubleGteLt GreaterThanEq LessThan
1372− | RangeDoubleGtLte GreaterThan LessThanEq
1373− deriving (Eq, Show, Generic, Typeable)
1375−rangeValueToPair :: RangeValue -> [Pair]
1376−rangeValueToPair rv = case rv of
1377− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1378− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1379− RangeDateLt (LessThanD t) -> ["lt" .= t]
1380− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1381− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1382− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1383− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1384− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1385− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1386− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1387− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1388− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1389− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1390− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1391− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1392− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1394−data Term = Term { termField :: Text
1395− , termValue :: Text } deriving (Eq, Show, Generic, Typeable)
1397−data BoolMatch = MustMatch Term Cache
1398− | MustNotMatch Term Cache
1399− | ShouldMatch [Term] Cache deriving (Eq, Show, Generic, Typeable)
1401−-- "memory" or "indexed"
1402−data GeoFilterType = GeoFilterMemory
1403− | GeoFilterIndexed deriving (Eq, Show, Generic, Typeable)
1405−data LatLon = LatLon { lat :: Double
1406− , lon :: Double } deriving (Eq, Show, Generic, Typeable)
1408−data GeoBoundingBox =
1409− GeoBoundingBox { topLeft :: LatLon
1410− , bottomRight :: LatLon } deriving (Eq, Show, Generic, Typeable)
1412−data GeoBoundingBoxConstraint =
495+data PatternOrPatterns = PopPattern Pattern
1413− GeoBoundingBoxConstraint { geoBBField :: FieldName
1414− , constraintBox :: GeoBoundingBox
1415− , bbConstraintcache :: Cache
1416− , geoType :: GeoFilterType
1417− } deriving (Eq, Show, Generic, Typeable)
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1419−data GeoPoint =
498+instance ToJSON PatternOrPatterns where
1420− GeoPoint { geoField :: FieldName
499+ toJSON (PopPattern pattern) = toJSON pattern
1421− , latLon :: LatLon} deriving (Eq, Show, Generic, Typeable)
500+ toJSON (PopPatterns patterns) = toJSON patterns
1423−data DistanceUnit = Miles
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
1424− | Yards
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1431− | NauticalMiles deriving (Eq, Show, Generic, Typeable)
1433−data DistanceType = Arc
505+instance ToJSON Include where
1434− | SloppyArc -- doesn't exist <1.0
506+ toJSON (Include patterns) = toJSON patterns
1435− | Plane deriving (Eq, Show, Generic, Typeable)
1437−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
508+instance ToJSON Exclude where
1438− | NoOptimizeBbox deriving (Eq, Show, Generic, Typeable)
509+ toJSON (Exclude patterns) = toJSON patterns
1440−data Distance =
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1441− Distance { coefficient :: Double
1442− , unit :: DistanceUnit } deriving (Eq, Show, Generic, Typeable)
1444−data DistanceRange =
513+instance ToJSON Pattern where
1445− DistanceRange { distanceFrom :: Distance
514+ toJSON (Pattern pattern) = toJSON pattern
1446− , distanceTo :: Distance } deriving (Eq, Show, Generic, Typeable)
1448data SearchResult a =
516data SearchResult a =
1449 SearchResult { took :: Int
517 SearchResult { took :: Int
@@ -1451,2018 +519,12 @@ data SearchResult a =
1451 , shards :: ShardResult
519 , shards :: ShardResult
1452 , searchHits :: SearchHits a
520 , searchHits :: SearchHits a
1453 , aggregations :: Maybe AggregationResults
521 , aggregations :: Maybe AggregationResults
1454− , scrollId :: Maybe ScrollId } deriving (Eq, Show, Generic, Typeable)
522+ , scrollId :: Maybe ScrollId
1455−
523+ -- ^ Only one Suggestion request / response per
1456−newtype ScrollId = ScrollId Text deriving (Eq, Show, Generic, Ord, ToJSON, FromJSON)
524+ -- Search is supported.
1457−
525+ , suggest :: Maybe NamedSuggestionResponse
1458−type Score = Maybe Double
526+ }
1459−
527+ deriving (Eq, Show)
1461− SearchHits { hitsTotal :: Int
1462− , maxScore :: Score
1463− , hits :: [Hit a] } deriving (Eq, Show, Generic, Typeable)
1466−instance Monoid (SearchHits a) where
1467− mempty = SearchHits 0 Nothing mempty
1468− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1469− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1473− Hit { hitIndex :: IndexName
1474− , hitType :: MappingName
1475− , hitDocId :: DocId
1476− , hitScore :: Score
1477− , hitSource :: Maybe a
1478− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show, Generic, Typeable)
1481− ShardResult { shardTotal :: Int
1482− , shardsSuccessful :: Int
1483− , shardsFailed :: Int } deriving (Eq, Show, Generic, Typeable)
1485−type HitHighlight = M.Map Text [Text]
1487−showText :: Show a => a -> Text
1488−showText = T.pack . show
1490−readMay :: Read a => String -> Maybe a
1491−readMay s = case reads s of
1492− (a, ""):_ -> Just a
1495−parseReadText :: Read a => Text -> Parser a
1496−parseReadText = maybe mzero return . readMay . T.unpack
1498−type Aggregations = M.Map Text Aggregation
1500−emptyAggregations :: Aggregations
1501−emptyAggregations = M.empty
1503−mkAggregations :: Text -> Aggregation -> Aggregations
1504−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1506−data TermOrder = TermOrder{ termSortField :: Text
1507− , termSortOrder :: SortOrder } deriving (Eq, Show, Generic, Typeable)
1509−data TermInclusion = TermInclusion Text
1510− | TermPattern Text Text deriving (Eq, Show, Generic, Typeable)
1512−data CollectionMode = BreadthFirst
1513− | DepthFirst deriving (Eq, Show, Generic, Typeable)
1515−data ExecutionHint = Ordinals
1517− | GlobalOrdinalsHash
1518− | GlobalOrdinalsLowCardinality
1519− | Map deriving (Eq, Show, Generic, Typeable)
1521−data TimeInterval = Weeks
1525− | Seconds deriving (Eq)
1527−data Interval = Year
1535− | FractionalInterval Float TimeInterval deriving (Eq, Show, Generic, Typeable)
1537−data Aggregation = TermsAgg TermsAggregation
1538− | DateHistogramAgg DateHistogramAggregation
1539− | ValueCountAgg ValueCountAggregation
1540− | FilterAgg FilterAggregation
1541− | DateRangeAgg DateRangeAggregation deriving (Eq, Show, Generic, Typeable)
1544−data TermsAggregation = TermsAggregation { term :: Either Text Text
1545− , termInclude :: Maybe TermInclusion
1546− , termExclude :: Maybe TermInclusion
1547− , termOrder :: Maybe TermOrder
1548− , termMinDocCount :: Maybe Int
1549− , termSize :: Maybe Int
1550− , termShardSize :: Maybe Int
1551− , termCollectMode :: Maybe CollectionMode
1552− , termExecutionHint :: Maybe ExecutionHint
1553− , termAggs :: Maybe Aggregations
1554− } deriving (Eq, Show, Generic, Typeable)
1556−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1557− , dateInterval :: Interval
1558− , dateFormat :: Maybe Text
1559− -- pre and post deprecated in 1.5
1560− , datePreZone :: Maybe Text
1561− , datePostZone :: Maybe Text
1562− , datePreOffset :: Maybe Text
1563− , datePostOffset :: Maybe Text
1564− , dateAggs :: Maybe Aggregations
1565− } deriving (Eq, Show, Generic, Typeable)
1568−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1569− , draFormat :: Maybe Text
1570− , draRanges :: NonEmpty DateRangeAggRange
1571− } deriving (Eq, Show, Generic, Typeable)
1573−data DateRangeAggRange = DateRangeFrom DateMathExpr
1574− | DateRangeTo DateMathExpr
1575− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Show, Generic, Typeable)
1577−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1578−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Show, Generic, Typeable)
1581−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1582−data DateMathAnchor = DMNow
1583− | DMDate Day deriving (Eq, Show, Generic, Typeable)
1585−data DateMathModifier = AddTime Int DateMathUnit
1586− | SubtractTime Int DateMathUnit
1587− | RoundDownTo DateMathUnit deriving (Eq, Show, Generic, Typeable)
1589−data DateMathUnit = DMYear
1595− | DMSecond deriving (Eq, Show, Generic, Typeable)
1597−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1598−data ValueCountAggregation = FieldValueCount FieldName
1599− | ScriptValueCount Script deriving (Eq, Show, Generic, Typeable)
1601−-- | 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.
1602−data FilterAggregation = FilterAggregation { faFilter :: Filter
1603− , faAggs :: Maybe Aggregations} deriving (Eq, Show, Generic, Typeable)
1605−mkTermsAggregation :: Text -> TermsAggregation
1606−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1608−mkTermsScriptAggregation :: Text -> TermsAggregation
1609−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1611−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1612−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1614−instance ToJSON Version where
1615− toJSON Version {..} = object ["number" .= number
1616− ,"build_hash" .= build_hash
1617− ,"build_timestamp" .= build_timestamp
1618− ,"build_snapshot" .= build_snapshot
1619− ,"lucene_version" .= lucene_version]
1621−instance FromJSON Version where
1622− parseJSON = withObject "Version" parse
1623− where parse o = Version
1625− <*> o .: "build_hash"
1626− <*> o .: "build_timestamp"
1627− <*> o .: "build_snapshot"
1628− <*> o .: "lucene_version"
1630−instance ToJSON TermOrder where
1631− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1633−instance ToJSON TermInclusion where
1634− toJSON (TermInclusion x) = toJSON x
1635− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1638−instance ToJSON CollectionMode where
1639− toJSON BreadthFirst = "breadth_first"
1640− toJSON DepthFirst = "depth_first"
1642−instance ToJSON ExecutionHint where
1643− toJSON Ordinals = "ordinals"
1644− toJSON GlobalOrdinals = "global_ordinals"
1645− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1646− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1649−instance ToJSON Interval where
1650− toJSON Year = "year"
1651− toJSON Quarter = "quarter"
1652− toJSON Month = "month"
1653− toJSON Week = "week"
1655− toJSON Hour = "hour"
1656− toJSON Minute = "minute"
1657− toJSON Second = "second"
1658− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1660−instance Show TimeInterval where
1667−instance ToJSON Aggregation where
1668− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1669− omitNulls ["terms" .= omitNulls [ toJSON' term,
1670− "include" .= include,
1671− "exclude" .= exclude,
1673− "min_doc_count" .= minDocCount,
1675− "shard_size" .= shardSize,
1676− "collect_mode" .= collectMode,
1677− "execution_hint" .= executionHint
1679− "aggs" .= termAggs ]
1681− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1683− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1684− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1685− "interval" .= interval,
1686− "format" .= format,
1687− "pre_zone" .= preZone,
1688− "post_zone" .= postZone,
1689− "pre_offset" .= preOffset,
1690− "post_offset" .= postOffset
1692− "aggs" .= dateHistoAggs ]
1693− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1694− where v = case a of
1695− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1696− (ScriptValueCount (Script s)) -> object ["script" .= s]
1697− toJSON (FilterAgg (FilterAggregation filt ags)) =
1698− omitNulls [ "filter" .= filt
1700− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1703−instance ToJSON DateRangeAggregation where
1704− toJSON DateRangeAggregation {..} =
1705− omitNulls [ "field" .= draField
1706− , "format" .= draFormat
1707− , "ranges" .= toList draRanges
1710−instance ToJSON DateRangeAggRange where
1711− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1712− toJSON (DateRangeTo e) = object [ "to" .= e ]
1713− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1715−instance ToJSON DateMathExpr where
1716− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1717− where fmtA DMNow = "now"
1718− fmtA (DMDate date) = case toGregorian date of
1719− (y,m,d) -> showText y <> "-" <>
1720− showText m <> "-" <>
1722− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1723− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1724− fmtMod (RoundDownTo u) = "/" <> fmtU u
1730− fmtU DMMinute = "m"
1731− fmtU DMSecond = "s"
1734−type AggregationResults = M.Map Text Value
1736−class BucketAggregation a where
1738− docCount :: a -> Int
1739− aggs :: a -> Maybe AggregationResults
1742−data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1744−data TermsResult = TermsResult { termKey :: Text
1745− , termsDocCount :: Int
1746− , termsAggs :: Maybe AggregationResults } deriving (Show)
1748−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1749− , dateKeyStr :: Maybe Text
1750− , dateDocCount :: Int
1751− , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1753−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1754− , dateRangeFrom :: Maybe UTCTime
1755− , dateRangeFromAsString :: Maybe Text
1756− , dateRangeTo :: Maybe UTCTime
1757− , dateRangeToAsString :: Maybe Text
1758− , dateRangeDocCount :: Int
1759− , dateRangeAggs :: Maybe AggregationResults } deriving (Show, Eq, Generic, Typeable)
1761−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1762−toTerms t a = M.lookup t a >>= deserialize
1763− where deserialize = parseMaybe parseJSON
1765−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1766−toDateHistogram t a = M.lookup t a >>= deserialize
1767− where deserialize = parseMaybe parseJSON
1769−instance BucketAggregation TermsResult where
1771− docCount = termsDocCount
1774−instance BucketAggregation DateHistogramResult where
1775− key = showText . dateKey
1776− docCount = dateDocCount
1777− aggs = dateHistogramAggs
1779−instance BucketAggregation DateRangeResult where
1781− docCount = dateRangeDocCount
1782− aggs = dateRangeAggs
1784−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1785− parseJSON (Object v) = Bucket <$>
1787− parseJSON _ = mempty
1789−instance FromJSON TermsResult where
1790− parseJSON (Object v) = TermsResult <$>
1792− v .: "doc_count" <*>
1793− v .:? "aggregations"
1794− parseJSON _ = mempty
1796−instance FromJSON DateHistogramResult where
1797− parseJSON (Object v) = DateHistogramResult <$>
1799− v .:? "key_as_string" <*>
1800− v .: "doc_count" <*>
1801− v .:? "aggregations"
1802− parseJSON _ = mempty
1804−instance FromJSON DateRangeResult where
1805− parseJSON = withObject "DateRangeResult" parse
1806− where parse v = DateRangeResult <$>
1808− (fmap posixMS <$> v .:? "from") <*>
1809− v .:? "from_as_string" <*>
1810− (fmap posixMS <$> v .:? "to") <*>
1811− v .:? "to_as_string" <*>
1812− v .: "doc_count" <*>
1813− v .:? "aggregations"
1815−instance FromJSON POSIXMS where
1816− parseJSON = withScientific "POSIXMS" (return . parse)
1817− where parse n = let n' = truncate n :: Integer
1818− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1820−instance Monoid Filter where
1821− mempty = IdentityFilter
1822− mappend a b = AndFilter [a, b] defaultCache
1824−instance Seminearring Filter where
1825− a <||> b = OrFilter [a, b] defaultCache
1827−instance ToJSON Filter where
1828− toJSON (AndFilter filters cache) =
1830− object [ "filters" .= fmap toJSON filters
1831− , "_cache" .= cache]]
1833− toJSON (OrFilter filters cache) =
1835− object [ "filters" .= fmap toJSON filters
1836− , "_cache" .= cache]]
1838− toJSON (NotFilter notFilter cache) =
1840− object ["filter" .= notFilter
1841− , "_cache" .= cache]]
1843− toJSON (IdentityFilter) =
1844− object ["match_all" .= object []]
1846− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1847− object ["term" .= object base]
1848− where base = [termFilterField .= termFilterValue,
1851− toJSON (ExistsFilter (FieldName fieldName)) =
1852− object ["exists" .= object
1853− ["field" .= fieldName]]
1855− toJSON (BoolFilter boolMatch) =
1856− object ["bool" .= boolMatch]
1858− toJSON (GeoBoundingBoxFilter bbConstraint) =
1859− object ["geo_bounding_box" .= bbConstraint]
1861− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1862− distance distanceType optimizeBbox cache) =
1863− object ["geo_distance" .=
1864− object ["distance" .= distance
1865− , "distance_type" .= distanceType
1866− , "optimize_bbox" .= optimizeBbox
1867− , distanceGeoField .= geoDistLatLon
1868− , "_cache" .= cache]]
1870− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1871− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1872− object ["geo_distance_range" .=
1873− object ["from" .= geoDistRangeDistFrom
1874− , "to" .= drDistanceTo
1875− , gddrField .= drLatLon]]
1877− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1878− object ["geo_polygon" .=
1879− object [geoPolygonFilterField .=
1880− object ["points" .= fmap toJSON latLons]]]
1882− toJSON (IdsFilter (MappingName mappingName) values) =
1884− object ["type" .= mappingName
1885− , "values" .= fmap unpackId values]]
1887− toJSON (LimitFilter limit) =
1888− object ["limit" .= object ["value" .= limit]]
1890− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1891− object ["missing" .=
1892− object ["field" .= fieldName
1893− , "existence" .= existence
1894− , "null_value" .= nullValue]]
1896− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1897− object ["prefix" .=
1898− object [fieldName .= fieldValue
1899− , "_cache" .= cache]]
1901− toJSON (QueryFilter query False) =
1902− object ["query" .= toJSON query ]
1903− toJSON (QueryFilter query True) =
1904− object ["fquery" .=
1905− object [ "query" .= toJSON query
1906− , "_cache" .= True ]]
1908− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1910− object [ fieldName .= object (rangeValueToPair rangeValue)
1911− , "execution" .= rangeExecution
1912− , "_cache" .= cache]]
1914− toJSON (RegexpFilter (FieldName fieldName)
1915− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1916− object ["regexp" .=
1917− object [fieldName .=
1918− object ["value" .= regexText
1919− , "flags" .= flags]
1920− , "_name" .= cacheName
1921− , "_cache" .= cache
1922− , "_cache_key" .= cacheKey]]
1924−instance FromJSON Filter where
1925− parseJSON = withObject "Filter" parse
1926− where parse o = andFilter `taggedWith` "and"
1927− <|> orFilter `taggedWith` "or"
1928− <|> notFilter `taggedWith` "not"
1929− <|> identityFilter `taggedWith` "match_all"
1930− <|> boolFilter `taggedWith` "bool"
1931− <|> existsFilter `taggedWith` "exists"
1932− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
1933− <|> geoDistanceFilter `taggedWith` "geo_distance"
1934− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
1935− <|> geoPolygonFilter `taggedWith` "geo_polygon"
1936− <|> idsFilter `taggedWith` "ids"
1937− <|> limitFilter `taggedWith` "limit"
1938− <|> missingFilter `taggedWith` "missing"
1939− <|> prefixFilter `taggedWith` "prefix"
1940− <|> queryFilter `taggedWith` "query"
1941− <|> fqueryFilter `taggedWith` "fquery"
1942− <|> rangeFilter `taggedWith` "range"
1943− <|> regexpFilter `taggedWith` "regexp"
1944− <|> termFilter `taggedWith` "term"
1945− where taggedWith parser k = parser =<< o .: k
1946− andFilter o = AndFilter <$> o .: "filters"
1947− <*> o .:? "_cache" .!= defaultCache
1948− orFilter o = OrFilter <$> o .: "filters"
1949− <*> o .:? "_cache" .!= defaultCache
1950− notFilter o = NotFilter <$> o .: "filter"
1951− <*> o .: "_cache" .!= defaultCache
1952− identityFilter :: Object -> Parser Filter
1954− | HM.null m = pure IdentityFilter
1955− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
1956− boolFilter = pure . BoolFilter
1957− existsFilter o = ExistsFilter <$> o .: "field"
1958− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1959− geoDistanceFilter o = do
1960− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
1962− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1963− GeoDistanceFilter gp <$> o .: "distance"
1964− <*> o .: "distance_type"
1965− <*> o .: "optimize_bbox"
1966− <*> o .:? "_cache" .!= defaultCache
1967− _ -> fail "Could not find GeoDistanceFilter field name"
1968− geoDistanceRangeFilter o = do
1969− case HM.toList (deleteSeveral ["from", "to"] o) of
1971− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1972− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1973− return (GeoDistanceRangeFilter gp rng)
1974− _ -> fail "Could not find GeoDistanceRangeFilter field name"
1975− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
1976− idsFilter o = IdsFilter <$> o .: "type"
1978− limitFilter o = LimitFilter <$> o .: "value"
1979− missingFilter o = MissingFilter <$> o .: "field"
1980− <*> o .: "existence"
1981− <*> o .: "null_value"
1982− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
1983− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
1984− _ -> fail "Could not parse PrefixFilter"
1986− queryFilter q = pure (QueryFilter q False)
1987− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
1988− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
1989− [(fn, v)] -> RangeFilter (FieldName fn)
1991− <*> o .: "execution"
1992− <*> o .:? "_cache" .!= defaultCache
1993− _ -> fail "Could not find field name for RangeFilter"
1994− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
1995− [(fn, Object o')] -> RegexpFilter (FieldName fn)
1999− <*> o .:? "_cache" .!= defaultCache
2000− <*> o .: "_cache_key"
2001− _ -> fail "Could not find field name for RegexpFilter"
2002− termFilter o = case HM.toList (HM.delete "_cache" o) of
2003− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2004− <$> o .:? "_cache" .!= defaultCache
2005− _ -> fail "Could not find term field for TermFilter"
2007−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2008−fieldTagged f o = case HM.toList o of
2009− [(k, Object o')] -> f (FieldName k) o'
2010− _ -> fail "Expected object with 1 field-named key"
2012−instance ToJSON GeoPoint where
2013− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2014− object [ geoPointField .= geoPointLatLon ]
2017−instance ToJSON Query where
2018− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2020− object [termQueryField .= object merged]]
2022− base = [ "value" .= termQueryValue ]
2023− boosted = maybe [] (return . ("boost" .=)) boost
2024− merged = mappend base boosted
2026− toJSON (TermsQuery fieldName terms) =
2027− object [ "terms" .= object conjoined ]
2028− where conjoined = [fieldName .= terms]
2029− toJSON (IdsQuery idsQueryMappingName docIds) =
2030− object [ "ids" .= object conjoined ]
2031− where conjoined = [ "type" .= idsQueryMappingName
2032− , "values" .= fmap toJSON docIds ]
2034− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2035− object [ "query_string" .= qQueryStringQuery ]
2037− toJSON (QueryMatchQuery matchQuery) =
2038− object [ "match" .= matchQuery ]
2040− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2041− toJSON multiMatchQuery
2043− toJSON (QueryBoolQuery boolQuery) =
2044− object [ "bool" .= boolQuery ]
2046− toJSON (QueryBoostingQuery boostingQuery) =
2047− object [ "boosting" .= boostingQuery ]
2049− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2050− object [ "common" .= commonTermsQuery ]
2052− toJSON (ConstantScoreFilter csFilter boost) =
2053− object ["constant_score" .= object ["filter" .= csFilter
2054− , "boost" .= boost]]
2056− toJSON (ConstantScoreQuery query boost) =
2057− object ["constant_score" .= object ["query" .= query
2058− , "boost" .= boost]]
2060− toJSON (QueryDisMaxQuery disMaxQuery) =
2061− object [ "dis_max" .= disMaxQuery ]
2063− toJSON (QueryFilteredQuery qFilteredQuery) =
2064− object [ "filtered" .= qFilteredQuery ]
2066− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2067− object [ "fuzzy_like_this" .= fuzzyQuery ]
2069− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2070− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2072− toJSON (QueryFuzzyQuery fuzzyQuery) =
2073− object [ "fuzzy" .= fuzzyQuery ]
2075− toJSON (QueryHasChildQuery childQuery) =
2076− object [ "has_child" .= childQuery ]
2078− toJSON (QueryHasParentQuery parentQuery) =
2079− object [ "has_parent" .= parentQuery ]
2081− toJSON (QueryIndicesQuery qIndicesQuery) =
2082− object [ "indices" .= qIndicesQuery ]
2084− toJSON (MatchAllQuery boost) =
2085− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2087− toJSON (QueryMoreLikeThisQuery query) =
2088− object [ "more_like_this" .= query ]
2090− toJSON (QueryMoreLikeThisFieldQuery query) =
2091− object [ "more_like_this_field" .= query ]
2093− toJSON (QueryNestedQuery query) =
2094− object [ "nested" .= query ]
2096− toJSON (QueryPrefixQuery query) =
2097− object [ "prefix" .= query ]
2099− toJSON (QueryRangeQuery query) =
2100− object [ "range" .= query ]
2102− toJSON (QueryRegexpQuery query) =
2103− object [ "regexp" .= query ]
2105− toJSON (QuerySimpleQueryStringQuery query) =
2106− object [ "simple_query_string" .= query ]
2108−instance FromJSON Query where
2109− parseJSON v = withObject "Query" parse v
2110− where parse o = termQuery `taggedWith` "term"
2111− <|> termsQuery `taggedWith` "terms"
2112− <|> idsQuery `taggedWith` "ids"
2113− <|> queryQueryStringQuery `taggedWith` "query_string"
2114− <|> queryMatchQuery `taggedWith` "match"
2115− <|> queryMultiMatchQuery
2116− <|> queryBoolQuery `taggedWith` "bool"
2117− <|> queryBoostingQuery `taggedWith` "boosting"
2118− <|> queryCommonTermsQuery `taggedWith` "common"
2119− <|> constantScoreFilter `taggedWith` "constant_score"
2120− <|> constantScoreQuery `taggedWith` "constant_score"
2121− <|> queryDisMaxQuery `taggedWith` "dis_max"
2122− <|> queryFilteredQuery `taggedWith` "filtered"
2123− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2124− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2125− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2126− <|> queryHasChildQuery `taggedWith` "has_child"
2127− <|> queryHasParentQuery `taggedWith` "has_parent"
2128− <|> queryIndicesQuery `taggedWith` "indices"
2129− <|> matchAllQuery `taggedWith` "match_all"
2130− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2131− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2132− <|> queryNestedQuery `taggedWith` "nested"
2133− <|> queryPrefixQuery `taggedWith` "prefix"
2134− <|> queryRangeQuery `taggedWith` "range"
2135− <|> queryRegexpQuery `taggedWith` "regexp"
2136− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2137− where taggedWith parser k = parser =<< o .: k
2138− termQuery = fieldTagged $ \(FieldName fn) o ->
2139− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2140− termsQuery o = case HM.toList o of
2141− [(fn, vs)] -> do vals <- parseJSON vs
2143− x:xs -> return (TermsQuery fn (x :| xs))
2144− _ -> fail "Expected non empty list of values"
2145− _ -> fail "Expected object with 1 field-named key"
2146− idsQuery o = IdsQuery <$> o .: "type"
2148− queryQueryStringQuery = pure . QueryQueryStringQuery
2149− queryMatchQuery = pure . QueryMatchQuery
2150− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2151− queryBoolQuery = pure . QueryBoolQuery
2152− queryBoostingQuery = pure . QueryBoostingQuery
2153− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2154− constantScoreFilter o = case HM.lookup "filter" o of
2155− Just x -> ConstantScoreFilter <$> parseJSON x
2157− _ -> fail "Does not appear to be a ConstantScoreFilter"
2158− constantScoreQuery o = case HM.lookup "query" o of
2159− Just x -> ConstantScoreQuery <$> parseJSON x
2161− _ -> fail "Does not appear to be a ConstantScoreQuery"
2162− queryDisMaxQuery = pure . QueryDisMaxQuery
2163− queryFilteredQuery = pure . QueryFilteredQuery
2164− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2165− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2166− queryFuzzyQuery = pure . QueryFuzzyQuery
2167− queryHasChildQuery = pure . QueryHasChildQuery
2168− queryHasParentQuery = pure . QueryHasParentQuery
2169− queryIndicesQuery = pure . QueryIndicesQuery
2170− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2171− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2172− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2173− queryNestedQuery = pure . QueryNestedQuery
2174− queryPrefixQuery = pure . QueryPrefixQuery
2175− queryRangeQuery = pure . QueryRangeQuery
2176− queryRegexpQuery = pure . QueryRegexpQuery
2177− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2180−omitNulls :: [(Text, Value)] -> Value
2181−omitNulls = object . filter notNull where
2182− notNull (_, Null) = False
2183− notNull (_, Array a) = (not . V.null) a
2187−instance ToJSON SimpleQueryStringQuery where
2188− toJSON SimpleQueryStringQuery {..} =
2189− omitNulls (base ++ maybeAdd)
2190− where base = [ "query" .= simpleQueryStringQuery ]
2191− maybeAdd = [ "fields" .= simpleQueryStringField
2192− , "default_operator" .= simpleQueryStringOperator
2193− , "analyzer" .= simpleQueryStringAnalyzer
2194− , "flags" .= simpleQueryStringFlags
2195− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2196− , "locale" .= simpleQueryStringLocale ]
2198−instance FromJSON SimpleQueryStringQuery where
2199− parseJSON = withObject "SimpleQueryStringQuery" parse
2200− where parse o = SimpleQueryStringQuery <$> o .: "query"
2202− <*> o .:? "default_operator"
2203− <*> o .:? "analyzer"
2204− <*> (parseFlags <$> o .:? "flags")
2205− <*> o .:? "lowercase_expanded_terms"
2207− parseFlags (Just (x:xs)) = Just (x :| xs)
2208− parseFlags _ = Nothing
2210−instance ToJSON FieldOrFields where
2211− toJSON (FofField fieldName) =
2213− toJSON (FofFields fieldNames) =
2216−instance FromJSON FieldOrFields where
2217− parseJSON v = FofField <$> parseJSON v
2218− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2220−instance ToJSON SimpleQueryFlag where
2221− toJSON SimpleQueryAll = "ALL"
2222− toJSON SimpleQueryNone = "NONE"
2223− toJSON SimpleQueryAnd = "AND"
2224− toJSON SimpleQueryOr = "OR"
2225− toJSON SimpleQueryPrefix = "PREFIX"
2226− toJSON SimpleQueryPhrase = "PHRASE"
2227− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2228− toJSON SimpleQueryEscape = "ESCAPE"
2229− toJSON SimpleQueryWhitespace = "WHITESPACE"
2230− toJSON SimpleQueryFuzzy = "FUZZY"
2231− toJSON SimpleQueryNear = "NEAR"
2232− toJSON SimpleQuerySlop = "SLOP"
2234−instance FromJSON SimpleQueryFlag where
2235− parseJSON = withText "SimpleQueryFlag" parse
2236− where parse "ALL" = pure SimpleQueryAll
2237− parse "NONE" = pure SimpleQueryNone
2238− parse "AND" = pure SimpleQueryAnd
2239− parse "OR" = pure SimpleQueryOr
2240− parse "PREFIX" = pure SimpleQueryPrefix
2241− parse "PHRASE" = pure SimpleQueryPhrase
2242− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2243− parse "ESCAPE" = pure SimpleQueryEscape
2244− parse "WHITESPACE" = pure SimpleQueryWhitespace
2245− parse "FUZZY" = pure SimpleQueryFuzzy
2246− parse "NEAR" = pure SimpleQueryNear
2247− parse "SLOP" = pure SimpleQuerySlop
2248− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2250−instance ToJSON RegexpQuery where
2251− toJSON (RegexpQuery (FieldName rqQueryField)
2252− (Regexp regexpQueryQuery) rqQueryFlags
2254− object [ rqQueryField .= omitNulls base ]
2255− where base = [ "value" .= regexpQueryQuery
2256− , "flags" .= rqQueryFlags
2257− , "boost" .= rqQueryBoost ]
2259−instance FromJSON RegexpQuery where
2260− parseJSON = withObject "RegexpQuery" parse
2261− where parse = fieldTagged $ \fn o ->
2267−instance ToJSON QueryStringQuery where
2268− toJSON (QueryStringQuery qsQueryString
2269− qsDefaultField qsOperator
2270− qsAnalyzer qsAllowWildcard
2271− qsLowercaseExpanded qsEnablePositionIncrements
2272− qsFuzzyMaxExpansions qsFuzziness
2273− qsFuzzyPrefixLength qsPhraseSlop
2274− qsBoost qsAnalyzeWildcard
2275− qsGeneratePhraseQueries qsMinimumShouldMatch
2276− qsLenient qsLocale) =
2279− base = [ "query" .= qsQueryString
2280− , "default_field" .= qsDefaultField
2281− , "default_operator" .= qsOperator
2282− , "analyzer" .= qsAnalyzer
2283− , "allow_leading_wildcard" .= qsAllowWildcard
2284− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2285− , "enable_position_increments" .= qsEnablePositionIncrements
2286− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2287− , "fuzziness" .= qsFuzziness
2288− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2289− , "phrase_slop" .= qsPhraseSlop
2290− , "boost" .= qsBoost
2291− , "analyze_wildcard" .= qsAnalyzeWildcard
2292− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2293− , "minimum_should_match" .= qsMinimumShouldMatch
2294− , "lenient" .= qsLenient
2295− , "locale" .= qsLocale ]
2297−instance FromJSON QueryStringQuery where
2298− parseJSON = withObject "QueryStringQuery" parse
2299− where parse o = QueryStringQuery
2301− <*> o .:? "default_field"
2302− <*> o .:? "default_operator"
2303− <*> o .:? "analyzer"
2304− <*> o .:? "allow_leading_wildcard"
2305− <*> o .:? "lowercase_expanded_terms"
2306− <*> o .:? "enable_position_increments"
2307− <*> o .:? "fuzzy_max_expansions"
2308− <*> o .:? "fuzziness"
2309− <*> o .:? "fuzzy_prefix_length"
2310− <*> o .:? "phrase_slop"
2312− <*> o .:? "analyze_wildcard"
2313− <*> o .:? "auto_generate_phrase_queries"
2314− <*> o .:? "minimum_should_match"
2315− <*> o .:? "lenient"
2318−instance ToJSON RangeQuery where
2319− toJSON (RangeQuery (FieldName fieldName) range boost) =
2320− object [ fieldName .= object conjoined ]
2321− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2323−instance FromJSON RangeQuery where
2324− parseJSON = withObject "RangeQuery" parse
2325− where parse = fieldTagged $ \fn o ->
2327− <$> parseJSON (Object o)
2330−instance FromJSON RangeValue where
2331− parseJSON = withObject "RangeValue" parse
2332− where parse o = parseDate o
2334− parseDate o = do lt <- o .:? "lt"
2338− case (lt, lte, gt, gte) of
2339− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2340− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2341− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2342− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2343− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2344− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2345− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2346− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2347− (Nothing, Nothing, Nothing, Nothing) -> mzero
2348− parseDouble o = do lt <- o .:? "lt"
2352− case (lt, lte, gt, gte) of
2353− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2354− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2355− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2356− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2357− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2358− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2359− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2360− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2361− (Nothing, Nothing, Nothing, Nothing) -> mzero
2363−instance ToJSON PrefixQuery where
2364− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2365− object [ fieldName .= omitNulls base ]
2366− where base = [ "value" .= queryValue
2367− , "boost" .= boost ]
2369−instance FromJSON PrefixQuery where
2370− parseJSON = withObject "PrefixQuery" parse
2371− where parse = fieldTagged $ \fn o ->
2376−instance ToJSON NestedQuery where
2377− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2378− object [ "path" .= nqPath
2379− , "score_mode" .= nqScoreType
2380− , "query" .= nqQuery ]
2382−instance FromJSON NestedQuery where
2383− parseJSON = withObject "NestedQuery" parse
2384− where parse o = NestedQuery
2386− <*> o .: "score_mode"
2389−instance ToJSON MoreLikeThisFieldQuery where
2390− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2391− percent mtf mqt stopwords mindf maxdf
2392− minwl maxwl boostTerms boost analyzer) =
2393− object [ fieldName .= omitNulls base ]
2394− where base = [ "like_text" .= text
2395− , "percent_terms_to_match" .= percent
2396− , "min_term_freq" .= mtf
2397− , "max_query_terms" .= mqt
2398− , "stop_words" .= stopwords
2399− , "min_doc_freq" .= mindf
2400− , "max_doc_freq" .= maxdf
2401− , "min_word_length" .= minwl
2402− , "max_word_length" .= maxwl
2403− , "boost_terms" .= boostTerms
2405− , "analyzer" .= analyzer ]
2407−instance FromJSON MoreLikeThisFieldQuery where
2408− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2409− where parse = fieldTagged $ \fn o ->
2410− MoreLikeThisFieldQuery
2411− <$> o .: "like_text"
2413− <*> o .:? "percent_terms_to_match"
2414− <*> o .:? "min_term_freq"
2415− <*> o .:? "max_query_terms"
2416− <*> (optionalNE =<< o .:? "stop_words")
2417− <*> o .:? "min_doc_freq"
2418− <*> o .:? "max_doc_freq"
2419− <*> o .:? "min_word_length"
2420− <*> o .:? "max_word_length"
2421− <*> o .:? "boost_terms"
2423− <*> o .:? "analyzer"
2424− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2426−instance ToJSON MoreLikeThisQuery where
2427− toJSON (MoreLikeThisQuery text fields percent
2428− mtf mqt stopwords mindf maxdf
2429− minwl maxwl boostTerms boost analyzer) =
2431− where base = [ "like_text" .= text
2432− , "fields" .= fields
2433− , "percent_terms_to_match" .= percent
2434− , "min_term_freq" .= mtf
2435− , "max_query_terms" .= mqt
2436− , "stop_words" .= stopwords
2437− , "min_doc_freq" .= mindf
2438− , "max_doc_freq" .= maxdf
2439− , "min_word_length" .= minwl
2440− , "max_word_length" .= maxwl
2441− , "boost_terms" .= boostTerms
2443− , "analyzer" .= analyzer ]
2445−instance FromJSON MoreLikeThisQuery where
2446− parseJSON = withObject "MoreLikeThisQuery" parse
2447− where parse o = MoreLikeThisQuery
2448− <$> o .: "like_text"
2449− <*> (optionalNE =<< o .:? "fields")
2450− <*> o .:? "percent_terms_to_match"
2451− <*> o .:? "min_term_freq"
2452− <*> o .:? "max_query_terms"
2453− <*> (optionalNE =<< o .:? "stop_words")
2454− <*> o .:? "min_doc_freq"
2455− <*> o .:? "max_doc_freq"
2456− <*> o .:? "min_word_length"
2457− <*> o .:? "max_word_length"
2458− <*> o .:? "boost_terms"
2460− <*> o .:? "analyzer"
2461− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2463−instance ToJSON IndicesQuery where
2464− toJSON (IndicesQuery indices query noMatch) =
2465− omitNulls [ "indices" .= indices
2466− , "no_match_query" .= noMatch
2467− , "query" .= query ]
2469−instance FromJSON IndicesQuery where
2470− parseJSON = withObject "IndicesQuery" parse
2471− where parse o = IndicesQuery
2472− <$> o .:? "indices" .!= []
2474− <*> o .:? "no_match_query"
2476−instance ToJSON HasParentQuery where
2477− toJSON (HasParentQuery queryType query scoreType) =
2478− omitNulls [ "parent_type" .= queryType
2479− , "score_type" .= scoreType
2480− , "query" .= query ]
2482−instance FromJSON HasParentQuery where
2483− parseJSON = withObject "HasParentQuery" parse
2484− where parse o = HasParentQuery
2485− <$> o .: "parent_type"
2487− <*> o .:? "score_type"
2489−instance ToJSON HasChildQuery where
2490− toJSON (HasChildQuery queryType query scoreType) =
2491− omitNulls [ "query" .= query
2492− , "score_type" .= scoreType
2493− , "type" .= queryType ]
2495−instance FromJSON HasChildQuery where
2496− parseJSON = withObject "HasChildQuery" parse
2497− where parse o = HasChildQuery
2500− <*> o .:? "score_type"
2502−instance ToJSON FuzzyQuery where
2503− toJSON (FuzzyQuery (FieldName fieldName) queryText
2504− prefixLength maxEx fuzziness boost) =
2505− object [ fieldName .= omitNulls base ]
2506− where base = [ "value" .= queryText
2507− , "fuzziness" .= fuzziness
2508− , "prefix_length" .= prefixLength
2510− , "max_expansions" .= maxEx ]
2512−instance FromJSON FuzzyQuery where
2513− parseJSON = withObject "FuzzyQuery" parse
2514− where parse = fieldTagged $ \fn o ->
2517− <*> o .: "prefix_length"
2518− <*> o .: "max_expansions"
2519− <*> o .: "fuzziness"
2522−instance ToJSON FuzzyLikeFieldQuery where
2523− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2524− fieldText maxTerms ignoreFreq fuzziness prefixLength
2526− object [ fieldName .=
2527− omitNulls [ "like_text" .= fieldText
2528− , "max_query_terms" .= maxTerms
2529− , "ignore_tf" .= ignoreFreq
2530− , "fuzziness" .= fuzziness
2531− , "prefix_length" .= prefixLength
2532− , "analyzer" .= analyzer
2533− , "boost" .= boost ]]
2535−instance FromJSON FuzzyLikeFieldQuery where
2536− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2537− where parse = fieldTagged $ \fn o ->
2538− FuzzyLikeFieldQuery fn
2539− <$> o .: "like_text"
2540− <*> o .: "max_query_terms"
2541− <*> o .: "ignore_tf"
2542− <*> o .: "fuzziness"
2543− <*> o .: "prefix_length"
2545− <*> o .:? "analyzer"
2547−instance ToJSON FuzzyLikeThisQuery where
2548− toJSON (FuzzyLikeThisQuery fields text maxTerms
2549− ignoreFreq fuzziness prefixLength boost analyzer) =
2551− where base = [ "fields" .= fields
2552− , "like_text" .= text
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 FuzzyLikeThisQuery where
2561− parseJSON = withObject "FuzzyLikeThisQuery" parse
2562− where parse o = FuzzyLikeThisQuery
2563− <$> o .:? "fields" .!= []
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 FilteredQuery where
2573− toJSON (FilteredQuery query fFilter) =
2574− object [ "query" .= query
2575− , "filter" .= fFilter ]
2577−instance FromJSON FilteredQuery where
2578− parseJSON = withObject "FilteredQuery" parse
2579− where parse o = FilteredQuery
2583−instance ToJSON DisMaxQuery where
2584− toJSON (DisMaxQuery queries tiebreaker boost) =
2586− where base = [ "queries" .= queries
2588− , "tie_breaker" .= tiebreaker ]
2590−instance FromJSON DisMaxQuery where
2591− parseJSON = withObject "DisMaxQuery" parse
2592− where parse o = DisMaxQuery
2593− <$> o .:? "queries" .!= []
2594− <*> o .: "tie_breaker"
2597−instance ToJSON CommonTermsQuery where
2598− toJSON (CommonTermsQuery (FieldName fieldName)
2599− (QueryString query) cf lfo hfo msm
2600− boost analyzer disableCoord) =
2601− object [fieldName .= omitNulls base ]
2602− where base = [ "query" .= query
2603− , "cutoff_frequency" .= cf
2604− , "low_freq_operator" .= lfo
2605− , "minimum_should_match" .= msm
2607− , "analyzer" .= analyzer
2608− , "disable_coord" .= disableCoord
2609− , "high_freq_operator" .= hfo ]
2611−instance FromJSON CommonTermsQuery where
2612− parseJSON = withObject "CommonTermsQuery" parse
2613− where parse = fieldTagged $ \fn o ->
2614− CommonTermsQuery fn
2616− <*> o .: "cutoff_frequency"
2617− <*> o .: "low_freq_operator"
2618− <*> o .: "high_freq_operator"
2619− <*> o .:? "minimum_should_match"
2621− <*> o .:? "analyzer"
2622− <*> o .:? "disable_coord"
2624−instance ToJSON CommonMinimumMatch where
2625− toJSON (CommonMinimumMatch mm) = toJSON mm
2626− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2627− object [ "low_freq" .= lowF
2628− , "high_freq" .= highF ]
2630−instance FromJSON CommonMinimumMatch where
2631− parseJSON v = parseMinimum v
2632− <|> parseMinimumHighLow v
2633− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2634− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2635− MinimumMatchHighLow
2636− <$> o .: "low_freq"
2637− <*> o .: "high_freq")
2640−instance ToJSON BoostingQuery where
2641− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2642− object [ "positive" .= bqPositiveQuery
2643− , "negative" .= bqNegativeQuery
2644− , "negative_boost" .= bqNegativeBoost ]
2646−instance FromJSON BoostingQuery where
2647− parseJSON = withObject "BoostingQuery" parse
2648− where parse o = BoostingQuery
2649− <$> o .: "positive"
2650− <*> o .: "negative"
2651− <*> o .: "negative_boost"
2653−instance ToJSON BoolQuery where
2654− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2656− where base = [ "must" .= mustM
2657− , "must_not" .= notM
2658− , "should" .= shouldM
2659− , "minimum_should_match" .= bqMin
2661− , "disable_coord" .= disableCoord ]
2663−instance FromJSON BoolQuery where
2664− parseJSON = withObject "BoolQuery" parse
2665− where parse o = BoolQuery
2666− <$> o .:? "must" .!= []
2667− <*> o .:? "must_not" .!= []
2668− <*> o .:? "should" .!= []
2669− <*> o .:? "minimum_should_match"
2671− <*> o .:? "disable_coord"
2673−instance ToJSON MatchQuery where
2674− toJSON (MatchQuery (FieldName fieldName)
2675− (QueryString mqQueryString) booleanOperator
2676− zeroTermsQuery cutoffFrequency matchQueryType
2677− analyzer maxExpansions lenient boost) =
2678− object [ fieldName .= omitNulls base ]
2679− where base = [ "query" .= mqQueryString
2680− , "operator" .= booleanOperator
2681− , "zero_terms_query" .= zeroTermsQuery
2682− , "cutoff_frequency" .= cutoffFrequency
2683− , "type" .= matchQueryType
2684− , "analyzer" .= analyzer
2685− , "max_expansions" .= maxExpansions
2686− , "lenient" .= lenient
2687− , "boost" .= boost ]
2689−instance FromJSON MatchQuery where
2690− parseJSON = withObject "MatchQuery" parse
2691− where parse = fieldTagged $ \fn o ->
2694− <*> o .: "operator"
2695− <*> o .: "zero_terms_query"
2696− <*> o .:? "cutoff_frequency"
2698− <*> o .:? "analyzer"
2699− <*> o .:? "max_expansions"
2700− <*> o .:? "lenient"
2703−instance ToJSON MultiMatchQuery where
2704− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2705− ztQ tb mmqt cf analyzer maxEx lenient) =
2706− object ["multi_match" .= omitNulls base]
2707− where base = [ "fields" .= fmap toJSON fields
2709− , "operator" .= boolOp
2710− , "zero_terms_query" .= ztQ
2711− , "tiebreaker" .= tb
2713− , "cutoff_frequency" .= cf
2714− , "analyzer" .= analyzer
2715− , "max_expansions" .= maxEx
2716− , "lenient" .= lenient ]
2718−instance FromJSON MultiMatchQuery where
2719− parseJSON = withObject "MultiMatchQuery" parse
2720− where parse raw = do o <- raw .: "multi_match"
2722− <$> o .:? "fields" .!= []
2724− <*> o .: "operator"
2725− <*> o .: "zero_terms_query"
2726− <*> o .:? "tiebreaker"
2728− <*> o .:? "cutoff_frequency"
2729− <*> o .:? "analyzer"
2730− <*> o .:? "max_expansions"
2731− <*> o .:? "lenient"
2733−instance ToJSON MultiMatchQueryType where
2734− toJSON MultiMatchBestFields = "best_fields"
2735− toJSON MultiMatchMostFields = "most_fields"
2736− toJSON MultiMatchCrossFields = "cross_fields"
2737− toJSON MultiMatchPhrase = "phrase"
2738− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2740−instance FromJSON MultiMatchQueryType where
2741− parseJSON = withText "MultiMatchPhrasePrefix" parse
2742− where parse "best_fields" = pure MultiMatchBestFields
2743− parse "most_fields" = pure MultiMatchMostFields
2744− parse "cross_fields" = pure MultiMatchCrossFields
2745− parse "phrase" = pure MultiMatchPhrase
2746− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2747− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2749−instance ToJSON BooleanOperator where
2750− toJSON And = String "and"
2751− toJSON Or = String "or"
2753−instance FromJSON BooleanOperator where
2754− parseJSON = withText "BooleanOperator" parse
2755− where parse "and" = pure And
2756− parse "or" = pure Or
2757− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2759−instance ToJSON ZeroTermsQuery where
2760− toJSON ZeroTermsNone = String "none"
2761− toJSON ZeroTermsAll = String "all"
2763−instance FromJSON ZeroTermsQuery where
2764− parseJSON = withText "ZeroTermsQuery" parse
2765− where parse "none" = pure ZeroTermsNone
2766− parse "all" = pure ZeroTermsAll
2767− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2769−instance ToJSON MatchQueryType where
2770− toJSON MatchPhrase = "phrase"
2771− toJSON MatchPhrasePrefix = "phrase_prefix"
2773−instance FromJSON MatchQueryType where
2774− parseJSON = withText "MatchQueryType" parse
2775− where parse "phrase" = pure MatchPhrase
2776− parse "phrase_prefix" = pure MatchPhrasePrefix
2777− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2779−instance FromJSON Status where
2780− parseJSON (Object v) = Status <$>
2786− parseJSON _ = empty
2789−instance ToJSON IndexSettings where
2790− toJSON (IndexSettings s r) = object ["settings" .=
2792− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2796−instance FromJSON IndexSettings where
2797− parseJSON = withObject "IndexSettings" parse
2798− where parse o = do s <- o .: "settings"
2800− IndexSettings <$> i .: "number_of_shards"
2801− <*> i .: "number_of_replicas"
2803−instance ToJSON UpdatableIndexSetting where
2804− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2805− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2806− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2807− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2808− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2809− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2810− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2811− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2812− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2813− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2814− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2815− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2816− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2817− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2818− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2819− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2820− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2821− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2822− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2823− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2824− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2825− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2826− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2827− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2828− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2829− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2830− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2831− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2833−instance FromJSON UpdatableIndexSetting where
2834− parseJSON = withObject "UpdatableIndexSetting" parse
2835− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2836− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2837− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2838− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2839− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2840− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2841− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2842− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2843− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2844− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2845− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2846− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2847− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2848− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2849− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2850− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2851− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2852− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2853− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2854− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2855− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2856− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2857− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2858− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2859− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2860− <|> blocksRead `taggedAt` ["blocks", "read"]
2861− <|> blocksWrite `taggedAt` ["blocks", "write"]
2862− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2863− where taggedAt f ks = taggedAt' f (Object o) ks
2864− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON =<< unStringlyTypeJSON v))
2865− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
2866− taggedAt' f v' ks) v
2867− numberOfReplicas = pure . NumberOfReplicas
2868− autoExpandReplicas = pure . AutoExpandReplicas
2869− refreshInterval = pure . RefreshInterval . ndtJSON
2870− indexConcurrency = pure . IndexConcurrency
2871− failOnMergeFailure = pure . FailOnMergeFailure
2872− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
2873− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
2874− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
2875− translogDisableFlush = pure . TranslogDisableFlush
2876− cacheFilterMaxSize = pure . CacheFilterMaxSize
2877− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
2878− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
2879− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
2880− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
2881− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
2882− routingAllocationEnable = pure . RoutingAllocationEnable
2883− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
2884− recoveryInitialShards = pure . RecoveryInitialShards
2885− gcDeletes = pure . GCDeletes . ndtJSON
2886− ttlDisablePurge = pure . TTLDisablePurge
2887− translogFSType = pure . TranslogFSType
2888− compoundFormat = pure . IndexCompoundFormat
2889− compoundOnFlush = pure . IndexCompoundOnFlush
2890− warmerEnabled = pure . WarmerEnabled
2891− blocksReadOnly = pure . BlocksReadOnly
2892− blocksRead = pure . BlocksRead
2893− blocksWrite = pure . BlocksWrite
2894− blocksMetaData = pure . BlocksMetaData
2896−instance FromJSON IndexSettingsSummary where
2897− parseJSON = withObject "IndexSettingsSummary" parse
2898− where parse o = case HM.toList o of
2899− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
2901− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
2902− _ -> fail "Expected single-key object with index name"
2903− redundant (NumberOfReplicas _) = True
2904− redundant _ = False
2906−-- | For some reason in the settings API, all leaf values get returned
2907−-- as strings. This function attepmts to recover from this for all
2908−-- non-recursive JSON types. If nothing can be done or the same value
2909−-- would be return, it returns 'mzero'
2910−unStringlyTypeJSON :: MonadPlus m => Value -> m Value
2911−unStringlyTypeJSON (String "true") = return (Bool True)
2912−unStringlyTypeJSON (String "false") = return (Bool False)
2913−unStringlyTypeJSON (String "null") = return Null
2914−unStringlyTypeJSON (String t) = case readMay (T.unpack t) of
2915− Just n -> return (Number n)
2917−unStringlyTypeJSON _ = mzero
2920−parseSettings :: Object -> Parser [UpdatableIndexSetting]
2921−parseSettings o = do
2923− -- slice the index object into singleton hashmaps and try to parse each
2924− parses <- forM (HM.toList o') $ \(k, v) -> do
2925− -- blocks are now nested into the "index" key, which is not how they're serialized
2926− let atRoot = Object (HM.singleton k v)
2927− let atIndex = Object (HM.singleton "index" atRoot)
2928− optional (parseJSON atRoot <|> parseJSON atIndex)
2929− return (catMaybes parses)
2931−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2932−oPath (k :| []) v = object [k .= v]
2933−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2935−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2936−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2937− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2939−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
2940−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
2941− where parse o = case HM.toList o of
2942− [] -> fail "Expected non-empty list of NodeAttrFilters"
2943− x:xs -> DT.mapM (uncurry parse') (x :| xs)
2944− parse' n = withText "Text" $ \t ->
2945− case T.splitOn "," t of
2946− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
2947− [] -> fail "Expected non-empty list of filter values"
2949−instance ToJSON ReplicaBounds where
2950− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2951− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2952− toJSON ReplicasUnbounded = Bool False
2954−instance FromJSON ReplicaBounds where
2955− parseJSON v = withText "ReplicaBounds" parseText v
2956− <|> withBool "ReplicaBounds" parseBool v
2957− where parseText t = case T.splitOn "-" t of
2958− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
2959− [a, b] -> ReplicasBounded <$> parseReadText a
2960− <*> parseReadText b
2961− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
2962− parseBool False = pure ReplicasUnbounded
2963− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
2965−instance ToJSON AllocationPolicy where
2966− toJSON AllocAll = String "all"
2967− toJSON AllocPrimaries = String "primaries"
2968− toJSON AllocNewPrimaries = String "new_primaries"
2969− toJSON AllocNone = String "none"
2971−instance FromJSON AllocationPolicy where
2972− parseJSON = withText "AllocationPolicy" parse
2973− where parse "all" = pure AllocAll
2974− parse "primaries" = pure AllocPrimaries
2975− parse "new_primaries" = pure AllocNewPrimaries
2976− parse "none" = pure AllocNone
2977− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
2979−instance ToJSON InitialShardCount where
2980− toJSON QuorumShards = String "quorum"
2981− toJSON QuorumMinus1Shards = String "quorum-1"
2982− toJSON FullShards = String "full"
2983− toJSON FullMinus1Shards = String "full-1"
2984− toJSON (ExplicitShards x) = toJSON x
2986−instance FromJSON InitialShardCount where
2987− parseJSON v = withText "InitialShardCount" parseText v
2988− <|> ExplicitShards <$> parseJSON v
2989− where parseText "quorum" = pure QuorumShards
2990− parseText "quorum-1" = pure QuorumMinus1Shards
2991− parseText "full" = pure FullShards
2992− parseText "full-1" = pure FullMinus1Shards
2993− parseText _ = mzero
2995−instance ToJSON FSType where
2996− toJSON FSSimple = "simple"
2997− toJSON FSBuffered = "buffered"
2999−instance FromJSON FSType where
3000− parseJSON = withText "FSType" parse
3001− where parse "simple" = pure FSSimple
3002− parse "buffered" = pure FSBuffered
3003− parse t = fail ("Invalid FSType: " <> show t)
3005−instance ToJSON CompoundFormat where
3006− toJSON (CompoundFileFormat x) = Bool x
3007− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3009−instance FromJSON CompoundFormat where
3010− parseJSON v = CompoundFileFormat <$> parseJSON v
3011− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3013−instance ToJSON NominalDiffTimeJSON where
3014− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3016−instance FromJSON NominalDiffTimeJSON where
3017− parseJSON = withText "NominalDiffTime" parse
3018− where parse t = case T.takeEnd 1 t of
3019− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3020− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3022−instance ToJSON IndexTemplate where
3023− toJSON (IndexTemplate p s m) = merge
3024− (object [ "template" .= p
3025− , "mappings" .= foldl' merge (object []) m
3029− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3031− merge _ _ = undefined
3033−instance (FromJSON a) => FromJSON (EsResult a) where
3034− parseJSON jsonVal@(Object v) = do
3035− found <- v .:? "found" .!= False
3037− then parseJSON jsonVal
3038− else return Nothing
3039− EsResult <$> v .: "_index" <*>
3043− parseJSON _ = empty
3045−instance (FromJSON a) => FromJSON (EsResultFound a) where
3046− parseJSON (Object v) = EsResultFound <$>
3047− v .: "_version" <*>
3049− parseJSON _ = empty
3051−instance FromJSON EsError where
3052− parseJSON (Object v) = EsError <$>
3055− parseJSON _ = empty
3057−instance FromJSON IndexAliasesSummary where
3058− parseJSON = withObject "IndexAliasesSummary" parse
3059− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3060− go ixn = withObject "index aliases" $ \ia -> do
3061− aliases <- ia .: "aliases"
3062− forM (HM.toList aliases) $ \(aName, v) -> do
3063− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3064− IndexAliasSummary indexAlias <$> parseJSON v
3067−instance ToJSON IndexAliasAction where
3068− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3069− where Object iaObj = toJSON ia
3070− Object optsObj = toJSON opts
3071− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3072− where Object iaObj = toJSON ia
3074−instance ToJSON IndexAlias where
3075− toJSON IndexAlias {..} = object ["index" .= srcIndex
3076− , "alias" .= indexAlias
3079−instance ToJSON IndexAliasCreate where
3080− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3081− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3082− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3084−instance ToJSON AliasRouting where
3085− toJSON (AllAliasRouting v) = object ["routing" .= v]
3086− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3087− where prs = [("search_routing" .=) <$> srch
3088− ,("index_routing" .=) <$> idx]
3090−instance FromJSON AliasRouting where
3091− parseJSON = withObject "AliasRouting" parse
3092− where parse o = parseAll o <|> parseGranular o
3093− parseAll o = AllAliasRouting <$> o .: "routing"
3094− parseGranular o = do
3095− sr <- o .:? "search_routing"
3096− ir <- o .:? "index_routing"
3097− if isNothing sr && isNothing ir
3098− then fail "Both search_routing and index_routing can't be blank"
3099− else return (GranularAliasRouting sr ir)
3101−instance FromJSON IndexAliasCreate where
3102− parseJSON v = withObject "IndexAliasCreate" parse v
3103− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3106−instance ToJSON SearchAliasRouting where
3107− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3109−instance FromJSON SearchAliasRouting where
3110− parseJSON = withText "SearchAliasRouting" parse
3111− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3113−instance ToJSON Search where
3114− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3115− omitNulls [ "query" .= query
3116− , "filter" .= sFilter
3118− , "aggregations" .= searchAggs
3119− , "highlight" .= highlight
3122− , "track_scores" .= sTrackSortScores
3123− , "fields" .= sFields
3124− , "_source" .= sSource]
3127−instance ToJSON Source where
3128− toJSON NoSource = toJSON False
3129− toJSON (SourcePatterns patterns) = toJSON patterns
3130− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3132−instance ToJSON PatternOrPatterns where
3133− toJSON (PopPattern pattern) = toJSON pattern
3134− toJSON (PopPatterns patterns) = toJSON patterns
3136−instance ToJSON Include where
3137− toJSON (Include patterns) = toJSON patterns
3139−instance ToJSON Exclude where
3140− toJSON (Exclude patterns) = toJSON patterns
3142−instance ToJSON Pattern where
3143− toJSON (Pattern pattern) = toJSON pattern
3146−instance ToJSON FieldHighlight where
3147− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3148− object [ fName .= fSettings ]
3149− toJSON (FieldHighlight (FieldName fName) Nothing) =
3150− object [ fName .= emptyObject ]
3152−instance ToJSON Highlights where
3153− toJSON (Highlights global fields) =
3154− omitNulls (("fields" .= fields)
3155− : highlightSettingsPairs global)
3157−instance ToJSON HighlightSettings where
3158− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3160−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3161−highlightSettingsPairs Nothing = []
3162−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3163−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3164−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3167−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3168−plainHighPairs Nothing = []
3169−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3170− [ "type" .= String "plain"]
3171− ++ commonHighlightPairs plCom
3172− ++ nonPostingsToPairs plNonPost
3174−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3175−postHighPairs Nothing = []
3176−postHighPairs (Just (PostingsHighlight pCom)) =
3177− ("type" .= String "postings")
3178− : commonHighlightPairs pCom
3180−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3181−fastVectorHighPairs Nothing = []
3182−fastVectorHighPairs (Just
3183− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3184− fvBoundMaxScan fvFragOff fvMatchedFields
3186− [ "type" .= String "fvh"
3187− , "boundary_chars" .= fvBoundChars
3188− , "boundary_max_scan" .= fvBoundMaxScan
3189− , "fragment_offset" .= fvFragOff
3190− , "matched_fields" .= fvMatchedFields
3191− , "phraseLimit" .= fvPhraseLim]
3192− ++ commonHighlightPairs fvCom
3193− ++ nonPostingsToPairs fvNonPostSettings
3195−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3196−deleteSeveral ks hm = foldr HM.delete hm ks
3198−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3199−commonHighlightPairs Nothing = []
3200−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3201− chNoMatchSize chHighlightQuery
3202− chRequireFieldMatch)) =
3203− [ "order" .= chScore
3204− , "force_source" .= chForceSource
3205− , "encoder" .= chEncoder
3206− , "no_match_size" .= chNoMatchSize
3207− , "highlight_query" .= chHighlightQuery
3208− , "require_fieldMatch" .= chRequireFieldMatch]
3209− ++ highlightTagToPairs chTag
3212−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3213−nonPostingsToPairs Nothing = []
3214−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3215− [ "fragment_size" .= npFragSize
3216− , "number_of_fragments" .= npNumOfFrags]
3218−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3219−parseNEJSON [] = fail "Expected non-empty list"
3220−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3223−instance ToJSON HighlightEncoder where
3224− toJSON DefaultEncoder = String "default"
3225− toJSON HTMLEncoder = String "html"
3227−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3228−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3229−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3230− , "post_tags" .= post]
3231−highlightTagToPairs Nothing = []
3233−instance ToJSON SortSpec where
3234− toJSON (DefaultSortSpec
3235− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3236− dsSortMode dsMissingSort dsNestedFilter)) =
3237− object [dsSortFieldName .= omitNulls base] where
3238− base = [ "order" .= dsSortOrder
3239− , "ignore_unmapped" .= dsIgnoreUnmapped
3240− , "mode" .= dsSortMode
3241− , "missing" .= dsMissingSort
3242− , "nested_filter" .= dsNestedFilter ]
3244− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3245− object [ "unit" .= units
3246− , field .= gdsLatLon
3247− , "order" .= gdsSortOrder ]
3250−instance ToJSON SortOrder where
3251− toJSON Ascending = String "asc"
3252− toJSON Descending = String "desc"
3255−instance ToJSON SortMode where
3256− toJSON SortMin = String "min"
3257− toJSON SortMax = String "max"
3258− toJSON SortSum = String "sum"
3259− toJSON SortAvg = String "avg"
3262−instance ToJSON Missing where
3263− toJSON LastMissing = String "_last"
3264− toJSON FirstMissing = String "_first"
3265− toJSON (CustomMissing txt) = String txt
3268−instance ToJSON ScoreType where
3269− toJSON ScoreTypeMax = "max"
3270− toJSON ScoreTypeAvg = "avg"
3271− toJSON ScoreTypeSum = "sum"
3272− toJSON ScoreTypeNone = "none"
3274−instance FromJSON ScoreType where
3275− parseJSON = withText "ScoreType" parse
3276− where parse "max" = pure ScoreTypeMax
3277− parse "avg" = pure ScoreTypeAvg
3278− parse "sum" = pure ScoreTypeSum
3279− parse "none" = pure ScoreTypeNone
3280− parse t = fail ("Unexpected ScoreType: " <> show t)
3282−instance ToJSON Distance where
3283− toJSON (Distance dCoefficient dUnit) =
3284− String boltedTogether where
3285− coefText = showText dCoefficient
3286− (String unitText) = toJSON dUnit
3287− boltedTogether = mappend coefText unitText
3289−instance FromJSON Distance where
3290− parseJSON = withText "Distance" parse
3291− where parse t = Distance <$> parseCoeff nT
3292− <*> parseJSON (String unitT)
3293− where (nT, unitT) = T.span validForNumber t
3294− -- may be a better way to do this
3295− validForNumber '-' = True
3296− validForNumber '.' = True
3297− validForNumber 'e' = True
3298− validForNumber c = isNumber c
3299− parseCoeff "" = fail "Empty string cannot be parsed as number"
3300− parseCoeff s = return (read (T.unpack s))
3302−instance ToJSON DistanceUnit where
3303− toJSON Miles = String "mi"
3304− toJSON Yards = String "yd"
3305− toJSON Feet = String "ft"
3306− toJSON Inches = String "in"
3307− toJSON Kilometers = String "km"
3308− toJSON Meters = String "m"
3309− toJSON Centimeters = String "cm"
3310− toJSON Millimeters = String "mm"
3311− toJSON NauticalMiles = String "nmi"
3314−instance FromJSON DistanceUnit where
3315− parseJSON = withText "DistanceUnit" parse
3316− where parse "mi" = pure Miles
3317− parse "yd" = pure Yards
3318− parse "ft" = pure Feet
3319− parse "in" = pure Inches
3320− parse "km" = pure Kilometers
3321− parse "m" = pure Meters
3322− parse "cm" = pure Centimeters
3323− parse "mm" = pure Millimeters
3324− parse "nmi" = pure NauticalMiles
3325− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3327−instance ToJSON DistanceType where
3328− toJSON Arc = String "arc"
3329− toJSON SloppyArc = String "sloppy_arc"
3330− toJSON Plane = String "plane"
3332−instance FromJSON DistanceType where
3333− parseJSON = withText "DistanceType" parse
3334− where parse "arc" = pure Arc
3335− parse "sloppy_arc" = pure SloppyArc
3336− parse "plane" = pure Plane
3337− parse t = fail ("Unrecognized DistanceType: " <> show t)
3340−instance ToJSON OptimizeBbox where
3341− toJSON NoOptimizeBbox = String "none"
3342− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3344−instance FromJSON OptimizeBbox where
3345− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3346− <|> parseOptimize v
3347− where parseNoOptimize "none" = pure NoOptimizeBbox
3348− parseNoOptimize _ = mzero
3349− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3351−instance ToJSON GeoBoundingBoxConstraint where
3352− toJSON (GeoBoundingBoxConstraint
3353− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3354− object [gbbcGeoBBField .= gbbcConstraintBox
3355− , "_cache" .= cache
3358−instance FromJSON GeoBoundingBoxConstraint where
3359− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3360− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3361− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3363− <*> o .:? "_cache" .!= defaultCache
3365− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3367−instance ToJSON GeoFilterType where
3368− toJSON GeoFilterMemory = String "memory"
3369− toJSON GeoFilterIndexed = String "indexed"
3371−instance FromJSON GeoFilterType where
3372− parseJSON = withText "GeoFilterType" parse
3373− where parse "memory" = pure GeoFilterMemory
3374− parse "indexed" = pure GeoFilterIndexed
3375− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3377−instance ToJSON GeoBoundingBox where
3378− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3379− object ["top_left" .= gbbTopLeft
3380− , "bottom_right" .= gbbBottomRight]
3382−instance FromJSON GeoBoundingBox where
3383− parseJSON = withObject "GeoBoundingBox" parse
3384− where parse o = GeoBoundingBox
3385− <$> o .: "top_left"
3386− <*> o .: "bottom_right"
3388−instance ToJSON LatLon where
3389− toJSON (LatLon lLat lLon) =
3390− object ["lat" .= lLat
3393−instance FromJSON LatLon where
3394− parseJSON = withObject "LatLon" parse
3395− where parse o = LatLon <$> o .: "lat"
3398−-- index for smaller ranges, fielddata for longer ranges
3399−instance ToJSON RangeExecution where
3400− toJSON RangeExecutionIndex = "index"
3401− toJSON RangeExecutionFielddata = "fielddata"
3404−instance FromJSON RangeExecution where
3405− parseJSON = withText "RangeExecution" parse
3406− where parse "index" = pure RangeExecutionIndex
3407− parse "fielddata" = pure RangeExecutionFielddata
3408− parse t = error ("Unrecognized RangeExecution " <> show t)
3410−instance ToJSON RegexpFlags where
3411− toJSON AllRegexpFlags = String "ALL"
3412− toJSON NoRegexpFlags = String "NONE"
3413− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3414− where flagStrs = map flagStr . nub $ h:fs
3415− flagStr AnyString = "ANYSTRING"
3416− flagStr Automaton = "AUTOMATON"
3417− flagStr Complement = "COMPLEMENT"
3418− flagStr Empty = "EMPTY"
3419− flagStr Intersection = "INTERSECTION"
3420− flagStr Interval = "INTERVAL"
3422−instance FromJSON RegexpFlags where
3423− parseJSON = withText "RegexpFlags" parse
3424− where parse "ALL" = pure AllRegexpFlags
3425− parse "NONE" = pure NoRegexpFlags
3426− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3428−instance FromJSON RegexpFlag where
3429− parseJSON = withText "RegexpFlag" parse
3430− where parse "ANYSTRING" = pure AnyString
3431− parse "AUTOMATON" = pure Automaton
3432− parse "COMPLEMENT" = pure Complement
3433− parse "EMPTY" = pure Empty
3434− parse "INTERSECTION" = pure Intersection
3435− parse "INTERVAL" = pure Interval
3436− parse f = fail ("Unknown RegexpFlag: " <> show f)
3438−instance ToJSON Term where
3439− toJSON (Term field value) = object ["term" .= object
3442−instance FromJSON Term where
3443− parseJSON = withObject "Term" parse
3444− where parse o = do termObj <- o .: "term"
3445− case HM.toList termObj of
3446− [(fn, v)] -> Term fn <$> parseJSON v
3447− _ -> fail "Expected object with 1 field-named key"
3449−instance ToJSON BoolMatch where
3450− toJSON (MustMatch term cache) = object ["must" .= term,
3452− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3454− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3457−instance FromJSON BoolMatch where
3458− parseJSON = withObject "BoolMatch" parse
3459− where parse o = mustMatch `taggedWith` "must"
3460− <|> mustNotMatch `taggedWith` "must_not"
3461− <|> shouldMatch `taggedWith` "should"
3462− where taggedWith parser k = parser =<< o .: k
3463− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3464− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3465− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3467instance (FromJSON a) => FromJSON (SearchResult a) where
529instance (FromJSON a) => FromJSON (SearchResult a) where
3468 parseJSON (Object v) = SearchResult <$>
530 parseJSON (Object v) = SearchResult <$>
@@ -3471,65 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3471 v .: "_shards" <*>
533 v .: "_shards" <*>
3472 v .: "hits" <*>
534 v .: "hits" <*>
3473 v .:? "aggregations" <*>
535 v .:? "aggregations" <*>
3474− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
3475− parseJSON _ = empty
537+ v .:? "suggest"
3477−instance (FromJSON a) => FromJSON (SearchHits a) where
3478− parseJSON (Object v) = SearchHits <$>
3480− v .: "max_score" <*>
3482 parseJSON _ = empty
538 parseJSON _ = empty
3484−instance (FromJSON a) => FromJSON (Hit a) where
540+newtype ScrollId =
3485− parseJSON (Object v) = Hit <$>
541+ ScrollId Text
3486− v .: "_index" <*>
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
3490− v .:? "_source" <*>
3492− parseJSON _ = empty
3494−instance FromJSON ShardResult where
3495− parseJSON (Object v) = ShardResult <$>
3497− v .: "successful" <*>
3499− parseJSON _ = empty
3502−instance FromJSON DocVersion where
3505− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3507−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3508−instance FromJSON ReplicaCount where
3509− parseJSON v = parseAsInt v
3510− <|> parseAsString v
3511− where parseAsInt = fmap ReplicaCount . parseJSON
3512− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3514−instance FromJSON ShardCount where
3515− parseJSON v = parseAsInt v
3516− <|> parseAsString v
3517− where parseAsInt = fmap ShardCount . parseJSON
3518− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3520−instance Bounded DocVersion where
3521− minBound = DocVersion 1
3522− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3524−instance Enum DocVersion where
3526− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3527− | otherwise = succError "DocVersion"
3529− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3530− | otherwise = predError "DocVersion"
3532− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3533− fromEnum = docVersionNumber
3534− enumFrom = boundedEnumFrom
3535− enumFromThen = boundedEnumFromThen