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