@@ -1,8 +1,10 @@
1+{-# LANGUAGE DeriveDataTypeable #-}
2+{-# LANGUAGE DeriveGeneric #-}
1{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE FlexibleInstances #-}
3{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE NamedFieldPuns #-}
7+{-# LANGUAGE NoMonomorphismRestriction #-}
6{-# LANGUAGE OverloadedStrings #-}
8{-# LANGUAGE OverloadedStrings #-}
7{-# LANGUAGE RecordWildCards #-}
9{-# LANGUAGE RecordWildCards #-}
8{-# LANGUAGE UndecidableInstances #-}
10{-# LANGUAGE UndecidableInstances #-}
@@ -10,11 +12,11 @@
10-------------------------------------------------------------------------------
12-------------------------------------------------------------------------------
12-- Module : Database.Bloodhound.Types
14-- Module : Database.Bloodhound.Types
13−-- Copyright : (C) 2014, 2018 Chris Allen
15+-- Copyright : (C) 2014 Chris Allen
14-- License : BSD-style (see the file LICENSE)
16-- License : BSD-style (see the file LICENSE)
15-- Maintainer : Chris Allen <cma@bitemyapp.com
17-- Maintainer : Chris Allen <cma@bitemyapp.com
16-- Stability : provisional
18-- Stability : provisional
17−-- Portability : RecordWildCards
19+-- Portability : DeriveGeneric, RecordWildCards
19-- Data types for describing actions and data structures performed to interact
21-- Data types for describing actions and data structures performed to interact
20-- with Elasticsearch. The two main buckets your queries against Elasticsearch
22-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -42,15 +44,10 @@ module Database.Bloodhound.Types
42 , mkTermsAggregation
44 , mkTermsAggregation
43 , mkTermsScriptAggregation
45 , mkTermsScriptAggregation
44 , mkDateHistogram
46 , mkDateHistogram
45− , mkCardinalityAggregation
46 , mkDocVersion
47 , mkDocVersion
48− , mkExtendedStatsAggregation
49 , docVersionNumber
48 , docVersionNumber
52 , toDateHistogram
50 , toDateHistogram
54 , omitNulls
51 , omitNulls
@@ -61,9 +58,6 @@ module Database.Bloodhound.Types
62 , MonadBH(..)
59 , MonadBH(..)
63 , Version(..)
60 , Version(..)
67 , Status(..)
61 , Status(..)
68 , Existence(..)
62 , Existence(..)
69 , NullValue(..)
63 , NullValue(..)
@@ -71,12 +65,8 @@ module Database.Bloodhound.Types
71 , UpdatableIndexSetting(..)
65 , UpdatableIndexSetting(..)
72 , IndexSettingsSummary(..)
66 , IndexSettingsSummary(..)
73 , AllocationPolicy(..)
67 , AllocationPolicy(..)
75 , ReplicaBounds(..)
68 , ReplicaBounds(..)
76 , Bytes(..)
69 , Bytes(..)
80 , FSType(..)
70 , FSType(..)
81 , InitialShardCount(..)
71 , InitialShardCount(..)
82 , NodeAttrFilter(..)
72 , NodeAttrFilter(..)
@@ -120,8 +110,8 @@ module Database.Bloodhound.Types
120 , Pattern(..)
110 , Pattern(..)
121 , ShardResult(..)
111 , ShardResult(..)
122 , Hit(..)
112 , Hit(..)
124 , Filter(..)
113 , Filter(..)
125 , BoolMatch(..)
115 , BoolMatch(..)
126 , Term(..)
116 , Term(..)
127 , GeoPoint(..)
117 , GeoPoint(..)
@@ -148,22 +138,8 @@ module Database.Bloodhound.Types
148 , RegexpFlags(..)
138 , RegexpFlags(..)
149 , RegexpFlag(..)
139 , RegexpFlag(..)
150 , FieldName(..)
140 , FieldName(..)
154 , Script(..)
141 , Script(..)
155− , ScriptLanguage(..)
161 , IndexName(..)
142 , IndexName(..)
162− , IndexSelection(..)
165− , ForceMergeIndexSettings(..)
166− , defaultForceMergeIndexSettings
167 , TemplateName(..)
143 , TemplateName(..)
168 , TemplatePattern(..)
144 , TemplatePattern(..)
169 , MappingName(..)
145 , MappingName(..)
@@ -187,19 +163,8 @@ module Database.Bloodhound.Types
187 , BoolQuery(..)
163 , BoolQuery(..)
188 , BoostingQuery(..)
164 , BoostingQuery(..)
189 , CommonTermsQuery(..)
165 , CommonTermsQuery(..)
190− , FunctionScoreQuery(..)
193− , FunctionScoreFunctions(..)
194− , ComponentFunctionScoreFunction(..)
195− , FunctionScoreFunction(..)
198− , FieldValueFactor(..)
200− , FactorModifier(..)
201− , FactorMissingFieldValue(..)
202 , DisMaxQuery(..)
166 , DisMaxQuery(..)
203 , FuzzyLikeThisQuery(..)
168 , FuzzyLikeThisQuery(..)
204 , FuzzyLikeFieldQuery(..)
169 , FuzzyLikeFieldQuery(..)
205 , FuzzyQuery(..)
170 , FuzzyQuery(..)
@@ -215,16 +180,10 @@ module Database.Bloodhound.Types
215 , RangeQuery(..)
180 , RangeQuery(..)
216 , RegexpQuery(..)
181 , RegexpQuery(..)
217 , QueryString(..)
182 , QueryString(..)
218− , TemplateQueryInline(..)
219− , TemplateQueryKeyValuePairs(..)
221 , BooleanOperator(..)
183 , BooleanOperator(..)
222 , ZeroTermsQuery(..)
184 , ZeroTermsQuery(..)
223 , CutoffFrequency(..)
185 , CutoffFrequency(..)
224 , Analyzer(..)
186 , Analyzer(..)
228 , MaxExpansions(..)
187 , MaxExpansions(..)
229 , Lenient(..)
188 , Lenient(..)
230 , MatchQueryType(..)
189 , MatchQueryType(..)
@@ -271,108 +230,15 @@ module Database.Bloodhound.Types
271 , CollectionMode(..)
230 , CollectionMode(..)
272 , TermOrder(..)
231 , TermOrder(..)
273 , TermInclusion(..)
232 , 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 (..)
364 , Aggregation(..)
234 , Aggregation(..)
365 , Aggregations
235 , Aggregations
366 , AggregationResults
236 , AggregationResults
368 , Bucket(..)
237 , Bucket(..)
369 , BucketAggregation(..)
238 , BucketAggregation(..)
370 , TermsAggregation(..)
239 , TermsAggregation(..)
371− , MissingAggregation(..)
372 , ValueCountAggregation(..)
240 , ValueCountAggregation(..)
373 , FilterAggregation(..)
241 , FilterAggregation(..)
374− , CardinalityAggregation(..)
375− , MaxAggregation(..)
376 , DateHistogramAggregation(..)
242 , DateHistogramAggregation(..)
377 , DateRangeAggregation(..)
243 , DateRangeAggregation(..)
378 , DateRangeAggRange(..)
244 , DateRangeAggRange(..)
@@ -380,9 +246,6 @@ module Database.Bloodhound.Types
380 , DateMathAnchor(..)
246 , DateMathAnchor(..)
381 , DateMathModifier(..)
247 , DateMathModifier(..)
382 , DateMathUnit(..)
248 , DateMathUnit(..)
383− , TopHitsAggregation(..)
384− , StatisticsAggregation(..)
387 , Highlights(..)
250 , Highlights(..)
388 , FieldHighlight(..)
251 , FieldHighlight(..)
@@ -396,36 +259,646 @@ module Database.Bloodhound.Types
396 , HighlightTag(..)
259 , HighlightTag(..)
397 , HitHighlight
260 , HitHighlight
400 , TermsResult(..)
262 , TermsResult(..)
401 , DateHistogramResult(..)
263 , DateHistogramResult(..)
402 , DateRangeResult(..)
264 , DateRangeResult(..)
405 , EsUsername(..)
266 , EsUsername(..)
406 , EsPassword(..)
267 , EsPassword(..)
408− , Analysis(..)
270+import Control.Applicative
409− , AnalyzerDefinition(..)
271+import Control.Monad.Catch
410− , TokenizerDefinition(..)
272+import Control.Monad.Except
411− , TokenFilterDefinition(..)
273+import Control.Monad.Reader
412− , CharFilterDefinition(..)
274+import Control.Monad.State
413− , Ngram(..)
275+import Control.Monad.Writer
414− , TokenChar(..)
276+import Data.Aeson
415− , Shingle(..)
277+import Data.Aeson.Types (Pair, Parser, emptyObject,
416− , Language(..)
278+ parseMaybe)
417− ) where
279+import qualified Data.ByteString.Lazy.Char8 as L
419−import Bloodhound.Import
281+import Data.Hashable (Hashable)
420−
282+import qualified Data.HashMap.Strict as HM
421−import Database.Bloodhound.Internal.Aggregation
283+import Data.List (foldl', nub)
422−import Database.Bloodhound.Internal.Analysis
284+import Data.List.NonEmpty (NonEmpty (..), toList)
423−import Database.Bloodhound.Internal.Client
285+import qualified Data.Map.Strict as M
424−import Database.Bloodhound.Internal.Highlight
286+import Data.Maybe
425−import Database.Bloodhound.Internal.Newtypes
287+import Data.Text (Text)
426−import Database.Bloodhound.Internal.Query
288+import qualified Data.Text as T
427−import Database.Bloodhound.Internal.Sort
289+import Data.Time.Calendar
428−import Database.Bloodhound.Internal.Suggest
290+import Data.Time.Clock (NominalDiffTime, UTCTime)
291+import Data.Time.Clock.POSIX
292+import qualified Data.Traversable as DT
293+import Data.Typeable (Typeable)
294+import qualified Data.Vector as V
296+import GHC.Generics (Generic)
297+import Network.HTTP.Client
298+import qualified Network.HTTP.Types.Method as NHTM
300+import Database.Bloodhound.Types.Class
301+import Database.Bloodhound.Types.Internal
304+-- >>> :set -XOverloadedStrings
305+-- >>> import Database.Bloodhound
306+-- >>> let testServer = (Server "http://localhost:9200")
307+-- >>> let testIndex = IndexName "twitter"
308+-- >>> let testMapping = MappingName "tweet"
309+-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
311+-- defaultIndexSettings is exported by Database.Bloodhound as well
312+-- no trailing slashes in servers, library handles building the path.
314+-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
315+-- will be a noop. You can use the exported fields to customize it further, e.g.:
317+-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
318+mkBHEnv :: Server -> Manager -> BHEnv
319+mkBHEnv s m = BHEnv s m return
321+newtype BH m a = BH {
322+ unBH :: ReaderT BHEnv m a
323+ } deriving ( Functor
337+instance MonadTrans BH where
340+instance (MonadReader r m) => MonadReader r (BH m) where
342+ local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
345+instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
346+ getBHEnv = BH getBHEnv
348+runBH :: BHEnv -> BH m a -> m a
349+runBH e f = runReaderT (unBH f) e
351+{-| 'Version' is embedded in 'Status' -}
352+data Version = Version { number :: Text
353+ , build_hash :: Text
354+ , build_timestamp :: UTCTime
355+ , build_snapshot :: Bool
356+ , lucene_version :: Text } deriving (Eq, Show, Generic, Typeable)
358+{-| 'Status' is a data type for describing the JSON body returned by
359+ Elasticsearch when you query its status. This was deprecated in 1.2.0.
361+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
364+data Status = Status { ok :: Maybe Bool
367+ , version :: Version
368+ , tagline :: Text } deriving (Eq, Show, Generic)
370+{-| 'IndexSettings' is used to configure the shards and replicas when you create
371+ an Elasticsearch Index.
373+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
377+ IndexSettings { indexShards :: ShardCount
378+ , indexReplicas :: ReplicaCount } deriving (Eq, Show, Generic, Typeable)
380+{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
381+defaultIndexSettings :: IndexSettings
382+defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
384+{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
386+ <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
388+data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
389+ -- ^ The number of replicas each shard has.
390+ | AutoExpandReplicas ReplicaBounds
391+ | BlocksReadOnly Bool
392+ -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
394+ -- ^ Set to True to disable read operations against the index.
396+ -- ^ Set to True to disable write operations against the index.
397+ | BlocksMetaData Bool
398+ -- ^ Set to True to disable metadata operations against the index.
399+ | RefreshInterval NominalDiffTime
400+ -- ^ The async refresh interval of a shard
401+ | IndexConcurrency Int
402+ | FailOnMergeFailure Bool
403+ | TranslogFlushThresholdOps Int
404+ -- ^ When to flush on operations.
405+ | TranslogFlushThresholdSize Bytes
406+ -- ^ When to flush based on translog (bytes) size.
407+ | TranslogFlushThresholdPeriod NominalDiffTime
408+ -- ^ When to flush based on a period of not flushing.
409+ | TranslogDisableFlush Bool
410+ -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
411+ | CacheFilterMaxSize (Maybe Bytes)
412+ -- ^ The maximum size of filter cache (per segment in shard).
413+ | CacheFilterExpire (Maybe NominalDiffTime)
414+ -- ^ The expire after access time for filter cache.
415+ | GatewaySnapshotInterval NominalDiffTime
416+ -- ^ The gateway snapshot interval (only applies to shared gateways).
417+ | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
418+ -- ^ A node matching any rule will be allowed to host shards from the index.
419+ | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
420+ -- ^ A node matching any rule will NOT be allowed to host shards from the index.
421+ | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
422+ -- ^ Only nodes matching all rules will be allowed to host shards from the index.
423+ | RoutingAllocationEnable AllocationPolicy
424+ -- ^ Enables shard allocation for a specific index.
425+ | RoutingAllocationShardsPerNode ShardCount
426+ -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
427+ | RecoveryInitialShards InitialShardCount
428+ -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
429+ | GCDeletes NominalDiffTime
430+ | TTLDisablePurge Bool
431+ -- ^ Disables temporarily the purge of expired docs.
432+ | TranslogFSType FSType
433+ | IndexCompoundFormat CompoundFormat
434+ | IndexCompoundOnFlush Bool
435+ | WarmerEnabled Bool
436+ deriving (Eq, Show, Generic, Typeable)
438+data AllocationPolicy = AllocAll
439+ -- ^ Allows shard allocation for all shards.
441+ -- ^ Allows shard allocation only for primary shards.
443+ -- ^ Allows shard allocation only for primary shards for new indices.
445+ -- ^ No shard allocation is allowed
446+ deriving (Eq, Show, Generic, Typeable)
448+data ReplicaBounds = ReplicasBounded Int Int
449+ | ReplicasLowerBounded Int
451+ deriving (Eq, Show, Generic, Typeable)
453+newtype Bytes = Bytes Int deriving (Eq, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
455+data FSType = FSSimple
456+ | FSBuffered deriving (Eq, Show, Generic, Typeable, Ord)
458+data InitialShardCount = QuorumShards
459+ | QuorumMinus1Shards
462+ | ExplicitShards Int
463+ deriving (Eq, Show, Generic, Typeable)
465+data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
466+ , nodeAttrFilterValues :: NonEmpty Text}
467+ deriving (Eq, Show, Generic, Ord)
469+newtype NodeAttrName = NodeAttrName Text deriving (Eq, Show, Ord, Generic, Typeable)
471+data CompoundFormat = CompoundFileFormat Bool
472+ | MergeSegmentVsTotalIndex Double
473+ -- ^ percentage between 0 and 1 where 0 is false, 1 is true
474+ deriving (Eq, Show, Generic, Typeable)
476+newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
478+data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
479+ , sSummaryFixedSettings :: IndexSettings
480+ , sSummaryUpdateable :: [UpdatableIndexSetting]}
481+ deriving (Eq, Show, Generic, Typeable)
483+{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
484+type Reply = Network.HTTP.Client.Response L.ByteString
485+type Method = NHTM.Method
487+{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
489+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
491+data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show, Generic, Typeable)
493+data FieldType = GeoPointType
499+ | ByteType deriving (Eq, Show, Generic, Typeable)
501+data FieldDefinition =
502+ FieldDefinition { fieldType :: FieldType } deriving (Eq, Show, Generic, Typeable)
504+{-| An 'IndexTemplate' defines a template that will automatically be
505+ applied to new indices created. The templates include both
506+ 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
507+ controls if the template will be applied to the index created.
508+ Specify mappings as follows: @[toJSON TweetMapping, ...]@
510+ https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
513+ IndexTemplate { templatePattern :: TemplatePattern
514+ , templateSettings :: Maybe IndexSettings
515+ , templateMappings :: [Value]
519+ MappingField { mappingFieldName :: FieldName
520+ , fieldDefinition :: FieldDefinition } deriving (Eq, Show, Generic, Typeable)
522+{-| Support for type reification of 'Mapping's is currently incomplete, for
523+ now the mapping API verbiage expects a 'ToJSON'able blob.
525+ Indexes have mappings, mappings are schemas for the documents contained in the
526+ index. I'd recommend having only one mapping per index, always having a mapping,
527+ and keeping different kinds of documents separated if possible.
529+data Mapping = Mapping { typeName :: TypeName
530+ , mappingFields :: [MappingField] } deriving (Eq, Show, Generic, Typeable)
532+{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
533+ operation index, create, delete, and update. 'BulkIndex' behaves like an
534+ "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
536+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
539+ BulkIndex IndexName MappingName DocId Value
540+ | BulkCreate IndexName MappingName DocId Value
541+ | BulkDelete IndexName MappingName DocId
542+ | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show, Generic, Typeable)
544+{-| 'EsResult' describes the standard wrapper JSON document that you see in
545+ successful Elasticsearch lookups or lookups that couldn't find the document.
547+data EsResult a = EsResult { _index :: Text
550+ , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show, Generic, Typeable)
552+{-| 'EsResultFound' contains the document and its metadata inside of an
553+ 'EsResult' when the document was successfully found.
555+data EsResultFound a = EsResultFound { _version :: DocVersion
556+ , _source :: a } deriving (Eq, Show, Generic, Typeable)
558+{-| 'EsError' is the generic type that will be returned when there was a
559+ problem. If you can't parse the expected response, its a good idea to
562+data EsError = EsError { errorStatus :: Int
563+ , errorMessage :: Text } deriving (Eq, Show, Generic, Typeable)
565+{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
566+returned by the ElasticSearch server. If you encounter this error, please
567+verify that your domain data types and FromJSON instances are working properly
568+(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
569+sure that your mappings are correct, then this error may be an indication of an
570+incompatibility between Bloodhound and ElasticSearch. Please open a bug report
571+and be sure to include the exception body.
573+data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
574+ deriving (Eq, Show, Generic, Typeable)
576+instance Exception EsProtocolException
578+data IndexAlias = IndexAlias { srcIndex :: IndexName
579+ , indexAlias :: IndexAliasName } deriving (Eq, Show, Generic, Typeable)
581+newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Show, Generic, ToJSON)
583+data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
584+ | RemoveAlias IndexAlias deriving (Show, Eq, Generic, Typeable)
586+data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
587+ , aliasCreateFilter :: Maybe Filter}
588+ deriving (Show, Eq, Generic, Typeable)
590+data AliasRouting = AllAliasRouting RoutingValue
591+ | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
592+ deriving (Show, Eq, Generic, Typeable)
594+newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Show, Eq, Generic, Typeable)
596+newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
598+newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
600+newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Show, Eq, Generic, Typeable)
602+{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
603+data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
604+ , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Show, Eq, Generic, Typeable)
606+{-| 'DocVersion' is an integer version number for a document between 1
607+and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
609+newtype DocVersion = DocVersion {
610+ docVersionNumber :: Int
611+ } deriving (Eq, Show, Generic, Ord, ToJSON)
613+-- | Smart constructor for in-range doc version
614+mkDocVersion :: Int -> Maybe DocVersion
616+ | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
618+ | otherwise = Nothing
621+{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
622+own version numbers instead of ones from ES.
624+newtype ExternalDocVersion = ExternalDocVersion DocVersion
625+ deriving (Eq, Show, Generic, Ord, Bounded, Enum, ToJSON)
627+{-| 'VersionControl' is specified when indexing documents as a
628+optimistic concurrency control.
630+data VersionControl = NoVersionControl
631+ -- ^ Don't send a version. This is a pure overwrite.
632+ | InternalVersion DocVersion
633+ -- ^ Use the default ES versioning scheme. Only
634+ -- index the document if the version is the same
635+ -- as the one specified. Only applicable to
636+ -- updates, as you should be getting Version from
638+ | ExternalGT ExternalDocVersion
639+ -- ^ Use your own version numbering. Only index
640+ -- the document if the version is strictly higher
641+ -- OR the document doesn't exist. The given
642+ -- version will be used as the new version number
643+ -- for the stored document. N.B. All updates must
644+ -- increment this number, meaning there is some
645+ -- global, external ordering of updates.
646+ | ExternalGTE ExternalDocVersion
647+ -- ^ Use your own version numbering. Only index
648+ -- the document if the version is equal or higher
649+ -- than the stored version. Will succeed if there
650+ -- is no existing document. The given version will
651+ -- be used as the new version number for the
652+ -- stored document. Use with care, as this could
653+ -- result in data loss.
654+ | ForceVersion ExternalDocVersion
655+ -- ^ The document will always be indexed and the
656+ -- given version will be the new version. This is
657+ -- typically used for correcting errors. Use with
658+ -- care, as this could result in data loss.
659+ deriving (Show, Eq, Generic, Ord)
661+{-| 'DocumentParent' is used to specify a parent document.
663+newtype DocumentParent = DocumentParent DocId
664+ deriving (Eq, Show, Generic, Typeable)
666+{-| 'IndexDocumentSettings' are special settings supplied when indexing
667+a document. For the best backwards compatiblity when new fields are
668+added, you should probably prefer to start with 'defaultIndexDocumentSettings'
670+data IndexDocumentSettings =
671+ IndexDocumentSettings { idsVersionControl :: VersionControl
672+ , idsParent :: Maybe DocumentParent
673+ } deriving (Eq, Show, Generic, Typeable)
675+{-| Reasonable default settings. Chooses no version control and no parent.
677+defaultIndexDocumentSettings :: IndexDocumentSettings
678+defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
680+{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
681+ dependent with later sorts acting as tie-breakers for earlier sorts.
683+type Sort = [SortSpec]
685+{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
686+ 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
687+ 'DistanceUnit' to express "nearness" to a single geographical point as a
690+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
692+data SortSpec = DefaultSortSpec DefaultSort
693+ | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show, Generic, Typeable)
695+{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
696+ 'mkSort' convenience function for when you want to specify only the most
699+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
702+ DefaultSort { sortFieldName :: FieldName
703+ , sortOrder :: SortOrder
705+ , ignoreUnmapped :: Bool
706+ , sortMode :: Maybe SortMode
707+ , missingSort :: Maybe Missing
708+ , nestedFilter :: Maybe Filter } deriving (Eq, Show, Generic, Typeable)
710+{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
711+ encoded into "asc" or "desc" when turned into JSON.
713+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
715+data SortOrder = Ascending
716+ | Descending deriving (Eq, Show, Generic, Typeable)
718+{-| 'Missing' prescribes how to handle missing fields. A missing field can be
719+ sorted last, first, or using a custom value as a substitute.
721+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
723+data Missing = LastMissing
725+ | CustomMissing Text deriving (Eq, Show, Generic, Typeable)
727+{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
729+http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
731+data SortMode = SortMin
734+ | SortAvg deriving (Eq, Show, Generic, Typeable)
736+{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
737+ that you can concisely describe the usual kind of 'SortSpec's you want.
739+mkSort :: FieldName -> SortOrder -> DefaultSort
740+mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
742+{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
743+ 'Query's cannot be cached.
745+type Cache = Bool -- caching on/off
746+defaultCache :: Cache
749+{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
751+type PrefixValue = Text
753+{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
754+ JSON encoding baked in. Used all over the place.
756+data BooleanOperator = And | Or deriving (Eq, Show, Generic, Typeable)
758+{-| 'ShardCount' is part of 'IndexSettings'
760+newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
762+{-| 'ReplicaCount' is part of 'IndexSettings'
764+newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
766+{-| 'IndexName' is used to describe which index to query/create/delete
768+newtype IndexName = IndexName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
770+{-| 'TemplateName' is used to describe which template to query/create/delete
772+newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
774+{-| 'TemplatePattern' represents a pattern which is matched against index names
776+newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
778+{-| 'MappingName' is part of mappings which are how ES describes and schematizes
779+ the data in the indices.
781+newtype MappingName = MappingName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
783+{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
784+ Can be set by the user or created by ES itself. Often used in client
785+ functions for poking at specific documents.
787+newtype DocId = DocId Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
789+{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
791+newtype QueryString = QueryString Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
793+{-| 'FieldName' is used all over the place wherever a specific field within
794+ a document needs to be specified, usually in 'Query's or 'Filter's.
796+newtype FieldName = FieldName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
799+{-| 'Script' is often used in place of 'FieldName' to specify more
800+complex ways of extracting a value from a document.
802+newtype Script = Script { scriptText :: Text } deriving (Eq, Show, Generic, Typeable)
804+{-| 'CacheName' is used in 'RegexpFilter' for describing the
805+ 'CacheKey' keyed caching behavior.
807+newtype CacheName = CacheName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
809+{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
812+ CacheKey Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
814+ Existence Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
816+ NullValue Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
817+newtype CutoffFrequency =
818+ CutoffFrequency Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
820+ Analyzer Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
821+newtype MaxExpansions =
822+ MaxExpansions Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
824+{-| 'Lenient', if set to true, will cause format based failures to be
825+ ignored. I don't know what the bloody default is, Elasticsearch
826+ documentation didn't say what it was. Let me know if you figure it out.
829+ Lenient Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
831+ Tiebreaker Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
833+ Boost Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
835+ BoostTerms Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
837+{-| 'MinimumMatch' controls how many should clauses in the bool query should
838+ match. Can be an absolute value (2) or a percentage (30%) or a
839+ combination of both.
841+newtype MinimumMatch =
842+ MinimumMatch Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
843+newtype DisableCoord =
844+ DisableCoord Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
845+newtype IgnoreTermFrequency =
846+ IgnoreTermFrequency Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
847+newtype MinimumTermFrequency =
848+ MinimumTermFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
849+newtype MaxQueryTerms =
850+ MaxQueryTerms Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
852+ Fuzziness Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
854+{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
855+newtype PrefixLength =
856+ PrefixLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
858+ TypeName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
859+newtype PercentMatch =
860+ PercentMatch Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
862+ StopWord Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
864+ QueryPath Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
866+{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
867+ heavy, because all terms in the index need to be examined, just in case
868+ they match. Leading wildcards can be disabled by setting
869+ 'AllowLeadingWildcard' to false. -}
870+newtype AllowLeadingWildcard =
871+ AllowLeadingWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
872+newtype LowercaseExpanded =
873+ LowercaseExpanded Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
874+newtype EnablePositionIncrements =
875+ EnablePositionIncrements Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
877+{-| By default, wildcard terms in a query are not analyzed.
878+ Setting 'AnalyzeWildcard' to true enables best-effort analysis.
880+newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
882+{-| 'GeneratePhraseQueries' defaults to false.
884+newtype GeneratePhraseQueries =
885+ GeneratePhraseQueries Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
887+{-| 'Locale' is used for string conversions - defaults to ROOT.
889+newtype Locale = Locale Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
890+newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
891+newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
893+{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
894+ phrase matches. Default is 0.
896+newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
897+newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
898+newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
900+-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
901+newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
430{-| 'unpackId' is a silly convenience function that gets used once.
903{-| 'unpackId' is a silly convenience function that gets used once.
@@ -433,6 +906,8 @@ unpackId :: DocId -> Text
433unpackId (DocId docId) = docId
906unpackId (DocId docId) = docId
435type TrackSortScores = Bool
908type TrackSortScores = Bool
909+newtype From = From Int deriving (Eq, Show, Generic, ToJSON)
910+newtype Size = Size Int deriving (Eq, Show, Generic, ToJSON)
437data Search = Search { queryBody :: Maybe Query
912data Search = Search { queryBody :: Maybe Query
438 , filterBody :: Maybe Filter
913 , filterBody :: Maybe Filter
@@ -444,74 +919,537 @@ data Search = Search { queryBody :: Maybe Query
444 , from :: From
919 , from :: From
445 , size :: Size
920 , size :: Size
446 , searchType :: SearchType
921 , searchType :: SearchType
447− , searchAfterKey :: Maybe SearchAfterKey
448 , fields :: Maybe [FieldName]
922 , fields :: Maybe [FieldName]
449− , scriptFields :: Maybe ScriptFields
450− , source :: Maybe Source
923+ , source :: Maybe Source } deriving (Eq, Show, Generic, Typeable)
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)
480data SearchType = SearchTypeQueryThenFetch
925data SearchType = SearchTypeQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
926 | SearchTypeDfsQueryThenFetch
929+ | SearchTypeQueryAndFetch
930+ | SearchTypeDfsQueryAndFetch
482− deriving (Eq, Show)
931+ deriving (Eq, Show, Generic, Typeable)
484data Source =
933data Source =
486 | SourcePatterns PatternOrPatterns
935 | SourcePatterns PatternOrPatterns
487 | SourceIncludeExclude Include Exclude
936 | SourceIncludeExclude Include Exclude
488− deriving (Eq, Show)
937+ deriving (Show, Eq, Generic, Typeable)
490−instance ToJSON Source where
491− toJSON NoSource = toJSON False
492− toJSON (SourcePatterns patterns) = toJSON patterns
493− toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
495data PatternOrPatterns = PopPattern Pattern
939data PatternOrPatterns = PopPattern Pattern
496− | PopPatterns [Pattern] deriving (Eq, Read, Show)
940+ | PopPatterns [Pattern] deriving (Eq, Show, Generic, Typeable)
498−instance ToJSON PatternOrPatterns where
942+data Include = Include [Pattern] deriving (Eq, Show, Generic, Typeable)
499− toJSON (PopPattern pattern) = toJSON pattern
943+data Exclude = Exclude [Pattern] deriving (Eq, Show, Generic, Typeable)
500− toJSON (PopPatterns patterns) = toJSON patterns
502−data Include = Include [Pattern] deriving (Eq, Read, Show)
945+newtype Pattern = Pattern Text deriving (Eq, Show, Generic, Typeable)
503−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
505−instance ToJSON Include where
947+data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
506− toJSON (Include patterns) = toJSON patterns
948+ , highlightFields :: [FieldHighlight]
949+ } deriving (Show, Eq, Generic, Typeable)
508−instance ToJSON Exclude where
951+data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
509− toJSON (Exclude patterns) = toJSON patterns
952+ deriving (Show, Eq, Generic, Typeable)
511−newtype Pattern = Pattern Text deriving (Eq, Read, Show)
513−instance ToJSON Pattern where
955+data HighlightSettings = Plain PlainHighlight
514− toJSON (Pattern pattern) = toJSON pattern
956+ | Postings PostingsHighlight
957+ | FastVector FastVectorHighlight
958+ deriving (Show, Eq, Generic, Typeable)
959+data PlainHighlight =
960+ PlainHighlight { plainCommon :: Maybe CommonHighlight
961+ , plainNonPost :: Maybe NonPostings } deriving (Show, Eq, Generic, Typeable)
963+ -- This requires that index_options are set to 'offset' in the mapping.
964+data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq, Generic, Typeable)
966+-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
967+data FastVectorHighlight =
968+ FastVectorHighlight { fvCommon :: Maybe CommonHighlight
969+ , fvNonPostSettings :: Maybe NonPostings
970+ , boundaryChars :: Maybe Text
971+ , boundaryMaxScan :: Maybe Int
972+ , fragmentOffset :: Maybe Int
973+ , matchedFields :: [Text]
974+ , phraseLimit :: Maybe Int
975+ } deriving (Show, Eq, Generic, Typeable)
977+data CommonHighlight =
978+ CommonHighlight { order :: Maybe Text
979+ , forceSource :: Maybe Bool
980+ , tag :: Maybe HighlightTag
981+ , encoder :: Maybe HighlightEncoder
982+ , noMatchSize :: Maybe Int
983+ , highlightQuery :: Maybe Query
984+ , requireFieldMatch :: Maybe Bool
985+ } deriving (Show, Eq, Generic, Typeable)
987+-- Settings that are only applicable to FastVector and Plain highlighters.
989+ NonPostings { fragmentSize :: Maybe Int
990+ , numberOfFragments :: Maybe Int} deriving (Show, Eq, Generic, Typeable)
992+data HighlightEncoder = DefaultEncoder
994+ deriving (Show, Eq, Generic, Typeable)
996+-- NOTE: Should the tags use some kind of HTML type, rather than Text?
997+data HighlightTag = TagSchema Text
998+ | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
999+ deriving (Show, Eq, Generic, Typeable)
1003+ TermQuery Term (Maybe Boost)
1004+ | TermsQuery Text (NonEmpty Text)
1005+ | QueryMatchQuery MatchQuery
1006+ | QueryMultiMatchQuery MultiMatchQuery
1007+ | QueryBoolQuery BoolQuery
1008+ | QueryBoostingQuery BoostingQuery
1009+ | QueryCommonTermsQuery CommonTermsQuery
1010+ | ConstantScoreFilter Filter Boost
1011+ | ConstantScoreQuery Query Boost
1012+ | QueryDisMaxQuery DisMaxQuery
1013+ | QueryFilteredQuery FilteredQuery
1014+ | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1015+ | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1016+ | QueryFuzzyQuery FuzzyQuery
1017+ | QueryHasChildQuery HasChildQuery
1018+ | QueryHasParentQuery HasParentQuery
1019+ | IdsQuery MappingName [DocId]
1020+ | QueryIndicesQuery IndicesQuery
1021+ | MatchAllQuery (Maybe Boost)
1022+ | QueryMoreLikeThisQuery MoreLikeThisQuery
1023+ | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1024+ | QueryNestedQuery NestedQuery
1025+ | QueryPrefixQuery PrefixQuery
1026+ | QueryQueryStringQuery QueryStringQuery
1027+ | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1028+ | QueryRangeQuery RangeQuery
1029+ | QueryRegexpQuery RegexpQuery
1030+ deriving (Eq, Show, Generic, Typeable)
1033+ RegexpQuery { regexpQueryField :: FieldName
1034+ , regexpQuery :: Regexp
1035+ , regexpQueryFlags :: RegexpFlags
1036+ , regexpQueryBoost :: Maybe Boost
1037+ } deriving (Eq, Show, Generic, Typeable)
1040+ RangeQuery { rangeQueryField :: FieldName
1041+ , rangeQueryRange :: RangeValue
1042+ , rangeQueryBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1044+mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1045+mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1047+data SimpleQueryStringQuery =
1048+ SimpleQueryStringQuery
1049+ { simpleQueryStringQuery :: QueryString
1050+ , simpleQueryStringField :: Maybe FieldOrFields
1051+ , simpleQueryStringOperator :: Maybe BooleanOperator
1052+ , simpleQueryStringAnalyzer :: Maybe Analyzer
1053+ , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1054+ , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1055+ , simpleQueryStringLocale :: Maybe Locale
1056+ } deriving (Eq, Show, Generic, Typeable)
1058+data SimpleQueryFlag =
1063+ | SimpleQueryPrefix
1064+ | SimpleQueryPhrase
1065+ | SimpleQueryPrecedence
1066+ | SimpleQueryEscape
1067+ | SimpleQueryWhitespace
1070+ | SimpleQuerySlop deriving (Eq, Show, Generic, Typeable)
1072+-- use_dis_max and tie_breaker when fields are plural?
1073+data QueryStringQuery =
1075+ { queryStringQuery :: QueryString
1076+ , queryStringDefaultField :: Maybe FieldName
1077+ , queryStringOperator :: Maybe BooleanOperator
1078+ , queryStringAnalyzer :: Maybe Analyzer
1079+ , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1080+ , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1081+ , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1082+ , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1083+ , queryStringFuzziness :: Maybe Fuzziness
1084+ , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1085+ , queryStringPhraseSlop :: Maybe PhraseSlop
1086+ , queryStringBoost :: Maybe Boost
1087+ , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1088+ , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1089+ , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1090+ , queryStringLenient :: Maybe Lenient
1091+ , queryStringLocale :: Maybe Locale
1092+ } deriving (Eq, Show, Generic, Typeable)
1094+mkQueryStringQuery :: QueryString -> QueryStringQuery
1095+mkQueryStringQuery qs =
1096+ QueryStringQuery qs Nothing Nothing
1097+ Nothing Nothing Nothing Nothing
1098+ Nothing Nothing Nothing Nothing
1099+ Nothing Nothing Nothing Nothing
1102+data FieldOrFields = FofField FieldName
1103+ | FofFields (NonEmpty FieldName) deriving (Eq, Show, Generic, Typeable)
1107+ { prefixQueryField :: FieldName
1108+ , prefixQueryPrefixValue :: Text
1109+ , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1113+ { nestedQueryPath :: QueryPath
1114+ , nestedQueryScoreType :: ScoreType
1115+ , nestedQuery :: Query } deriving (Eq, Show, Generic, Typeable)
1117+data MoreLikeThisFieldQuery =
1118+ MoreLikeThisFieldQuery
1119+ { moreLikeThisFieldText :: Text
1120+ , moreLikeThisFieldFields :: FieldName
1121+ -- default 0.3 (30%)
1122+ , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1123+ , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1124+ , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1125+ , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1126+ , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1127+ , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1128+ , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1129+ , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1130+ , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1131+ , moreLikeThisFieldBoost :: Maybe Boost
1132+ , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1133+ } deriving (Eq, Show, Generic, Typeable)
1135+data MoreLikeThisQuery =
1137+ { moreLikeThisText :: Text
1138+ , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1139+ -- default 0.3 (30%)
1140+ , moreLikeThisPercentMatch :: Maybe PercentMatch
1141+ , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1142+ , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1143+ , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1144+ , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1145+ , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1146+ , moreLikeThisMinWordLength :: Maybe MinWordLength
1147+ , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1148+ , moreLikeThisBoostTerms :: Maybe BoostTerms
1149+ , moreLikeThisBoost :: Maybe Boost
1150+ , moreLikeThisAnalyzer :: Maybe Analyzer
1151+ } deriving (Eq, Show, Generic, Typeable)
1155+ { indicesQueryIndices :: [IndexName]
1156+ , indicesQuery :: Query
1158+ , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show, Generic, Typeable)
1160+data HasParentQuery =
1162+ { hasParentQueryType :: TypeName
1163+ , hasParentQuery :: Query
1164+ , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1166+data HasChildQuery =
1168+ { hasChildQueryType :: TypeName
1169+ , hasChildQuery :: Query
1170+ , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1176+ | ScoreTypeNone deriving (Eq, Show, Generic, Typeable)
1179+ FuzzyQuery { fuzzyQueryField :: FieldName
1180+ , fuzzyQueryValue :: Text
1181+ , fuzzyQueryPrefixLength :: PrefixLength
1182+ , fuzzyQueryMaxExpansions :: MaxExpansions
1183+ , fuzzyQueryFuzziness :: Fuzziness
1184+ , fuzzyQueryBoost :: Maybe Boost
1185+ } deriving (Eq, Show, Generic, Typeable)
1187+data FuzzyLikeFieldQuery =
1188+ FuzzyLikeFieldQuery
1189+ { fuzzyLikeField :: FieldName
1190+ -- anaphora is good for the soul.
1191+ , fuzzyLikeFieldText :: Text
1192+ , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1193+ , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1194+ , fuzzyLikeFieldFuzziness :: Fuzziness
1195+ , fuzzyLikeFieldPrefixLength :: PrefixLength
1196+ , fuzzyLikeFieldBoost :: Boost
1197+ , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1198+ } deriving (Eq, Show, Generic, Typeable)
1200+data FuzzyLikeThisQuery =
1202+ { fuzzyLikeFields :: [FieldName]
1203+ , fuzzyLikeText :: Text
1204+ , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1205+ , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1206+ , fuzzyLikeFuzziness :: Fuzziness
1207+ , fuzzyLikePrefixLength :: PrefixLength
1208+ , fuzzyLikeBoost :: Boost
1209+ , fuzzyLikeAnalyzer :: Maybe Analyzer
1210+ } deriving (Eq, Show, Generic, Typeable)
1212+data FilteredQuery =
1214+ { filteredQuery :: Query
1215+ , filteredFilter :: Filter } deriving (Eq, Show, Generic, Typeable)
1218+ DisMaxQuery { disMaxQueries :: [Query]
1220+ , disMaxTiebreaker :: Tiebreaker
1221+ , disMaxBoost :: Maybe Boost
1222+ } deriving (Eq, Show, Generic, Typeable)
1225+ MatchQuery { matchQueryField :: FieldName
1226+ , matchQueryQueryString :: QueryString
1227+ , matchQueryOperator :: BooleanOperator
1228+ , matchQueryZeroTerms :: ZeroTermsQuery
1229+ , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1230+ , matchQueryMatchType :: Maybe MatchQueryType
1231+ , matchQueryAnalyzer :: Maybe Analyzer
1232+ , matchQueryMaxExpansions :: Maybe MaxExpansions
1233+ , matchQueryLenient :: Maybe Lenient
1234+ , matchQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1236+{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1237+ enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1239+mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1240+mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1242+data MatchQueryType =
1244+ | MatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1246+data MultiMatchQuery =
1247+ MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1248+ , multiMatchQueryString :: QueryString
1249+ , multiMatchQueryOperator :: BooleanOperator
1250+ , multiMatchQueryZeroTerms :: ZeroTermsQuery
1251+ , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1252+ , multiMatchQueryType :: Maybe MultiMatchQueryType
1253+ , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1254+ , multiMatchQueryAnalyzer :: Maybe Analyzer
1255+ , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1256+ , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show, Generic, Typeable)
1258+{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1259+ enabling you to provide only the list of 'FieldName's and 'QueryString' to
1260+ make a 'MultiMatchQuery'.
1263+mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1264+mkMultiMatchQuery matchFields query =
1265+ MultiMatchQuery matchFields query
1266+ Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1268+data MultiMatchQueryType =
1269+ MultiMatchBestFields
1270+ | MultiMatchMostFields
1271+ | MultiMatchCrossFields
1273+ | MultiMatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1276+ BoolQuery { boolQueryMustMatch :: [Query]
1277+ , boolQueryMustNotMatch :: [Query]
1278+ , boolQueryShouldMatch :: [Query]
1279+ , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1280+ , boolQueryBoost :: Maybe Boost
1281+ , boolQueryDisableCoord :: Maybe DisableCoord
1282+ } deriving (Eq, Show, Generic, Typeable)
1284+mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1285+mkBoolQuery must mustNot should =
1286+ BoolQuery must mustNot should Nothing Nothing Nothing
1288+data BoostingQuery =
1289+ BoostingQuery { positiveQuery :: Query
1290+ , negativeQuery :: Query
1291+ , negativeBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1293+data CommonTermsQuery =
1294+ CommonTermsQuery { commonField :: FieldName
1295+ , commonQuery :: QueryString
1296+ , commonCutoffFrequency :: CutoffFrequency
1297+ , commonLowFreqOperator :: BooleanOperator
1298+ , commonHighFreqOperator :: BooleanOperator
1299+ , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1300+ , commonBoost :: Maybe Boost
1301+ , commonAnalyzer :: Maybe Analyzer
1302+ , commonDisableCoord :: Maybe DisableCoord
1303+ } deriving (Eq, Show, Generic, Typeable)
1305+data CommonMinimumMatch =
1306+ CommonMinimumMatchHighLow MinimumMatchHighLow
1307+ | CommonMinimumMatch MinimumMatch
1308+ deriving (Eq, Show, Generic, Typeable)
1310+data MinimumMatchHighLow =
1311+ MinimumMatchHighLow { lowFreq :: MinimumMatch
1312+ , highFreq :: MinimumMatch } deriving (Eq, Show, Generic, Typeable)
1314+data Filter = AndFilter [Filter] Cache
1315+ | OrFilter [Filter] Cache
1316+ | NotFilter Filter Cache
1318+ | BoolFilter BoolMatch
1319+ | ExistsFilter FieldName -- always cached
1320+ | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1321+ | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1322+ | GeoDistanceRangeFilter GeoPoint DistanceRange
1323+ | GeoPolygonFilter FieldName [LatLon]
1324+ | IdsFilter MappingName [DocId]
1326+ | MissingFilter FieldName Existence NullValue
1327+ | PrefixFilter FieldName PrefixValue Cache
1328+ | QueryFilter Query Cache
1329+ | RangeFilter FieldName RangeValue RangeExecution Cache
1330+ | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1331+ | TermFilter Term Cache
1332+ deriving (Eq, Show, Generic, Typeable)
1334+data ZeroTermsQuery = ZeroTermsNone
1335+ | ZeroTermsAll deriving (Eq, Show, Generic, Typeable)
1337+data RangeExecution = RangeExecutionIndex
1338+ | RangeExecutionFielddata deriving (Eq, Show, Generic, Typeable)
1340+newtype Regexp = Regexp Text deriving (Eq, Show, Generic, Typeable, FromJSON)
1342+data RegexpFlags = AllRegexpFlags
1344+ | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show, Generic, Typeable)
1346+data RegexpFlag = AnyString
1351+ | Interval deriving (Eq, Show, Generic, Typeable)
1353+newtype LessThan = LessThan Double deriving (Eq, Show, Generic, Typeable)
1354+newtype LessThanEq = LessThanEq Double deriving (Eq, Show, Generic, Typeable)
1355+newtype GreaterThan = GreaterThan Double deriving (Eq, Show, Generic, Typeable)
1356+newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show, Generic, Typeable)
1358+newtype LessThanD = LessThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1359+newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1360+newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1361+newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1363+data RangeValue = RangeDateLte LessThanEqD
1364+ | RangeDateLt LessThanD
1365+ | RangeDateGte GreaterThanEqD
1366+ | RangeDateGt GreaterThanD
1367+ | RangeDateGtLt GreaterThanD LessThanD
1368+ | RangeDateGteLte GreaterThanEqD LessThanEqD
1369+ | RangeDateGteLt GreaterThanEqD LessThanD
1370+ | RangeDateGtLte GreaterThanD LessThanEqD
1371+ | RangeDoubleLte LessThanEq
1372+ | RangeDoubleLt LessThan
1373+ | RangeDoubleGte GreaterThanEq
1374+ | RangeDoubleGt GreaterThan
1375+ | RangeDoubleGtLt GreaterThan LessThan
1376+ | RangeDoubleGteLte GreaterThanEq LessThanEq
1377+ | RangeDoubleGteLt GreaterThanEq LessThan
1378+ | RangeDoubleGtLte GreaterThan LessThanEq
1379+ deriving (Eq, Show, Generic, Typeable)
1381+rangeValueToPair :: RangeValue -> [Pair]
1382+rangeValueToPair rv = case rv of
1383+ RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1384+ RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1385+ RangeDateLt (LessThanD t) -> ["lt" .= t]
1386+ RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1387+ RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1388+ RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1389+ RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1390+ RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1391+ RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1392+ RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1393+ RangeDoubleLt (LessThan t) -> ["lt" .= t]
1394+ RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1395+ RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1396+ RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1397+ RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1398+ RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1400+data Term = Term { termField :: Text
1401+ , termValue :: Text } deriving (Eq, Show, Generic, Typeable)
1403+data BoolMatch = MustMatch Term Cache
1404+ | MustNotMatch Term Cache
1405+ | ShouldMatch [Term] Cache deriving (Eq, Show, Generic, Typeable)
1407+-- "memory" or "indexed"
1408+data GeoFilterType = GeoFilterMemory
1409+ | GeoFilterIndexed deriving (Eq, Show, Generic, Typeable)
1411+data LatLon = LatLon { lat :: Double
1412+ , lon :: Double } deriving (Eq, Show, Generic, Typeable)
1414+data GeoBoundingBox =
1415+ GeoBoundingBox { topLeft :: LatLon
1416+ , bottomRight :: LatLon } deriving (Eq, Show, Generic, Typeable)
1418+data GeoBoundingBoxConstraint =
1419+ GeoBoundingBoxConstraint { geoBBField :: FieldName
1420+ , constraintBox :: GeoBoundingBox
1421+ , bbConstraintcache :: Cache
1422+ , geoType :: GeoFilterType
1423+ } deriving (Eq, Show, Generic, Typeable)
1426+ GeoPoint { geoField :: FieldName
1427+ , latLon :: LatLon} deriving (Eq, Show, Generic, Typeable)
1429+data DistanceUnit = Miles
1437+ | NauticalMiles deriving (Eq, Show, Generic, Typeable)
1439+data DistanceType = Arc
1440+ | SloppyArc -- doesn't exist <1.0
1441+ | Plane deriving (Eq, Show, Generic, Typeable)
1443+data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1444+ | NoOptimizeBbox deriving (Eq, Show, Generic, Typeable)
1447+ Distance { coefficient :: Double
1448+ , unit :: DistanceUnit } deriving (Eq, Show, Generic, Typeable)
1450+data DistanceRange =
1451+ DistanceRange { distanceFrom :: Distance
1452+ , distanceTo :: Distance } deriving (Eq, Show, Generic, Typeable)
516data SearchResult a =
1454data SearchResult a =
517 SearchResult { took :: Int
1455 SearchResult { took :: Int
@@ -519,24 +1457,2091 @@ data SearchResult a =
519 , shards :: ShardResult
1457 , shards :: ShardResult
520 , searchHits :: SearchHits a
1458 , searchHits :: SearchHits a
521 , aggregations :: Maybe AggregationResults
1459 , aggregations :: Maybe AggregationResults
522− , scrollId :: Maybe ScrollId
1460+ , scrollId :: Maybe ScrollId } deriving (Eq, Show, Generic, Typeable)
523− -- ^ Only one Suggestion request / response per
524− -- Search is supported.
525− , suggest :: Maybe NamedSuggestionResponse
529−instance (FromJSON a) => FromJSON (SearchResult a) where
1462+newtype ScrollId = ScrollId Text deriving (Eq, Show, Generic, Ord, ToJSON, FromJSON)
530− parseJSON (Object v) = SearchResult <$>
1463+
531− v .: "took" <*>
1464+type Score = Maybe Double
532− v .: "timed_out" <*>
1465+
533− v .: "_shards" <*>
1466+data SearchHits a =
534− v .: "hits" <*>
1467+ SearchHits { hitsTotal :: Int
535− v .:? "aggregations" <*>
1468+ , maxScore :: Score
536− v .:? "_scroll_id" <*>
1469+ , hits :: [Hit a] } deriving (Eq, Show, Generic, Typeable)
537− v .:? "suggest"
1470+
538− parseJSON _ = empty
1471+
1472+instance Monoid (SearchHits a) where
1473+ mempty = SearchHits 0 Nothing mempty
1474+ mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1475+ SearchHits (ta + tb) (max ma mb) (ha <> hb)
1479+ Hit { hitIndex :: IndexName
1480+ , hitType :: MappingName
1481+ , hitDocId :: DocId
1482+ , hitScore :: Score
1483+ , hitSource :: Maybe a
1484+ , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show, Generic, Typeable)
1487+ ShardResult { shardTotal :: Int
1488+ , shardsSuccessful :: Int
1489+ , shardsFailed :: Int } deriving (Eq, Show, Generic, Typeable)
1491+type HitHighlight = M.Map Text [Text]
1493+showText :: Show a => a -> Text
1494+showText = T.pack . show
1496+readMay :: Read a => String -> Maybe a
1497+readMay s = case reads s of
1498+ (a, ""):_ -> Just a
1501+parseReadText :: Read a => Text -> Parser a
1502+parseReadText = maybe mzero return . readMay . T.unpack
1504+type Aggregations = M.Map Text Aggregation
1506+emptyAggregations :: Aggregations
1507+emptyAggregations = M.empty
1509+mkAggregations :: Text -> Aggregation -> Aggregations
1510+mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1512+data TermOrder = TermOrder{ termSortField :: Text
1513+ , termSortOrder :: SortOrder } deriving (Eq, Show, Generic, Typeable)
1515+data TermInclusion = TermInclusion Text
1516+ | TermPattern Text Text deriving (Eq, Show, Generic, Typeable)
1518+data CollectionMode = BreadthFirst
1519+ | DepthFirst deriving (Eq, Show, Generic, Typeable)
1521+data ExecutionHint = Ordinals
1523+ | GlobalOrdinalsHash
1524+ | GlobalOrdinalsLowCardinality
1525+ | Map deriving (Eq, Show, Generic, Typeable)
1527+data TimeInterval = Weeks
1531+ | Seconds deriving (Eq)
1533+data Interval = Year
1541+ | FractionalInterval Float TimeInterval deriving (Eq, Show, Generic, Typeable)
1543+data Aggregation = TermsAgg TermsAggregation
1544+ | DateHistogramAgg DateHistogramAggregation
1545+ | ValueCountAgg ValueCountAggregation
1546+ | FilterAgg FilterAggregation
1547+ | DateRangeAgg DateRangeAggregation deriving (Eq, Show, Generic, Typeable)
1550+data TermsAggregation = TermsAggregation { term :: Either Text Text
1551+ , termInclude :: Maybe TermInclusion
1552+ , termExclude :: Maybe TermInclusion
1553+ , termOrder :: Maybe TermOrder
1554+ , termMinDocCount :: Maybe Int
1555+ , termSize :: Maybe Int
1556+ , termShardSize :: Maybe Int
1557+ , termCollectMode :: Maybe CollectionMode
1558+ , termExecutionHint :: Maybe ExecutionHint
1559+ , termAggs :: Maybe Aggregations
1560+ } deriving (Eq, Show, Generic, Typeable)
1562+data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1563+ , dateInterval :: Interval
1564+ , dateFormat :: Maybe Text
1565+ -- pre and post deprecated in 1.5
1566+ , datePreZone :: Maybe Text
1567+ , datePostZone :: Maybe Text
1568+ , datePreOffset :: Maybe Text
1569+ , datePostOffset :: Maybe Text
1570+ , dateAggs :: Maybe Aggregations
1571+ } deriving (Eq, Show, Generic, Typeable)
1574+data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1575+ , draFormat :: Maybe Text
1576+ , draRanges :: NonEmpty DateRangeAggRange
1577+ } deriving (Eq, Show, Generic, Typeable)
1579+data DateRangeAggRange = DateRangeFrom DateMathExpr
1580+ | DateRangeTo DateMathExpr
1581+ | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Show, Generic, Typeable)
1583+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1584+data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Show, Generic, Typeable)
1587+-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1588+data DateMathAnchor = DMNow
1589+ | DMDate Day deriving (Eq, Show, Generic, Typeable)
1591+data DateMathModifier = AddTime Int DateMathUnit
1592+ | SubtractTime Int DateMathUnit
1593+ | RoundDownTo DateMathUnit deriving (Eq, Show, Generic, Typeable)
1595+data DateMathUnit = DMYear
1601+ | DMSecond deriving (Eq, Show, Generic, Typeable)
1603+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1604+data ValueCountAggregation = FieldValueCount FieldName
1605+ | ScriptValueCount Script deriving (Eq, Show, Generic, Typeable)
1607+-- | 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.
1608+data FilterAggregation = FilterAggregation { faFilter :: Filter
1609+ , faAggs :: Maybe Aggregations} deriving (Eq, Show, Generic, Typeable)
1611+mkTermsAggregation :: Text -> TermsAggregation
1612+mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1614+mkTermsScriptAggregation :: Text -> TermsAggregation
1615+mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1617+mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1618+mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1620+instance ToJSON Version where
1621+ toJSON Version {..} = object ["number" .= number
1622+ ,"build_hash" .= build_hash
1623+ ,"build_timestamp" .= build_timestamp
1624+ ,"build_snapshot" .= build_snapshot
1625+ ,"lucene_version" .= lucene_version]
1627+instance FromJSON Version where
1628+ parseJSON = withObject "Version" parse
1629+ where parse o = Version
1631+ <*> o .: "build_hash"
1632+ <*> o .: "build_timestamp"
1633+ <*> o .: "build_snapshot"
1634+ <*> o .: "lucene_version"
1636+instance ToJSON TermOrder where
1637+ toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1639+instance ToJSON TermInclusion where
1640+ toJSON (TermInclusion x) = toJSON x
1641+ toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1644+instance ToJSON CollectionMode where
1645+ toJSON BreadthFirst = "breadth_first"
1646+ toJSON DepthFirst = "depth_first"
1648+instance ToJSON ExecutionHint where
1649+ toJSON Ordinals = "ordinals"
1650+ toJSON GlobalOrdinals = "global_ordinals"
1651+ toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1652+ toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1655+instance ToJSON Interval where
1656+ toJSON Year = "year"
1657+ toJSON Quarter = "quarter"
1658+ toJSON Month = "month"
1659+ toJSON Week = "week"
1661+ toJSON Hour = "hour"
1662+ toJSON Minute = "minute"
1663+ toJSON Second = "second"
1664+ toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1666+instance Show TimeInterval where
1673+instance ToJSON Aggregation where
1674+ toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1675+ omitNulls ["terms" .= omitNulls [ toJSON' term,
1676+ "include" .= include,
1677+ "exclude" .= exclude,
1679+ "min_doc_count" .= minDocCount,
1681+ "shard_size" .= shardSize,
1682+ "collect_mode" .= collectMode,
1683+ "execution_hint" .= executionHint
1685+ "aggs" .= termAggs ]
1687+ toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1689+ toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1690+ omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1691+ "interval" .= interval,
1692+ "format" .= format,
1693+ "pre_zone" .= preZone,
1694+ "post_zone" .= postZone,
1695+ "pre_offset" .= preOffset,
1696+ "post_offset" .= postOffset
1698+ "aggs" .= dateHistoAggs ]
1699+ toJSON (ValueCountAgg a) = object ["value_count" .= v]
1700+ where v = case a of
1701+ (FieldValueCount (FieldName n)) -> object ["field" .= n]
1702+ (ScriptValueCount (Script s)) -> object ["script" .= s]
1703+ toJSON (FilterAgg (FilterAggregation filt ags)) =
1704+ omitNulls [ "filter" .= filt
1706+ toJSON (DateRangeAgg a) = object [ "date_range" .= a
1709+instance ToJSON DateRangeAggregation where
1710+ toJSON DateRangeAggregation {..} =
1711+ omitNulls [ "field" .= draField
1712+ , "format" .= draFormat
1713+ , "ranges" .= toList draRanges
1716+instance ToJSON DateRangeAggRange where
1717+ toJSON (DateRangeFrom e) = object [ "from" .= e ]
1718+ toJSON (DateRangeTo e) = object [ "to" .= e ]
1719+ toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1721+instance ToJSON DateMathExpr where
1722+ toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1723+ where fmtA DMNow = "now"
1724+ fmtA (DMDate date) = case toGregorian date of
1725+ (y,m,d) -> showText y <> "-" <>
1726+ showText m <> "-" <>
1728+ fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1729+ fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1730+ fmtMod (RoundDownTo u) = "/" <> fmtU u
1736+ fmtU DMMinute = "m"
1737+ fmtU DMSecond = "s"
1740+type AggregationResults = M.Map Text Value
1742+class BucketAggregation a where
1744+ docCount :: a -> Int
1745+ aggs :: a -> Maybe AggregationResults
1748+data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1750+data TermsResult = TermsResult { termKey :: Text
1751+ , termsDocCount :: Int
1752+ , termsAggs :: Maybe AggregationResults } deriving (Show)
1754+data DateHistogramResult = DateHistogramResult { dateKey :: Int
1755+ , dateKeyStr :: Maybe Text
1756+ , dateDocCount :: Int
1757+ , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1759+data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1760+ , dateRangeFrom :: Maybe UTCTime
1761+ , dateRangeFromAsString :: Maybe Text
1762+ , dateRangeTo :: Maybe UTCTime
1763+ , dateRangeToAsString :: Maybe Text
1764+ , dateRangeDocCount :: Int
1765+ , dateRangeAggs :: Maybe AggregationResults } deriving (Show, Eq, Generic, Typeable)
1767+toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1768+toTerms t a = M.lookup t a >>= deserialize
1769+ where deserialize = parseMaybe parseJSON
1771+toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1772+toDateHistogram t a = M.lookup t a >>= deserialize
1773+ where deserialize = parseMaybe parseJSON
1775+instance BucketAggregation TermsResult where
1777+ docCount = termsDocCount
1780+instance BucketAggregation DateHistogramResult where
1781+ key = showText . dateKey
1782+ docCount = dateDocCount
1783+ aggs = dateHistogramAggs
1785+instance BucketAggregation DateRangeResult where
1787+ docCount = dateRangeDocCount
1788+ aggs = dateRangeAggs
1790+instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1791+ parseJSON (Object v) = Bucket <$>
1793+ parseJSON _ = mempty
1795+instance FromJSON TermsResult where
1796+ parseJSON (Object v) = TermsResult <$>
1798+ v .: "doc_count" <*>
1799+ v .:? "aggregations"
1800+ parseJSON _ = mempty
1802+instance FromJSON DateHistogramResult where
1803+ parseJSON (Object v) = DateHistogramResult <$>
1805+ v .:? "key_as_string" <*>
1806+ v .: "doc_count" <*>
1807+ v .:? "aggregations"
1808+ parseJSON _ = mempty
1810+instance FromJSON DateRangeResult where
1811+ parseJSON = withObject "DateRangeResult" parse
1812+ where parse v = DateRangeResult <$>
1814+ (fmap posixMS <$> v .:? "from") <*>
1815+ v .:? "from_as_string" <*>
1816+ (fmap posixMS <$> v .:? "to") <*>
1817+ v .:? "to_as_string" <*>
1818+ v .: "doc_count" <*>
1819+ v .:? "aggregations"
1821+instance FromJSON POSIXMS where
1822+ parseJSON = withScientific "POSIXMS" (return . parse)
1823+ where parse n = let n' = truncate n :: Integer
1824+ in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1826+instance Monoid Filter where
1827+ mempty = IdentityFilter
1828+ mappend a b = AndFilter [a, b] defaultCache
1830+instance Seminearring Filter where
1831+ a <||> b = OrFilter [a, b] defaultCache
1833+instance ToJSON Filter where
1834+ toJSON (AndFilter filters cache) =
1836+ object [ "filters" .= fmap toJSON filters
1837+ , "_cache" .= cache]]
1839+ toJSON (OrFilter filters cache) =
1841+ object [ "filters" .= fmap toJSON filters
1842+ , "_cache" .= cache]]
1844+ toJSON (NotFilter notFilter cache) =
1846+ object ["filter" .= notFilter
1847+ , "_cache" .= cache]]
1849+ toJSON (IdentityFilter) =
1850+ object ["match_all" .= object []]
1852+ toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1853+ object ["term" .= object base]
1854+ where base = [termFilterField .= termFilterValue,
1857+ toJSON (ExistsFilter (FieldName fieldName)) =
1858+ object ["exists" .= object
1859+ ["field" .= fieldName]]
1861+ toJSON (BoolFilter boolMatch) =
1862+ object ["bool" .= boolMatch]
1864+ toJSON (GeoBoundingBoxFilter bbConstraint) =
1865+ object ["geo_bounding_box" .= bbConstraint]
1867+ toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1868+ distance distanceType optimizeBbox cache) =
1869+ object ["geo_distance" .=
1870+ object ["distance" .= distance
1871+ , "distance_type" .= distanceType
1872+ , "optimize_bbox" .= optimizeBbox
1873+ , distanceGeoField .= geoDistLatLon
1874+ , "_cache" .= cache]]
1876+ toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1877+ (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1878+ object ["geo_distance_range" .=
1879+ object ["from" .= geoDistRangeDistFrom
1880+ , "to" .= drDistanceTo
1881+ , gddrField .= drLatLon]]
1883+ toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1884+ object ["geo_polygon" .=
1885+ object [geoPolygonFilterField .=
1886+ object ["points" .= fmap toJSON latLons]]]
1888+ toJSON (IdsFilter (MappingName mappingName) values) =
1890+ object ["type" .= mappingName
1891+ , "values" .= fmap unpackId values]]
1893+ toJSON (LimitFilter limit) =
1894+ object ["limit" .= object ["value" .= limit]]
1896+ toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1897+ object ["missing" .=
1898+ object ["field" .= fieldName
1899+ , "existence" .= existence
1900+ , "null_value" .= nullValue]]
1902+ toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1903+ object ["prefix" .=
1904+ object [fieldName .= fieldValue
1905+ , "_cache" .= cache]]
1907+ toJSON (QueryFilter query False) =
1908+ object ["query" .= toJSON query ]
1909+ toJSON (QueryFilter query True) =
1910+ object ["fquery" .=
1911+ object [ "query" .= toJSON query
1912+ , "_cache" .= True ]]
1914+ toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1916+ object [ fieldName .= object (rangeValueToPair rangeValue)
1917+ , "execution" .= rangeExecution
1918+ , "_cache" .= cache]]
1920+ toJSON (RegexpFilter (FieldName fieldName)
1921+ (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1922+ object ["regexp" .=
1923+ object [fieldName .=
1924+ object ["value" .= regexText
1925+ , "flags" .= flags]
1926+ , "_name" .= cacheName
1927+ , "_cache" .= cache
1928+ , "_cache_key" .= cacheKey]]
1930+instance FromJSON Filter where
1931+ parseJSON = withObject "Filter" parse
1932+ where parse o = andFilter `taggedWith` "and"
1933+ <|> orFilter `taggedWith` "or"
1934+ <|> notFilter `taggedWith` "not"
1935+ <|> identityFilter `taggedWith` "match_all"
1936+ <|> boolFilter `taggedWith` "bool"
1937+ <|> existsFilter `taggedWith` "exists"
1938+ <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
1939+ <|> geoDistanceFilter `taggedWith` "geo_distance"
1940+ <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
1941+ <|> geoPolygonFilter `taggedWith` "geo_polygon"
1942+ <|> idsFilter `taggedWith` "ids"
1943+ <|> limitFilter `taggedWith` "limit"
1944+ <|> missingFilter `taggedWith` "missing"
1945+ <|> prefixFilter `taggedWith` "prefix"
1946+ <|> queryFilter `taggedWith` "query"
1947+ <|> fqueryFilter `taggedWith` "fquery"
1948+ <|> rangeFilter `taggedWith` "range"
1949+ <|> regexpFilter `taggedWith` "regexp"
1950+ <|> termFilter `taggedWith` "term"
1951+ where taggedWith parser k = parser =<< o .: k
1952+ andFilter o = AndFilter <$> o .: "filters"
1953+ <*> o .:? "_cache" .!= defaultCache
1954+ orFilter o = OrFilter <$> o .: "filters"
1955+ <*> o .:? "_cache" .!= defaultCache
1956+ notFilter o = NotFilter <$> o .: "filter"
1957+ <*> o .: "_cache" .!= defaultCache
1958+ identityFilter :: Object -> Parser Filter
1960+ | HM.null m = pure IdentityFilter
1961+ | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
1962+ boolFilter = pure . BoolFilter
1963+ existsFilter o = ExistsFilter <$> o .: "field"
1964+ geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1965+ geoDistanceFilter o = do
1966+ case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
1968+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
1969+ GeoDistanceFilter gp <$> o .: "distance"
1970+ <*> o .: "distance_type"
1971+ <*> o .: "optimize_bbox"
1972+ <*> o .:? "_cache" .!= defaultCache
1973+ _ -> fail "Could not find GeoDistanceFilter field name"
1974+ geoDistanceRangeFilter o = do
1975+ case HM.toList (deleteSeveral ["from", "to"] o) of
1977+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
1978+ rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1979+ return (GeoDistanceRangeFilter gp rng)
1980+ _ -> fail "Could not find GeoDistanceRangeFilter field name"
1981+ geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
1982+ idsFilter o = IdsFilter <$> o .: "type"
1984+ limitFilter o = LimitFilter <$> o .: "value"
1985+ missingFilter o = MissingFilter <$> o .: "field"
1986+ <*> o .: "existence"
1987+ <*> o .: "null_value"
1988+ prefixFilter o = case HM.toList (HM.delete "_cache" o) of
1989+ [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
1990+ _ -> fail "Could not parse PrefixFilter"
1992+ queryFilter q = pure (QueryFilter q False)
1993+ fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
1994+ rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
1995+ [(fn, v)] -> RangeFilter (FieldName fn)
1997+ <*> o .: "execution"
1998+ <*> o .:? "_cache" .!= defaultCache
1999+ _ -> fail "Could not find field name for RangeFilter"
2000+ regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2001+ [(fn, Object o')] -> RegexpFilter (FieldName fn)
2005+ <*> o .:? "_cache" .!= defaultCache
2006+ <*> o .: "_cache_key"
2007+ _ -> fail "Could not find field name for RegexpFilter"
2008+ termFilter o = case HM.toList (HM.delete "_cache" o) of
2009+ [(termField, String termVal)] -> TermFilter (Term termField termVal)
2010+ <$> o .:? "_cache" .!= defaultCache
2011+ _ -> fail "Could not find term field for TermFilter"
2013+fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2014+fieldTagged f o = case HM.toList o of
2015+ [(k, Object o')] -> f (FieldName k) o'
2016+ _ -> fail "Expected object with 1 field-named key"
2018+instance ToJSON GeoPoint where
2019+ toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2020+ object [ geoPointField .= geoPointLatLon ]
2023+instance ToJSON Query where
2024+ toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2026+ object [termQueryField .= object merged]]
2028+ base = [ "value" .= termQueryValue ]
2029+ boosted = maybe [] (return . ("boost" .=)) boost
2030+ merged = mappend base boosted
2032+ toJSON (TermsQuery fieldName terms) =
2033+ object [ "terms" .= object conjoined ]
2034+ where conjoined = [fieldName .= terms]
2035+ toJSON (IdsQuery idsQueryMappingName docIds) =
2036+ object [ "ids" .= object conjoined ]
2037+ where conjoined = [ "type" .= idsQueryMappingName
2038+ , "values" .= fmap toJSON docIds ]
2040+ toJSON (QueryQueryStringQuery qQueryStringQuery) =
2041+ object [ "query_string" .= qQueryStringQuery ]
2043+ toJSON (QueryMatchQuery matchQuery) =
2044+ object [ "match" .= matchQuery ]
2046+ toJSON (QueryMultiMatchQuery multiMatchQuery) =
2047+ toJSON multiMatchQuery
2049+ toJSON (QueryBoolQuery boolQuery) =
2050+ object [ "bool" .= boolQuery ]
2052+ toJSON (QueryBoostingQuery boostingQuery) =
2053+ object [ "boosting" .= boostingQuery ]
2055+ toJSON (QueryCommonTermsQuery commonTermsQuery) =
2056+ object [ "common" .= commonTermsQuery ]
2058+ toJSON (ConstantScoreFilter csFilter boost) =
2059+ object ["constant_score" .= object ["filter" .= csFilter
2060+ , "boost" .= boost]]
2062+ toJSON (ConstantScoreQuery query boost) =
2063+ object ["constant_score" .= object ["query" .= query
2064+ , "boost" .= boost]]
2066+ toJSON (QueryDisMaxQuery disMaxQuery) =
2067+ object [ "dis_max" .= disMaxQuery ]
2069+ toJSON (QueryFilteredQuery qFilteredQuery) =
2070+ object [ "filtered" .= qFilteredQuery ]
2072+ toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2073+ object [ "fuzzy_like_this" .= fuzzyQuery ]
2075+ toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2076+ object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2078+ toJSON (QueryFuzzyQuery fuzzyQuery) =
2079+ object [ "fuzzy" .= fuzzyQuery ]
2081+ toJSON (QueryHasChildQuery childQuery) =
2082+ object [ "has_child" .= childQuery ]
2084+ toJSON (QueryHasParentQuery parentQuery) =
2085+ object [ "has_parent" .= parentQuery ]
2087+ toJSON (QueryIndicesQuery qIndicesQuery) =
2088+ object [ "indices" .= qIndicesQuery ]
2090+ toJSON (MatchAllQuery boost) =
2091+ object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2093+ toJSON (QueryMoreLikeThisQuery query) =
2094+ object [ "more_like_this" .= query ]
2096+ toJSON (QueryMoreLikeThisFieldQuery query) =
2097+ object [ "more_like_this_field" .= query ]
2099+ toJSON (QueryNestedQuery query) =
2100+ object [ "nested" .= query ]
2102+ toJSON (QueryPrefixQuery query) =
2103+ object [ "prefix" .= query ]
2105+ toJSON (QueryRangeQuery query) =
2106+ object [ "range" .= query ]
2108+ toJSON (QueryRegexpQuery query) =
2109+ object [ "regexp" .= query ]
2111+ toJSON (QuerySimpleQueryStringQuery query) =
2112+ object [ "simple_query_string" .= query ]
2114+instance FromJSON Query where
2115+ parseJSON v = withObject "Query" parse v
2116+ where parse o = termQuery `taggedWith` "term"
2117+ <|> termsQuery `taggedWith` "terms"
2118+ <|> idsQuery `taggedWith` "ids"
2119+ <|> queryQueryStringQuery `taggedWith` "query_string"
2120+ <|> queryMatchQuery `taggedWith` "match"
2121+ <|> queryMultiMatchQuery
2122+ <|> queryBoolQuery `taggedWith` "bool"
2123+ <|> queryBoostingQuery `taggedWith` "boosting"
2124+ <|> queryCommonTermsQuery `taggedWith` "common"
2125+ <|> constantScoreFilter `taggedWith` "constant_score"
2126+ <|> constantScoreQuery `taggedWith` "constant_score"
2127+ <|> queryDisMaxQuery `taggedWith` "dis_max"
2128+ <|> queryFilteredQuery `taggedWith` "filtered"
2129+ <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2130+ <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2131+ <|> queryFuzzyQuery `taggedWith` "fuzzy"
2132+ <|> queryHasChildQuery `taggedWith` "has_child"
2133+ <|> queryHasParentQuery `taggedWith` "has_parent"
2134+ <|> queryIndicesQuery `taggedWith` "indices"
2135+ <|> matchAllQuery `taggedWith` "match_all"
2136+ <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2137+ <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2138+ <|> queryNestedQuery `taggedWith` "nested"
2139+ <|> queryPrefixQuery `taggedWith` "prefix"
2140+ <|> queryRangeQuery `taggedWith` "range"
2141+ <|> queryRegexpQuery `taggedWith` "regexp"
2142+ <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2143+ where taggedWith parser k = parser =<< o .: k
2144+ termQuery = fieldTagged $ \(FieldName fn) o ->
2145+ TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2146+ termsQuery o = case HM.toList o of
2147+ [(fn, vs)] -> do vals <- parseJSON vs
2149+ x:xs -> return (TermsQuery fn (x :| xs))
2150+ _ -> fail "Expected non empty list of values"
2151+ _ -> fail "Expected object with 1 field-named key"
2152+ idsQuery o = IdsQuery <$> o .: "type"
2154+ queryQueryStringQuery = pure . QueryQueryStringQuery
2155+ queryMatchQuery = pure . QueryMatchQuery
2156+ queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2157+ queryBoolQuery = pure . QueryBoolQuery
2158+ queryBoostingQuery = pure . QueryBoostingQuery
2159+ queryCommonTermsQuery = pure . QueryCommonTermsQuery
2160+ constantScoreFilter o = case HM.lookup "filter" o of
2161+ Just x -> ConstantScoreFilter <$> parseJSON x
2163+ _ -> fail "Does not appear to be a ConstantScoreFilter"
2164+ constantScoreQuery o = case HM.lookup "query" o of
2165+ Just x -> ConstantScoreQuery <$> parseJSON x
2167+ _ -> fail "Does not appear to be a ConstantScoreQuery"
2168+ queryDisMaxQuery = pure . QueryDisMaxQuery
2169+ queryFilteredQuery = pure . QueryFilteredQuery
2170+ queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2171+ queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2172+ queryFuzzyQuery = pure . QueryFuzzyQuery
2173+ queryHasChildQuery = pure . QueryHasChildQuery
2174+ queryHasParentQuery = pure . QueryHasParentQuery
2175+ queryIndicesQuery = pure . QueryIndicesQuery
2176+ matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2177+ queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2178+ queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2179+ queryNestedQuery = pure . QueryNestedQuery
2180+ queryPrefixQuery = pure . QueryPrefixQuery
2181+ queryRangeQuery = pure . QueryRangeQuery
2182+ queryRegexpQuery = pure . QueryRegexpQuery
2183+ querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2186+omitNulls :: [(Text, Value)] -> Value
2187+omitNulls = object . filter notNull where
2188+ notNull (_, Null) = False
2189+ notNull (_, Array a) = (not . V.null) a
2193+instance ToJSON SimpleQueryStringQuery where
2194+ toJSON SimpleQueryStringQuery {..} =
2195+ omitNulls (base ++ maybeAdd)
2196+ where base = [ "query" .= simpleQueryStringQuery ]
2197+ maybeAdd = [ "fields" .= simpleQueryStringField
2198+ , "default_operator" .= simpleQueryStringOperator
2199+ , "analyzer" .= simpleQueryStringAnalyzer
2200+ , "flags" .= simpleQueryStringFlags
2201+ , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2202+ , "locale" .= simpleQueryStringLocale ]
2204+instance FromJSON SimpleQueryStringQuery where
2205+ parseJSON = withObject "SimpleQueryStringQuery" parse
2206+ where parse o = SimpleQueryStringQuery <$> o .: "query"
2208+ <*> o .:? "default_operator"
2209+ <*> o .:? "analyzer"
2210+ <*> (parseFlags <$> o .:? "flags")
2211+ <*> o .:? "lowercase_expanded_terms"
2213+ parseFlags (Just (x:xs)) = Just (x :| xs)
2214+ parseFlags _ = Nothing
2216+instance ToJSON FieldOrFields where
2217+ toJSON (FofField fieldName) =
2219+ toJSON (FofFields fieldNames) =
2222+instance FromJSON FieldOrFields where
2223+ parseJSON v = FofField <$> parseJSON v
2224+ <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2226+instance ToJSON SimpleQueryFlag where
2227+ toJSON SimpleQueryAll = "ALL"
2228+ toJSON SimpleQueryNone = "NONE"
2229+ toJSON SimpleQueryAnd = "AND"
2230+ toJSON SimpleQueryOr = "OR"
2231+ toJSON SimpleQueryPrefix = "PREFIX"
2232+ toJSON SimpleQueryPhrase = "PHRASE"
2233+ toJSON SimpleQueryPrecedence = "PRECEDENCE"
2234+ toJSON SimpleQueryEscape = "ESCAPE"
2235+ toJSON SimpleQueryWhitespace = "WHITESPACE"
2236+ toJSON SimpleQueryFuzzy = "FUZZY"
2237+ toJSON SimpleQueryNear = "NEAR"
2238+ toJSON SimpleQuerySlop = "SLOP"
2240+instance FromJSON SimpleQueryFlag where
2241+ parseJSON = withText "SimpleQueryFlag" parse
2242+ where parse "ALL" = pure SimpleQueryAll
2243+ parse "NONE" = pure SimpleQueryNone
2244+ parse "AND" = pure SimpleQueryAnd
2245+ parse "OR" = pure SimpleQueryOr
2246+ parse "PREFIX" = pure SimpleQueryPrefix
2247+ parse "PHRASE" = pure SimpleQueryPhrase
2248+ parse "PRECEDENCE" = pure SimpleQueryPrecedence
2249+ parse "ESCAPE" = pure SimpleQueryEscape
2250+ parse "WHITESPACE" = pure SimpleQueryWhitespace
2251+ parse "FUZZY" = pure SimpleQueryFuzzy
2252+ parse "NEAR" = pure SimpleQueryNear
2253+ parse "SLOP" = pure SimpleQuerySlop
2254+ parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2256+instance ToJSON RegexpQuery where
2257+ toJSON (RegexpQuery (FieldName rqQueryField)
2258+ (Regexp regexpQueryQuery) rqQueryFlags
2260+ object [ rqQueryField .= omitNulls base ]
2261+ where base = [ "value" .= regexpQueryQuery
2262+ , "flags" .= rqQueryFlags
2263+ , "boost" .= rqQueryBoost ]
2265+instance FromJSON RegexpQuery where
2266+ parseJSON = withObject "RegexpQuery" parse
2267+ where parse = fieldTagged $ \fn o ->
2273+instance ToJSON QueryStringQuery where
2274+ toJSON (QueryStringQuery qsQueryString
2275+ qsDefaultField qsOperator
2276+ qsAnalyzer qsAllowWildcard
2277+ qsLowercaseExpanded qsEnablePositionIncrements
2278+ qsFuzzyMaxExpansions qsFuzziness
2279+ qsFuzzyPrefixLength qsPhraseSlop
2280+ qsBoost qsAnalyzeWildcard
2281+ qsGeneratePhraseQueries qsMinimumShouldMatch
2282+ qsLenient qsLocale) =
2285+ base = [ "query" .= qsQueryString
2286+ , "default_field" .= qsDefaultField
2287+ , "default_operator" .= qsOperator
2288+ , "analyzer" .= qsAnalyzer
2289+ , "allow_leading_wildcard" .= qsAllowWildcard
2290+ , "lowercase_expanded_terms" .= qsLowercaseExpanded
2291+ , "enable_position_increments" .= qsEnablePositionIncrements
2292+ , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2293+ , "fuzziness" .= qsFuzziness
2294+ , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2295+ , "phrase_slop" .= qsPhraseSlop
2296+ , "boost" .= qsBoost
2297+ , "analyze_wildcard" .= qsAnalyzeWildcard
2298+ , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2299+ , "minimum_should_match" .= qsMinimumShouldMatch
2300+ , "lenient" .= qsLenient
2301+ , "locale" .= qsLocale ]
2303+instance FromJSON QueryStringQuery where
2304+ parseJSON = withObject "QueryStringQuery" parse
2305+ where parse o = QueryStringQuery
2307+ <*> o .:? "default_field"
2308+ <*> o .:? "default_operator"
2309+ <*> o .:? "analyzer"
2310+ <*> o .:? "allow_leading_wildcard"
2311+ <*> o .:? "lowercase_expanded_terms"
2312+ <*> o .:? "enable_position_increments"
2313+ <*> o .:? "fuzzy_max_expansions"
2314+ <*> o .:? "fuzziness"
2315+ <*> o .:? "fuzzy_prefix_length"
2316+ <*> o .:? "phrase_slop"
2318+ <*> o .:? "analyze_wildcard"
2319+ <*> o .:? "auto_generate_phrase_queries"
2320+ <*> o .:? "minimum_should_match"
2321+ <*> o .:? "lenient"
2324+instance ToJSON RangeQuery where
2325+ toJSON (RangeQuery (FieldName fieldName) range boost) =
2326+ object [ fieldName .= object conjoined ]
2327+ where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2329+instance FromJSON RangeQuery where
2330+ parseJSON = withObject "RangeQuery" parse
2331+ where parse = fieldTagged $ \fn o ->
2333+ <$> parseJSON (Object o)
2336+instance FromJSON RangeValue where
2337+ parseJSON = withObject "RangeValue" parse
2338+ where parse o = parseDate o
2340+ parseDate o = do lt <- o .:? "lt"
2344+ case (lt, lte, gt, gte) of
2345+ (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2346+ (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2347+ (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2348+ (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2349+ (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2350+ (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2351+ (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2352+ (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2353+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2354+ parseDouble o = do lt <- o .:? "lt"
2358+ case (lt, lte, gt, gte) of
2359+ (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2360+ (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2361+ (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2362+ (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2363+ (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2364+ (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2365+ (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2366+ (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2367+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2369+instance ToJSON PrefixQuery where
2370+ toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2371+ object [ fieldName .= omitNulls base ]
2372+ where base = [ "value" .= queryValue
2373+ , "boost" .= boost ]
2375+instance FromJSON PrefixQuery where
2376+ parseJSON = withObject "PrefixQuery" parse
2377+ where parse = fieldTagged $ \fn o ->
2382+instance ToJSON NestedQuery where
2383+ toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2384+ object [ "path" .= nqPath
2385+ , "score_mode" .= nqScoreType
2386+ , "query" .= nqQuery ]
2388+instance FromJSON NestedQuery where
2389+ parseJSON = withObject "NestedQuery" parse
2390+ where parse o = NestedQuery
2392+ <*> o .: "score_mode"
2395+instance ToJSON MoreLikeThisFieldQuery where
2396+ toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2397+ percent mtf mqt stopwords mindf maxdf
2398+ minwl maxwl boostTerms boost analyzer) =
2399+ object [ fieldName .= omitNulls base ]
2400+ where base = [ "like_text" .= text
2401+ , "percent_terms_to_match" .= percent
2402+ , "min_term_freq" .= mtf
2403+ , "max_query_terms" .= mqt
2404+ , "stop_words" .= stopwords
2405+ , "min_doc_freq" .= mindf
2406+ , "max_doc_freq" .= maxdf
2407+ , "min_word_length" .= minwl
2408+ , "max_word_length" .= maxwl
2409+ , "boost_terms" .= boostTerms
2411+ , "analyzer" .= analyzer ]
2413+instance FromJSON MoreLikeThisFieldQuery where
2414+ parseJSON = withObject "MoreLikeThisFieldQuery" parse
2415+ where parse = fieldTagged $ \fn o ->
2416+ MoreLikeThisFieldQuery
2417+ <$> o .: "like_text"
2419+ <*> o .:? "percent_terms_to_match"
2420+ <*> o .:? "min_term_freq"
2421+ <*> o .:? "max_query_terms"
2422+ <*> (optionalNE =<< o .:? "stop_words")
2423+ <*> o .:? "min_doc_freq"
2424+ <*> o .:? "max_doc_freq"
2425+ <*> o .:? "min_word_length"
2426+ <*> o .:? "max_word_length"
2427+ <*> o .:? "boost_terms"
2429+ <*> o .:? "analyzer"
2430+ optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2432+instance ToJSON MoreLikeThisQuery where
2433+ toJSON (MoreLikeThisQuery text fields percent
2434+ mtf mqt stopwords mindf maxdf
2435+ minwl maxwl boostTerms boost analyzer) =
2437+ where base = [ "like_text" .= text
2438+ , "fields" .= fields
2439+ , "percent_terms_to_match" .= percent
2440+ , "min_term_freq" .= mtf
2441+ , "max_query_terms" .= mqt
2442+ , "stop_words" .= stopwords
2443+ , "min_doc_freq" .= mindf
2444+ , "max_doc_freq" .= maxdf
2445+ , "min_word_length" .= minwl
2446+ , "max_word_length" .= maxwl
2447+ , "boost_terms" .= boostTerms
2449+ , "analyzer" .= analyzer ]
2451+instance FromJSON MoreLikeThisQuery where
2452+ parseJSON = withObject "MoreLikeThisQuery" parse
2453+ where parse o = MoreLikeThisQuery
2454+ <$> o .: "like_text"
2455+ <*> (optionalNE =<< o .:? "fields")
2456+ <*> o .:? "percent_terms_to_match"
2457+ <*> o .:? "min_term_freq"
2458+ <*> o .:? "max_query_terms"
2459+ <*> (optionalNE =<< o .:? "stop_words")
2460+ <*> o .:? "min_doc_freq"
2461+ <*> o .:? "max_doc_freq"
2462+ <*> o .:? "min_word_length"
2463+ <*> o .:? "max_word_length"
2464+ <*> o .:? "boost_terms"
2466+ <*> o .:? "analyzer"
2467+ optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2469+instance ToJSON IndicesQuery where
2470+ toJSON (IndicesQuery indices query noMatch) =
2471+ omitNulls [ "indices" .= indices
2472+ , "no_match_query" .= noMatch
2473+ , "query" .= query ]
2475+instance FromJSON IndicesQuery where
2476+ parseJSON = withObject "IndicesQuery" parse
2477+ where parse o = IndicesQuery
2478+ <$> o .:? "indices" .!= []
2480+ <*> o .:? "no_match_query"
2482+instance ToJSON HasParentQuery where
2483+ toJSON (HasParentQuery queryType query scoreType) =
2484+ omitNulls [ "parent_type" .= queryType
2485+ , "score_type" .= scoreType
2486+ , "query" .= query ]
2488+instance FromJSON HasParentQuery where
2489+ parseJSON = withObject "HasParentQuery" parse
2490+ where parse o = HasParentQuery
2491+ <$> o .: "parent_type"
2493+ <*> o .:? "score_type"
2495+instance ToJSON HasChildQuery where
2496+ toJSON (HasChildQuery queryType query scoreType) =
2497+ omitNulls [ "query" .= query
2498+ , "score_type" .= scoreType
2499+ , "type" .= queryType ]
2501+instance FromJSON HasChildQuery where
2502+ parseJSON = withObject "HasChildQuery" parse
2503+ where parse o = HasChildQuery
2506+ <*> o .:? "score_type"
2508+instance ToJSON FuzzyQuery where
2509+ toJSON (FuzzyQuery (FieldName fieldName) queryText
2510+ prefixLength maxEx fuzziness boost) =
2511+ object [ fieldName .= omitNulls base ]
2512+ where base = [ "value" .= queryText
2513+ , "fuzziness" .= fuzziness
2514+ , "prefix_length" .= prefixLength
2516+ , "max_expansions" .= maxEx ]
2518+instance FromJSON FuzzyQuery where
2519+ parseJSON = withObject "FuzzyQuery" parse
2520+ where parse = fieldTagged $ \fn o ->
2523+ <*> o .: "prefix_length"
2524+ <*> o .: "max_expansions"
2525+ <*> o .: "fuzziness"
2528+instance ToJSON FuzzyLikeFieldQuery where
2529+ toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2530+ fieldText maxTerms ignoreFreq fuzziness prefixLength
2532+ object [ fieldName .=
2533+ omitNulls [ "like_text" .= fieldText
2534+ , "max_query_terms" .= maxTerms
2535+ , "ignore_tf" .= ignoreFreq
2536+ , "fuzziness" .= fuzziness
2537+ , "prefix_length" .= prefixLength
2538+ , "analyzer" .= analyzer
2539+ , "boost" .= boost ]]
2541+instance FromJSON FuzzyLikeFieldQuery where
2542+ parseJSON = withObject "FuzzyLikeFieldQuery" parse
2543+ where parse = fieldTagged $ \fn o ->
2544+ FuzzyLikeFieldQuery fn
2545+ <$> o .: "like_text"
2546+ <*> o .: "max_query_terms"
2547+ <*> o .: "ignore_tf"
2548+ <*> o .: "fuzziness"
2549+ <*> o .: "prefix_length"
2551+ <*> o .:? "analyzer"
2553+instance ToJSON FuzzyLikeThisQuery where
2554+ toJSON (FuzzyLikeThisQuery fields text maxTerms
2555+ ignoreFreq fuzziness prefixLength boost analyzer) =
2557+ where base = [ "fields" .= fields
2558+ , "like_text" .= text
2559+ , "max_query_terms" .= maxTerms
2560+ , "ignore_tf" .= ignoreFreq
2561+ , "fuzziness" .= fuzziness
2562+ , "prefix_length" .= prefixLength
2563+ , "analyzer" .= analyzer
2564+ , "boost" .= boost ]
2566+instance FromJSON FuzzyLikeThisQuery where
2567+ parseJSON = withObject "FuzzyLikeThisQuery" parse
2568+ where parse o = FuzzyLikeThisQuery
2569+ <$> o .:? "fields" .!= []
2570+ <*> o .: "like_text"
2571+ <*> o .: "max_query_terms"
2572+ <*> o .: "ignore_tf"
2573+ <*> o .: "fuzziness"
2574+ <*> o .: "prefix_length"
2576+ <*> o .:? "analyzer"
2578+instance ToJSON FilteredQuery where
2579+ toJSON (FilteredQuery query fFilter) =
2580+ object [ "query" .= query
2581+ , "filter" .= fFilter ]
2583+instance FromJSON FilteredQuery where
2584+ parseJSON = withObject "FilteredQuery" parse
2585+ where parse o = FilteredQuery
2589+instance ToJSON DisMaxQuery where
2590+ toJSON (DisMaxQuery queries tiebreaker boost) =
2592+ where base = [ "queries" .= queries
2594+ , "tie_breaker" .= tiebreaker ]
2596+instance FromJSON DisMaxQuery where
2597+ parseJSON = withObject "DisMaxQuery" parse
2598+ where parse o = DisMaxQuery
2599+ <$> o .:? "queries" .!= []
2600+ <*> o .: "tie_breaker"
2603+instance ToJSON CommonTermsQuery where
2604+ toJSON (CommonTermsQuery (FieldName fieldName)
2605+ (QueryString query) cf lfo hfo msm
2606+ boost analyzer disableCoord) =
2607+ object [fieldName .= omitNulls base ]
2608+ where base = [ "query" .= query
2609+ , "cutoff_frequency" .= cf
2610+ , "low_freq_operator" .= lfo
2611+ , "minimum_should_match" .= msm
2613+ , "analyzer" .= analyzer
2614+ , "disable_coord" .= disableCoord
2615+ , "high_freq_operator" .= hfo ]
2617+instance FromJSON CommonTermsQuery where
2618+ parseJSON = withObject "CommonTermsQuery" parse
2619+ where parse = fieldTagged $ \fn o ->
2620+ CommonTermsQuery fn
2622+ <*> o .: "cutoff_frequency"
2623+ <*> o .: "low_freq_operator"
2624+ <*> o .: "high_freq_operator"
2625+ <*> o .:? "minimum_should_match"
2627+ <*> o .:? "analyzer"
2628+ <*> o .:? "disable_coord"
2630+instance ToJSON CommonMinimumMatch where
2631+ toJSON (CommonMinimumMatch mm) = toJSON mm
2632+ toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2633+ object [ "low_freq" .= lowF
2634+ , "high_freq" .= highF ]
2636+instance FromJSON CommonMinimumMatch where
2637+ parseJSON v = parseMinimum v
2638+ <|> parseMinimumHighLow v
2639+ where parseMinimum = fmap CommonMinimumMatch . parseJSON
2640+ parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2641+ MinimumMatchHighLow
2642+ <$> o .: "low_freq"
2643+ <*> o .: "high_freq")
2646+instance ToJSON BoostingQuery where
2647+ toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2648+ object [ "positive" .= bqPositiveQuery
2649+ , "negative" .= bqNegativeQuery
2650+ , "negative_boost" .= bqNegativeBoost ]
2652+instance FromJSON BoostingQuery where
2653+ parseJSON = withObject "BoostingQuery" parse
2654+ where parse o = BoostingQuery
2655+ <$> o .: "positive"
2656+ <*> o .: "negative"
2657+ <*> o .: "negative_boost"
2659+instance ToJSON BoolQuery where
2660+ toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2662+ where base = [ "must" .= mustM
2663+ , "must_not" .= notM
2664+ , "should" .= shouldM
2665+ , "minimum_should_match" .= bqMin
2667+ , "disable_coord" .= disableCoord ]
2669+instance FromJSON BoolQuery where
2670+ parseJSON = withObject "BoolQuery" parse
2671+ where parse o = BoolQuery
2672+ <$> o .:? "must" .!= []
2673+ <*> o .:? "must_not" .!= []
2674+ <*> o .:? "should" .!= []
2675+ <*> o .:? "minimum_should_match"
2677+ <*> o .:? "disable_coord"
2679+instance ToJSON MatchQuery where
2680+ toJSON (MatchQuery (FieldName fieldName)
2681+ (QueryString mqQueryString) booleanOperator
2682+ zeroTermsQuery cutoffFrequency matchQueryType
2683+ analyzer maxExpansions lenient boost) =
2684+ object [ fieldName .= omitNulls base ]
2685+ where base = [ "query" .= mqQueryString
2686+ , "operator" .= booleanOperator
2687+ , "zero_terms_query" .= zeroTermsQuery
2688+ , "cutoff_frequency" .= cutoffFrequency
2689+ , "type" .= matchQueryType
2690+ , "analyzer" .= analyzer
2691+ , "max_expansions" .= maxExpansions
2692+ , "lenient" .= lenient
2693+ , "boost" .= boost ]
2695+instance FromJSON MatchQuery where
2696+ parseJSON = withObject "MatchQuery" parse
2697+ where parse = fieldTagged $ \fn o ->
2700+ <*> o .: "operator"
2701+ <*> o .: "zero_terms_query"
2702+ <*> o .:? "cutoff_frequency"
2704+ <*> o .:? "analyzer"
2705+ <*> o .:? "max_expansions"
2706+ <*> o .:? "lenient"
2709+instance ToJSON MultiMatchQuery where
2710+ toJSON (MultiMatchQuery fields (QueryString query) boolOp
2711+ ztQ tb mmqt cf analyzer maxEx lenient) =
2712+ object ["multi_match" .= omitNulls base]
2713+ where base = [ "fields" .= fmap toJSON fields
2715+ , "operator" .= boolOp
2716+ , "zero_terms_query" .= ztQ
2717+ , "tiebreaker" .= tb
2719+ , "cutoff_frequency" .= cf
2720+ , "analyzer" .= analyzer
2721+ , "max_expansions" .= maxEx
2722+ , "lenient" .= lenient ]
2724+instance FromJSON MultiMatchQuery where
2725+ parseJSON = withObject "MultiMatchQuery" parse
2726+ where parse raw = do o <- raw .: "multi_match"
2728+ <$> o .:? "fields" .!= []
2730+ <*> o .: "operator"
2731+ <*> o .: "zero_terms_query"
2732+ <*> o .:? "tiebreaker"
2734+ <*> o .:? "cutoff_frequency"
2735+ <*> o .:? "analyzer"
2736+ <*> o .:? "max_expansions"
2737+ <*> o .:? "lenient"
2739+instance ToJSON MultiMatchQueryType where
2740+ toJSON MultiMatchBestFields = "best_fields"
2741+ toJSON MultiMatchMostFields = "most_fields"
2742+ toJSON MultiMatchCrossFields = "cross_fields"
2743+ toJSON MultiMatchPhrase = "phrase"
2744+ toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2746+instance FromJSON MultiMatchQueryType where
2747+ parseJSON = withText "MultiMatchPhrasePrefix" parse
2748+ where parse "best_fields" = pure MultiMatchBestFields
2749+ parse "most_fields" = pure MultiMatchMostFields
2750+ parse "cross_fields" = pure MultiMatchCrossFields
2751+ parse "phrase" = pure MultiMatchPhrase
2752+ parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2753+ parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2755+instance ToJSON BooleanOperator where
2756+ toJSON And = String "and"
2757+ toJSON Or = String "or"
2759+instance FromJSON BooleanOperator where
2760+ parseJSON = withText "BooleanOperator" parse
2761+ where parse "and" = pure And
2762+ parse "or" = pure Or
2763+ parse o = fail ("Unexpected BooleanOperator: " <> show o)
2765+instance ToJSON ZeroTermsQuery where
2766+ toJSON ZeroTermsNone = String "none"
2767+ toJSON ZeroTermsAll = String "all"
2769+instance FromJSON ZeroTermsQuery where
2770+ parseJSON = withText "ZeroTermsQuery" parse
2771+ where parse "none" = pure ZeroTermsNone
2772+ parse "all" = pure ZeroTermsAll
2773+ parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2775+instance ToJSON MatchQueryType where
2776+ toJSON MatchPhrase = "phrase"
2777+ toJSON MatchPhrasePrefix = "phrase_prefix"
2779+instance FromJSON MatchQueryType where
2780+ parseJSON = withText "MatchQueryType" parse
2781+ where parse "phrase" = pure MatchPhrase
2782+ parse "phrase_prefix" = pure MatchPhrasePrefix
2783+ parse t = fail ("Unexpected MatchQueryType: " <> show t)
2785+instance FromJSON Status where
2786+ parseJSON (Object v) = Status <$>
2792+ parseJSON _ = empty
2795+instance ToJSON IndexSettings where
2796+ toJSON (IndexSettings s r) = object ["settings" .=
2798+ object ["number_of_shards" .= s, "number_of_replicas" .= r]
2802+instance FromJSON IndexSettings where
2803+ parseJSON = withObject "IndexSettings" parse
2804+ where parse o = do s <- o .: "settings"
2806+ IndexSettings <$> i .: "number_of_shards"
2807+ <*> i .: "number_of_replicas"
2809+instance ToJSON UpdatableIndexSetting where
2810+ toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2811+ toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2812+ toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2813+ toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2814+ toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2815+ toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2816+ toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2817+ toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2818+ toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2819+ toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2820+ toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2821+ toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2822+ toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2823+ toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2824+ toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2825+ toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2826+ toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2827+ toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2828+ toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2829+ toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2830+ toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2831+ toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2832+ toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2833+ toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2834+ toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2835+ toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2836+ toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2837+ toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2839+instance FromJSON UpdatableIndexSetting where
2840+ parseJSON = withObject "UpdatableIndexSetting" parse
2841+ where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2842+ <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2843+ <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2844+ <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2845+ <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2846+ <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2847+ <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2848+ <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2849+ <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2850+ <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2851+ <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2852+ <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2853+ <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2854+ <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2855+ <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2856+ <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2857+ <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2858+ <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2859+ <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2860+ <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2861+ <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2862+ <|> compoundFormat `taggedAt` ["index", "compound_format"]
2863+ <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2864+ <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2865+ <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2866+ <|> blocksRead `taggedAt` ["blocks", "read"]
2867+ <|> blocksWrite `taggedAt` ["blocks", "write"]
2868+ <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2869+ where taggedAt f ks = taggedAt' f (Object o) ks
2870+ taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON =<< unStringlyTypeJSON v))
2871+ taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
2872+ taggedAt' f v' ks) v
2873+ numberOfReplicas = pure . NumberOfReplicas
2874+ autoExpandReplicas = pure . AutoExpandReplicas
2875+ refreshInterval = pure . RefreshInterval . ndtJSON
2876+ indexConcurrency = pure . IndexConcurrency
2877+ failOnMergeFailure = pure . FailOnMergeFailure
2878+ translogFlushThresholdOps = pure . TranslogFlushThresholdOps
2879+ translogFlushThresholdSize = pure . TranslogFlushThresholdSize
2880+ translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
2881+ translogDisableFlush = pure . TranslogDisableFlush
2882+ cacheFilterMaxSize = pure . CacheFilterMaxSize
2883+ cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
2884+ gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
2885+ routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
2886+ routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
2887+ routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
2888+ routingAllocationEnable = pure . RoutingAllocationEnable
2889+ routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
2890+ recoveryInitialShards = pure . RecoveryInitialShards
2891+ gcDeletes = pure . GCDeletes . ndtJSON
2892+ ttlDisablePurge = pure . TTLDisablePurge
2893+ translogFSType = pure . TranslogFSType
2894+ compoundFormat = pure . IndexCompoundFormat
2895+ compoundOnFlush = pure . IndexCompoundOnFlush
2896+ warmerEnabled = pure . WarmerEnabled
2897+ blocksReadOnly = pure . BlocksReadOnly
2898+ blocksRead = pure . BlocksRead
2899+ blocksWrite = pure . BlocksWrite
2900+ blocksMetaData = pure . BlocksMetaData
2902+instance FromJSON IndexSettingsSummary where
2903+ parseJSON = withObject "IndexSettingsSummary" parse
2904+ where parse o = case HM.toList o of
2905+ [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
2907+ <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
2908+ _ -> fail "Expected single-key object with index name"
2909+ redundant (NumberOfReplicas _) = True
2910+ redundant _ = False
2912+-- | For some reason in the settings API, all leaf values get returned
2913+-- as strings. This function attepmts to recover from this for all
2914+-- non-recursive JSON types. If nothing can be done or the same value
2915+-- would be return, it returns 'mzero'
2916+unStringlyTypeJSON :: MonadPlus m => Value -> m Value
2917+unStringlyTypeJSON (String "true") = return (Bool True)
2918+unStringlyTypeJSON (String "false") = return (Bool False)
2919+unStringlyTypeJSON (String "null") = return Null
2920+unStringlyTypeJSON (String t) = case readMay (T.unpack t) of
2921+ Just n -> return (Number n)
2923+unStringlyTypeJSON _ = mzero
2926+parseSettings :: Object -> Parser [UpdatableIndexSetting]
2927+parseSettings o = do
2929+ -- slice the index object into singleton hashmaps and try to parse each
2930+ parses <- forM (HM.toList o') $ \(k, v) -> do
2931+ -- blocks are now nested into the "index" key, which is not how they're serialized
2932+ let atRoot = Object (HM.singleton k v)
2933+ let atIndex = Object (HM.singleton "index" atRoot)
2934+ optional (parseJSON atRoot <|> parseJSON atIndex)
2935+ return (catMaybes parses)
2937+oPath :: ToJSON a => NonEmpty Text -> a -> Value
2938+oPath (k :| []) v = object [k .= v]
2939+oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2941+attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2942+attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2943+ | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2945+parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
2946+parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
2947+ where parse o = case HM.toList o of
2948+ [] -> fail "Expected non-empty list of NodeAttrFilters"
2949+ x:xs -> DT.mapM (uncurry parse') (x :| xs)
2950+ parse' n = withText "Text" $ \t ->
2951+ case T.splitOn "," t of
2952+ fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
2953+ [] -> fail "Expected non-empty list of filter values"
2955+instance ToJSON ReplicaBounds where
2956+ toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2957+ toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2958+ toJSON ReplicasUnbounded = Bool False
2960+instance FromJSON ReplicaBounds where
2961+ parseJSON v = withText "ReplicaBounds" parseText v
2962+ <|> withBool "ReplicaBounds" parseBool v
2963+ where parseText t = case T.splitOn "-" t of
2964+ [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
2965+ [a, b] -> ReplicasBounded <$> parseReadText a
2966+ <*> parseReadText b
2967+ _ -> fail ("Could not parse ReplicaBounds: " <> show t)
2968+ parseBool False = pure ReplicasUnbounded
2969+ parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
2971+instance ToJSON AllocationPolicy where
2972+ toJSON AllocAll = String "all"
2973+ toJSON AllocPrimaries = String "primaries"
2974+ toJSON AllocNewPrimaries = String "new_primaries"
2975+ toJSON AllocNone = String "none"
2977+instance FromJSON AllocationPolicy where
2978+ parseJSON = withText "AllocationPolicy" parse
2979+ where parse "all" = pure AllocAll
2980+ parse "primaries" = pure AllocPrimaries
2981+ parse "new_primaries" = pure AllocNewPrimaries
2982+ parse "none" = pure AllocNone
2983+ parse t = fail ("Invlaid AllocationPolicy: " <> show t)
2985+instance ToJSON InitialShardCount where
2986+ toJSON QuorumShards = String "quorum"
2987+ toJSON QuorumMinus1Shards = String "quorum-1"
2988+ toJSON FullShards = String "full"
2989+ toJSON FullMinus1Shards = String "full-1"
2990+ toJSON (ExplicitShards x) = toJSON x
2992+instance FromJSON InitialShardCount where
2993+ parseJSON v = withText "InitialShardCount" parseText v
2994+ <|> ExplicitShards <$> parseJSON v
2995+ where parseText "quorum" = pure QuorumShards
2996+ parseText "quorum-1" = pure QuorumMinus1Shards
2997+ parseText "full" = pure FullShards
2998+ parseText "full-1" = pure FullMinus1Shards
2999+ parseText _ = mzero
3001+instance ToJSON FSType where
3002+ toJSON FSSimple = "simple"
3003+ toJSON FSBuffered = "buffered"
3005+instance FromJSON FSType where
3006+ parseJSON = withText "FSType" parse
3007+ where parse "simple" = pure FSSimple
3008+ parse "buffered" = pure FSBuffered
3009+ parse t = fail ("Invalid FSType: " <> show t)
3011+instance ToJSON CompoundFormat where
3012+ toJSON (CompoundFileFormat x) = Bool x
3013+ toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3015+instance FromJSON CompoundFormat where
3016+ parseJSON v = CompoundFileFormat <$> parseJSON v
3017+ <|> MergeSegmentVsTotalIndex <$> parseJSON v
3019+instance ToJSON NominalDiffTimeJSON where
3020+ toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3022+instance FromJSON NominalDiffTimeJSON where
3023+ parseJSON = withText "NominalDiffTime" parse
3024+ where parse t = case T.takeEnd 1 t of
3025+ "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3026+ _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3028+instance ToJSON IndexTemplate where
3029+ toJSON (IndexTemplate p s m) = merge
3030+ (object [ "template" .= p
3031+ , "mappings" .= foldl' merge (object []) m
3035+ merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3037+ merge _ _ = undefined
3039+instance (FromJSON a) => FromJSON (EsResult a) where
3040+ parseJSON jsonVal@(Object v) = do
3041+ found <- v .:? "found" .!= False
3043+ then parseJSON jsonVal
3044+ else return Nothing
3045+ EsResult <$> v .: "_index" <*>
3049+ parseJSON _ = empty
3051+instance (FromJSON a) => FromJSON (EsResultFound a) where
3052+ parseJSON (Object v) = EsResultFound <$>
3053+ v .: "_version" <*>
3055+ parseJSON _ = empty
3057+instance FromJSON EsError where
3058+ parseJSON (Object v) = EsError <$>
3061+ parseJSON _ = empty
3063+instance FromJSON IndexAliasesSummary where
3064+ parseJSON = withObject "IndexAliasesSummary" parse
3065+ where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3066+ go ixn = withObject "index aliases" $ \ia -> do
3067+ aliases <- ia .:? "aliases" .!= mempty
3068+ forM (HM.toList aliases) $ \(aName, v) -> do
3069+ let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3070+ IndexAliasSummary indexAlias <$> parseJSON v
3073+instance ToJSON IndexAliasAction where
3074+ toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3075+ where Object iaObj = toJSON ia
3076+ Object optsObj = toJSON opts
3077+ toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3078+ where Object iaObj = toJSON ia
3080+instance ToJSON IndexAlias where
3081+ toJSON IndexAlias {..} = object ["index" .= srcIndex
3082+ , "alias" .= indexAlias
3085+instance ToJSON IndexAliasCreate where
3086+ toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3087+ where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3088+ Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3090+instance ToJSON AliasRouting where
3091+ toJSON (AllAliasRouting v) = object ["routing" .= v]
3092+ toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3093+ where prs = [("search_routing" .=) <$> srch
3094+ ,("index_routing" .=) <$> idx]
3096+instance FromJSON AliasRouting where
3097+ parseJSON = withObject "AliasRouting" parse
3098+ where parse o = parseAll o <|> parseGranular o
3099+ parseAll o = AllAliasRouting <$> o .: "routing"
3100+ parseGranular o = do
3101+ sr <- o .:? "search_routing"
3102+ ir <- o .:? "index_routing"
3103+ if isNothing sr && isNothing ir
3104+ then fail "Both search_routing and index_routing can't be blank"
3105+ else return (GranularAliasRouting sr ir)
3107+instance FromJSON IndexAliasCreate where
3108+ parseJSON v = withObject "IndexAliasCreate" parse v
3109+ where parse o = IndexAliasCreate <$> optional (parseJSON v)
3112+instance ToJSON SearchAliasRouting where
3113+ toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3115+instance FromJSON SearchAliasRouting where
3116+ parseJSON = withText "SearchAliasRouting" parse
3117+ where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3119+instance ToJSON Search where
3120+ toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3121+ omitNulls [ "query" .= query
3122+ , "filter" .= sFilter
3124+ , "aggregations" .= searchAggs
3125+ , "highlight" .= highlight
3128+ , "track_scores" .= sTrackSortScores
3129+ , "fields" .= sFields
3130+ , "_source" .= sSource]
3133+instance ToJSON Source where
3134+ toJSON NoSource = toJSON False
3135+ toJSON (SourcePatterns patterns) = toJSON patterns
3136+ toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3138+instance ToJSON PatternOrPatterns where
3139+ toJSON (PopPattern pattern) = toJSON pattern
3140+ toJSON (PopPatterns patterns) = toJSON patterns
3142+instance ToJSON Include where
3143+ toJSON (Include patterns) = toJSON patterns
3145+instance ToJSON Exclude where
3146+ toJSON (Exclude patterns) = toJSON patterns
3148+instance ToJSON Pattern where
3149+ toJSON (Pattern pattern) = toJSON pattern
3152+instance ToJSON FieldHighlight where
3153+ toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3154+ object [ fName .= fSettings ]
3155+ toJSON (FieldHighlight (FieldName fName) Nothing) =
3156+ object [ fName .= emptyObject ]
3158+instance ToJSON Highlights where
3159+ toJSON (Highlights global fields) =
3160+ omitNulls (("fields" .= fields)
3161+ : highlightSettingsPairs global)
3163+instance ToJSON HighlightSettings where
3164+ toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3166+highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3167+highlightSettingsPairs Nothing = []
3168+highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3169+highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3170+highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3173+plainHighPairs :: Maybe PlainHighlight -> [Pair]
3174+plainHighPairs Nothing = []
3175+plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3176+ [ "type" .= String "plain"]
3177+ ++ commonHighlightPairs plCom
3178+ ++ nonPostingsToPairs plNonPost
3180+postHighPairs :: Maybe PostingsHighlight -> [Pair]
3181+postHighPairs Nothing = []
3182+postHighPairs (Just (PostingsHighlight pCom)) =
3183+ ("type" .= String "postings")
3184+ : commonHighlightPairs pCom
3186+fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3187+fastVectorHighPairs Nothing = []
3188+fastVectorHighPairs (Just
3189+ (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3190+ fvBoundMaxScan fvFragOff fvMatchedFields
3192+ [ "type" .= String "fvh"
3193+ , "boundary_chars" .= fvBoundChars
3194+ , "boundary_max_scan" .= fvBoundMaxScan
3195+ , "fragment_offset" .= fvFragOff
3196+ , "matched_fields" .= fvMatchedFields
3197+ , "phraseLimit" .= fvPhraseLim]
3198+ ++ commonHighlightPairs fvCom
3199+ ++ nonPostingsToPairs fvNonPostSettings
3201+deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3202+deleteSeveral ks hm = foldr HM.delete hm ks
3204+commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3205+commonHighlightPairs Nothing = []
3206+commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3207+ chNoMatchSize chHighlightQuery
3208+ chRequireFieldMatch)) =
3209+ [ "order" .= chScore
3210+ , "force_source" .= chForceSource
3211+ , "encoder" .= chEncoder
3212+ , "no_match_size" .= chNoMatchSize
3213+ , "highlight_query" .= chHighlightQuery
3214+ , "require_fieldMatch" .= chRequireFieldMatch]
3215+ ++ highlightTagToPairs chTag
3218+nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3219+nonPostingsToPairs Nothing = []
3220+nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3221+ [ "fragment_size" .= npFragSize
3222+ , "number_of_fragments" .= npNumOfFrags]
3224+parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3225+parseNEJSON [] = fail "Expected non-empty list"
3226+parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3229+instance ToJSON HighlightEncoder where
3230+ toJSON DefaultEncoder = String "default"
3231+ toJSON HTMLEncoder = String "html"
3233+highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3234+highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3235+highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3236+ , "post_tags" .= post]
3237+highlightTagToPairs Nothing = []
3239+instance ToJSON SortSpec where
3240+ toJSON (DefaultSortSpec
3241+ (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3242+ dsSortMode dsMissingSort dsNestedFilter)) =
3243+ object [dsSortFieldName .= omitNulls base] where
3244+ base = [ "order" .= dsSortOrder
3245+ , "ignore_unmapped" .= dsIgnoreUnmapped
3246+ , "mode" .= dsSortMode
3247+ , "missing" .= dsMissingSort
3248+ , "nested_filter" .= dsNestedFilter ]
3250+ toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3251+ object [ "unit" .= units
3252+ , field .= gdsLatLon
3253+ , "order" .= gdsSortOrder ]
3256+instance ToJSON SortOrder where
3257+ toJSON Ascending = String "asc"
3258+ toJSON Descending = String "desc"
3261+instance ToJSON SortMode where
3262+ toJSON SortMin = String "min"
3263+ toJSON SortMax = String "max"
3264+ toJSON SortSum = String "sum"
3265+ toJSON SortAvg = String "avg"
3268+instance ToJSON Missing where
3269+ toJSON LastMissing = String "_last"
3270+ toJSON FirstMissing = String "_first"
3271+ toJSON (CustomMissing txt) = String txt
3274+instance ToJSON ScoreType where
3275+ toJSON ScoreTypeMax = "max"
3276+ toJSON ScoreTypeAvg = "avg"
3277+ toJSON ScoreTypeSum = "sum"
3278+ toJSON ScoreTypeNone = "none"
3280+instance FromJSON ScoreType where
3281+ parseJSON = withText "ScoreType" parse
3282+ where parse "max" = pure ScoreTypeMax
3283+ parse "avg" = pure ScoreTypeAvg
3284+ parse "sum" = pure ScoreTypeSum
3285+ parse "none" = pure ScoreTypeNone
3286+ parse t = fail ("Unexpected ScoreType: " <> show t)
3288+instance ToJSON Distance where
3289+ toJSON (Distance dCoefficient dUnit) =
3290+ String boltedTogether where
3291+ coefText = showText dCoefficient
3292+ (String unitText) = toJSON dUnit
3293+ boltedTogether = mappend coefText unitText
3295+instance FromJSON Distance where
3296+ parseJSON = withText "Distance" parse
3297+ where parse t = Distance <$> parseCoeff nT
3298+ <*> parseJSON (String unitT)
3299+ where (nT, unitT) = T.span validForNumber t
3300+ -- may be a better way to do this
3301+ validForNumber '-' = True
3302+ validForNumber '.' = True
3303+ validForNumber 'e' = True
3304+ validForNumber c = isNumber c
3305+ parseCoeff "" = fail "Empty string cannot be parsed as number"
3306+ parseCoeff s = return (read (T.unpack s))
3308+instance ToJSON DistanceUnit where
3309+ toJSON Miles = String "mi"
3310+ toJSON Yards = String "yd"
3311+ toJSON Feet = String "ft"
3312+ toJSON Inches = String "in"
3313+ toJSON Kilometers = String "km"
3314+ toJSON Meters = String "m"
3315+ toJSON Centimeters = String "cm"
3316+ toJSON Millimeters = String "mm"
3317+ toJSON NauticalMiles = String "nmi"
3320+instance FromJSON DistanceUnit where
3321+ parseJSON = withText "DistanceUnit" parse
3322+ where parse "mi" = pure Miles
3323+ parse "yd" = pure Yards
3324+ parse "ft" = pure Feet
3325+ parse "in" = pure Inches
3326+ parse "km" = pure Kilometers
3327+ parse "m" = pure Meters
3328+ parse "cm" = pure Centimeters
3329+ parse "mm" = pure Millimeters
3330+ parse "nmi" = pure NauticalMiles
3331+ parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3333+instance ToJSON DistanceType where
3334+ toJSON Arc = String "arc"
3335+ toJSON SloppyArc = String "sloppy_arc"
3336+ toJSON Plane = String "plane"
3338+instance FromJSON DistanceType where
3339+ parseJSON = withText "DistanceType" parse
3340+ where parse "arc" = pure Arc
3341+ parse "sloppy_arc" = pure SloppyArc
3342+ parse "plane" = pure Plane
3343+ parse t = fail ("Unrecognized DistanceType: " <> show t)
3346+instance ToJSON OptimizeBbox where
3347+ toJSON NoOptimizeBbox = String "none"
3348+ toJSON (OptimizeGeoFilterType gft) = toJSON gft
3350+instance FromJSON OptimizeBbox where
3351+ parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3352+ <|> parseOptimize v
3353+ where parseNoOptimize "none" = pure NoOptimizeBbox
3354+ parseNoOptimize _ = mzero
3355+ parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3357+instance ToJSON GeoBoundingBoxConstraint where
3358+ toJSON (GeoBoundingBoxConstraint
3359+ (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3360+ object [gbbcGeoBBField .= gbbcConstraintBox
3361+ , "_cache" .= cache
3364+instance FromJSON GeoBoundingBoxConstraint where
3365+ parseJSON = withObject "GeoBoundingBoxConstraint" parse
3366+ where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3367+ [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3369+ <*> o .:? "_cache" .!= defaultCache
3371+ _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3373+instance ToJSON GeoFilterType where
3374+ toJSON GeoFilterMemory = String "memory"
3375+ toJSON GeoFilterIndexed = String "indexed"
3377+instance FromJSON GeoFilterType where
3378+ parseJSON = withText "GeoFilterType" parse
3379+ where parse "memory" = pure GeoFilterMemory
3380+ parse "indexed" = pure GeoFilterIndexed
3381+ parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3383+instance ToJSON GeoBoundingBox where
3384+ toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3385+ object ["top_left" .= gbbTopLeft
3386+ , "bottom_right" .= gbbBottomRight]
3388+instance FromJSON GeoBoundingBox where
3389+ parseJSON = withObject "GeoBoundingBox" parse
3390+ where parse o = GeoBoundingBox
3391+ <$> o .: "top_left"
3392+ <*> o .: "bottom_right"
3394+instance ToJSON LatLon where
3395+ toJSON (LatLon lLat lLon) =
3396+ object ["lat" .= lLat
3399+instance FromJSON LatLon where
3400+ parseJSON = withObject "LatLon" parse
3401+ where parse o = LatLon <$> o .: "lat"
3404+-- index for smaller ranges, fielddata for longer ranges
3405+instance ToJSON RangeExecution where
3406+ toJSON RangeExecutionIndex = "index"
3407+ toJSON RangeExecutionFielddata = "fielddata"
3410+instance FromJSON RangeExecution where
3411+ parseJSON = withText "RangeExecution" parse
3412+ where parse "index" = pure RangeExecutionIndex
3413+ parse "fielddata" = pure RangeExecutionFielddata
3414+ parse t = error ("Unrecognized RangeExecution " <> show t)
3416+instance ToJSON RegexpFlags where
3417+ toJSON AllRegexpFlags = String "ALL"
3418+ toJSON NoRegexpFlags = String "NONE"
3419+ toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3420+ where flagStrs = map flagStr . nub $ h:fs
3421+ flagStr AnyString = "ANYSTRING"
3422+ flagStr Automaton = "AUTOMATON"
3423+ flagStr Complement = "COMPLEMENT"
3424+ flagStr Empty = "EMPTY"
3425+ flagStr Intersection = "INTERSECTION"
3426+ flagStr Interval = "INTERVAL"
3428+instance FromJSON RegexpFlags where
3429+ parseJSON = withText "RegexpFlags" parse
3430+ where parse "ALL" = pure AllRegexpFlags
3431+ parse "NONE" = pure NoRegexpFlags
3432+ parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3434+instance FromJSON RegexpFlag where
3435+ parseJSON = withText "RegexpFlag" parse
3436+ where parse "ANYSTRING" = pure AnyString
3437+ parse "AUTOMATON" = pure Automaton
3438+ parse "COMPLEMENT" = pure Complement
3439+ parse "EMPTY" = pure Empty
3440+ parse "INTERSECTION" = pure Intersection
3441+ parse "INTERVAL" = pure Interval
3442+ parse f = fail ("Unknown RegexpFlag: " <> show f)
3444+instance ToJSON Term where
3445+ toJSON (Term field value) = object ["term" .= object
3448+instance FromJSON Term where
3449+ parseJSON = withObject "Term" parse
3450+ where parse o = do termObj <- o .: "term"
3451+ case HM.toList termObj of
3452+ [(fn, v)] -> Term fn <$> parseJSON v
3453+ _ -> fail "Expected object with 1 field-named key"
3455+instance ToJSON BoolMatch where
3456+ toJSON (MustMatch term cache) = object ["must" .= term,
3458+ toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3460+ toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3463+instance FromJSON BoolMatch where
3464+ parseJSON = withObject "BoolMatch" parse
3465+ where parse o = mustMatch `taggedWith` "must"
3466+ <|> mustNotMatch `taggedWith` "must_not"
3467+ <|> shouldMatch `taggedWith` "should"
3468+ where taggedWith parser k = parser =<< o .: k
3469+ mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3470+ mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3471+ shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3473+instance (FromJSON a) => FromJSON (SearchResult a) where
3474+ parseJSON (Object v) = SearchResult <$>
3476+ v .: "timed_out" <*>
3479+ v .:? "aggregations" <*>
3481+ parseJSON _ = empty
3483+instance (FromJSON a) => FromJSON (SearchHits a) where
3484+ parseJSON (Object v) = SearchHits <$>
3486+ v .: "max_score" <*>
3488+ parseJSON _ = empty
3490+instance (FromJSON a) => FromJSON (Hit a) where
3491+ parseJSON (Object v) = Hit <$>
3496+ v .:? "_source" <*>
3498+ parseJSON _ = empty
3500+instance FromJSON ShardResult where
3501+ parseJSON (Object v) = ShardResult <$>
3503+ v .: "successful" <*>
3505+ parseJSON _ = empty
3508+instance FromJSON DocVersion where
3511+ maybe (fail "DocVersion out of range") return $ mkDocVersion i
3513+-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3514+instance FromJSON ReplicaCount where
3515+ parseJSON v = parseAsInt v
3516+ <|> parseAsString v
3517+ where parseAsInt = fmap ReplicaCount . parseJSON
3518+ parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3520+instance FromJSON ShardCount where
3521+ parseJSON v = parseAsInt v
3522+ <|> parseAsString v
3523+ where parseAsInt = fmap ShardCount . parseJSON
3524+ parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3526+instance Bounded DocVersion where
3527+ minBound = DocVersion 1
3528+ maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3530+instance Enum DocVersion where
3532+ | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3533+ | otherwise = succError "DocVersion"
3535+ | x /= minBound = DocVersion (pred $ docVersionNumber x)
3536+ | otherwise = predError "DocVersion"
3538+ fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3539+ fromEnum = docVersionNumber
3540+ enumFrom = boundedEnumFrom
3541+ enumFromThen = boundedEnumFromThen
3543+-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3544+newtype EsUsername = EsUsername { esUsername :: Text } deriving (Show, Eq)
540−newtype ScrollId =
3546+-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
541− ScrollId Text
3547+newtype EsPassword = EsPassword { esPassword :: Text } deriving (Show, Eq)
542− deriving (Eq, Show, Ord, ToJSON, FromJSON)