@@ -1,8 +1,8 @@
1−{-# LANGUAGE DeriveGeneric #-}
2{-# LANGUAGE FlexibleContexts #-}
1{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleInstances #-}
2{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE NamedFieldPuns #-}
6{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
7{-# LANGUAGE RecordWildCards #-}
7{-# LANGUAGE RecordWildCards #-}
8{-# LANGUAGE UndecidableInstances #-}
8{-# LANGUAGE UndecidableInstances #-}
@@ -10,11 +10,11 @@
10-------------------------------------------------------------------------------
10-------------------------------------------------------------------------------
12-- Module : Database.Bloodhound.Types
12-- Module : Database.Bloodhound.Types
13−-- Copyright : (C) 2014 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
14-- License : BSD-style (see the file LICENSE)
14-- License : BSD-style (see the file LICENSE)
15-- Maintainer : Chris Allen <cma@bitemyapp.com
15-- Maintainer : Chris Allen <cma@bitemyapp.com
16-- Stability : provisional
16-- Stability : provisional
17−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
19-- Data types for describing actions and data structures performed to interact
19-- Data types for describing actions and data structures performed to interact
20-- with Elasticsearch. The two main buckets your queries against Elasticsearch
20-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -42,26 +42,63 @@ module Database.Bloodhound.Types
42 , mkTermsAggregation
42 , mkTermsAggregation
43 , mkTermsScriptAggregation
43 , mkTermsScriptAggregation
44 , mkDateHistogram
44 , mkDateHistogram
45+ , mkCardinalityAggregation
45 , mkDocVersion
46 , mkDocVersion
48+ , mkExtendedStatsAggregation
46 , docVersionNumber
49 , docVersionNumber
48 , toDateHistogram
52 , toDateHistogram
49 , omitNulls
54 , omitNulls
52− , BHEnv(..)
57+ , BHEnv
53 , MonadBH(..)
62 , MonadBH(..)
54 , Version(..)
63 , Version(..)
55 , Status(..)
67 , Status(..)
56 , Existence(..)
68 , Existence(..)
57 , NullValue(..)
69 , NullValue(..)
58 , IndexSettings(..)
70 , IndexSettings(..)
59− , IndexSettingUpdate(..)
71+ , UpdatableIndexSetting(..)
72+ , IndexSettingsSummary(..)
73+ , AllocationPolicy(..)
81+ , InitialShardCount(..)
60 , IndexTemplate(..)
85 , IndexTemplate(..)
61 , Server(..)
86 , Server(..)
63 , EsResult(..)
88 , EsResult(..)
64 , EsResultFound(..)
89 , EsResultFound(..)
91+ , EsProtocolException(..)
94+ , IndexAliasAction(..)
95+ , IndexAliasCreate(..)
96+ , IndexAliasSummary(..)
97+ , IndexAliasesSummary(..)
99+ , SearchAliasRouting(..)
100+ , IndexAliasRouting(..)
65 , DocVersion
102 , DocVersion
66 , ExternalDocVersion(..)
103 , ExternalDocVersion(..)
67 , VersionControl(..)
104 , VersionControl(..)
@@ -71,7 +108,7 @@ module Database.Bloodhound.Types
71 , Search(..)
108 , Search(..)
72 , SearchType(..)
109 , SearchType(..)
73 , SearchResult(..)
110 , SearchResult(..)
74− , ScrollId
111+ , ScrollId(..)
75 , SearchHits(..)
112 , SearchHits(..)
76 , TrackSortScores
113 , TrackSortScores
77 , From(..)
114 , From(..)
@@ -83,8 +120,8 @@ module Database.Bloodhound.Types
83 , Pattern(..)
120 , Pattern(..)
84 , ShardResult(..)
121 , ShardResult(..)
85 , Hit(..)
122 , Hit(..)
86 , Filter(..)
124 , Filter(..)
88 , BoolMatch(..)
125 , BoolMatch(..)
89 , Term(..)
126 , Term(..)
90 , GeoPoint(..)
127 , GeoPoint(..)
@@ -111,8 +148,22 @@ module Database.Bloodhound.Types
111 , RegexpFlags(..)
148 , RegexpFlags(..)
112 , RegexpFlag(..)
149 , RegexpFlag(..)
113 , FieldName(..)
150 , FieldName(..)
114 , Script(..)
154 , Script(..)
155+ , ScriptLanguage(..)
115 , IndexName(..)
161 , IndexName(..)
162+ , IndexSelection(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
116 , TemplateName(..)
167 , TemplateName(..)
117 , TemplatePattern(..)
168 , TemplatePattern(..)
118 , MappingName(..)
169 , MappingName(..)
@@ -136,8 +187,19 @@ module Database.Bloodhound.Types
136 , BoolQuery(..)
187 , BoolQuery(..)
137 , BoostingQuery(..)
188 , BoostingQuery(..)
138 , CommonTermsQuery(..)
189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
198+ , FieldValueFactor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
139 , DisMaxQuery(..)
202 , DisMaxQuery(..)
141 , FuzzyLikeThisQuery(..)
203 , FuzzyLikeThisQuery(..)
142 , FuzzyLikeFieldQuery(..)
204 , FuzzyLikeFieldQuery(..)
143 , FuzzyQuery(..)
205 , FuzzyQuery(..)
@@ -153,10 +215,16 @@ module Database.Bloodhound.Types
153 , RangeQuery(..)
215 , RangeQuery(..)
154 , RegexpQuery(..)
216 , RegexpQuery(..)
155 , QueryString(..)
217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
156 , BooleanOperator(..)
221 , BooleanOperator(..)
157 , ZeroTermsQuery(..)
222 , ZeroTermsQuery(..)
158 , CutoffFrequency(..)
223 , CutoffFrequency(..)
159 , Analyzer(..)
224 , Analyzer(..)
160 , MaxExpansions(..)
228 , MaxExpansions(..)
161 , Lenient(..)
229 , Lenient(..)
162 , MatchQueryType(..)
230 , MatchQueryType(..)
@@ -203,16 +271,118 @@ module Database.Bloodhound.Types
203 , CollectionMode(..)
271 , CollectionMode(..)
204 , TermOrder(..)
272 , TermOrder(..)
205 , 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 (..)
207 , Aggregation(..)
364 , Aggregation(..)
208 , Aggregations
365 , Aggregations
209 , AggregationResults
366 , AggregationResults
210 , Bucket(..)
368 , Bucket(..)
211 , BucketAggregation(..)
369 , BucketAggregation(..)
212 , TermsAggregation(..)
370 , TermsAggregation(..)
371+ , MissingAggregation(..)
213 , ValueCountAggregation(..)
372 , ValueCountAggregation(..)
214 , FilterAggregation(..)
373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
215 , DateHistogramAggregation(..)
376 , DateHistogramAggregation(..)
377+ , DateRangeAggregation(..)
378+ , DateRangeAggRange(..)
380+ , DateMathAnchor(..)
381+ , DateMathModifier(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
217 , Highlights(..)
387 , Highlights(..)
218 , FieldHighlight(..)
388 , FieldHighlight(..)
@@ -226,544 +396,36 @@ module Database.Bloodhound.Types
226 , HighlightTag(..)
396 , HighlightTag(..)
227 , HitHighlight
397 , HitHighlight
229 , TermsResult(..)
400 , TermsResult(..)
230 , DateHistogramResult(..)
401 , DateHistogramResult(..)
231− ) where
402+ , DateRangeResult(..)
232−
403+ , TopHitResult(..)
233−import Control.Applicative
404+
234−import Control.Monad.Catch
405+ , EsUsername(..)
235−import Control.Monad.Except
406+ , EsPassword(..)
236−import Control.Monad.Reader
407+
237−import Control.Monad.State
408+ , Analysis(..)
238−import Control.Monad.Writer
409+ , AnalyzerDefinition(..)
239−import Data.Aeson
410+ , TokenizerDefinition(..)
240−import Data.Aeson.Types (Pair, emptyObject, parseMaybe)
411+ , TokenFilterDefinition(..)
241−import qualified Data.ByteString.Lazy.Char8 as L
412+ , CharFilterDefinition(..)
242−import qualified Data.HashMap.Strict as HM (union)
413+ , Ngram(..)
243−import Data.List (foldl', nub)
414+ , TokenChar(..)
244−import Data.List.NonEmpty (NonEmpty (..), toList)
415+ , Shingle(..)
245−import qualified Data.Map.Strict as M
416+ , Language(..)
246−import Data.Maybe
417+ ) where
247−import Data.Text (Text)
418+
248−import qualified Data.Text as T
419+import Bloodhound.Import
249−import Data.Time.Clock (UTCTime, NominalDiffTime)
420+
250−import qualified Data.Vector as V
421+import Database.Bloodhound.Internal.Aggregation
251−import GHC.Enum
422+import Database.Bloodhound.Internal.Analysis
252−import GHC.Generics (Generic)
423+import Database.Bloodhound.Internal.Client
253−import Network.HTTP.Client
424+import Database.Bloodhound.Internal.Highlight
254−import qualified Network.HTTP.Types.Method as NHTM
425+import Database.Bloodhound.Internal.Newtypes
255−
426+import Database.Bloodhound.Internal.Query
256−import Database.Bloodhound.Types.Class
427+import Database.Bloodhound.Internal.Sort
257−
428+import Database.Bloodhound.Internal.Suggest
259−-- >>> :set -XOverloadedStrings
260−-- >>> import Database.Bloodhound
261−-- >>> let testServer = (Server "http://localhost:9200")
262−-- >>> let testIndex = IndexName "twitter"
263−-- >>> let testMapping = MappingName "tweet"
264−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
266−-- defaultIndexSettings is exported by Database.Bloodhound as well
267−-- no trailing slashes in servers, library handles building the path.
269−{-| Common environment for Elasticsearch calls. Connections will be
270− pipelined according to the provided HTTP connection manager.
272−data BHEnv = BHEnv { bhServer :: Server
273− , bhManager :: Manager
276−{-| All API calls to Elasticsearch operate within
277− MonadBH. The idea is that it can be easily embedded in your
278− own monad transformer stack. A default instance for a ReaderT and
279− alias 'BH' is provided for the simple case.
281−class (Functor m, Applicative m, MonadIO m) => MonadBH m where
284−newtype BH m a = BH {
285− unBH :: ReaderT BHEnv m a
286− } deriving ( Functor
300−instance MonadTrans BH where
303−instance (MonadReader r m) => MonadReader r (BH m) where
305− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
308−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
309− getBHEnv = BH getBHEnv
312−instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where
315−runBH :: BHEnv -> BH m a -> m a
316−runBH e f = runReaderT (unBH f) e
318−{-| 'Version' is embedded in 'Status' -}
319−data Version = Version { number :: Text
320− , build_hash :: Text
321− , build_timestamp :: UTCTime
322− , build_snapshot :: Bool
323− , lucene_version :: Text } deriving (Eq, Show, Generic)
325−{-| 'Status' is a data type for describing the JSON body returned by
326− Elasticsearch when you query its status. This was deprecated in 1.2.0.
328− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
331−data Status = Status { ok :: Maybe Bool
334− , version :: Version
335− , tagline :: Text } deriving (Eq, Show)
337−{-| 'IndexSettings' is used to configure the shards and replicas when you create
338− an Elasticsearch Index.
340− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
344− IndexSettings { indexShards :: ShardCount
345− , indexReplicas :: ReplicaCount } deriving (Eq, Show)
347−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
348−defaultIndexSettings :: IndexSettings
349−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
351−data IndexSettingUpdate = NumberOfReplicas Int
352− | AutoExpandReplicas ReplicaBounds
353− | BlocksReadOnly Bool
356− | BlocksMetaData Bool
357− | RefreshInterval NominalDiffTime
358− | IndexConcurrency Int
359− | FailOnMergeFailure Bool
360− | TranslogFlushThresholdOps Int
361− | TranslogFlushThresholdSize Bytes
362− | TranslogFlushThresholdPeriod NominalDiffTime
363− | TranslogDisableFlush Bool
364− | CacheFilterMaxSize (Maybe Bytes)
365− | CacheFilterExpire (Maybe NominalDiffTime)
366− | GatewaySnapshotInterval NominalDiffTime
367− | RoutingAllocationDisable Bool
368− | RoutingAllocationDisableNew Bool
369− | RoutingAllocationDisableReplica Bool
370− | RoutingAllocationEnable AllocationPolicy
371− | RoutingAllocationShardsPerNode ShardCount
372− | RecoveryInitialShards --TODO: shard count or quorum specifications
374− | TTLDisablePurge Bool
375− | TranslogFSType FSType
376− | TranslogCompoundFormat
377− | TranslogCompoundOnFlush
378− | WarmerEnabled Bool
379− --TODO: figure out allocation options
381−data AllocationPolicy = AllocAll
386−data ReplicaBounds = ReplicasBounded Int Int
387− | ReplicasLowerBounded Int
390−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
391−type Reply = Network.HTTP.Client.Response L.ByteString
392−type Method = NHTM.Method
394−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
396− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
398−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show)
400−data FieldType = GeoPointType
406− | ByteType deriving (Eq, Show)
408−data FieldDefinition =
409− FieldDefinition { fieldType :: FieldType } deriving (Eq, Show)
411−{-| An 'IndexTemplate' defines a template that will automatically be
412− applied to new indices created. The templates include both
413− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
414− controls if the template will be applied to the index created.
415− Specify mappings as follows: @[toJSON TweetMapping, ...]@
417− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
420− IndexTemplate { templatePattern :: TemplatePattern
421− , templateSettings :: Maybe IndexSettings
422− , templateMappings :: [Value]
426− MappingField { mappingFieldName :: FieldName
427− , fieldDefinition :: FieldDefinition } deriving (Eq, Show)
429−{-| Support for type reification of 'Mapping's is currently incomplete, for
430− now the mapping API verbiage expects a 'ToJSON'able blob.
432− Indexes have mappings, mappings are schemas for the documents contained in the
433− index. I'd recommend having only one mapping per index, always having a mapping,
434− and keeping different kinds of documents separated if possible.
436−data Mapping = Mapping { typeName :: TypeName
437− , mappingFields :: [MappingField] } deriving (Eq, Show)
439−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
440− operation index, create, delete, and update. 'BulkIndex' behaves like an
441− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
443− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
446− BulkIndex IndexName MappingName DocId Value
447− | BulkCreate IndexName MappingName DocId Value
448− | BulkDelete IndexName MappingName DocId
449− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show)
451−{-| 'EsResult' describes the standard wrapper JSON document that you see in
452− successful Elasticsearch lookups or lookups that couldn't find the document.
454−data EsResult a = EsResult { _index :: Text
457− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show)
460−{-| 'EsResultFound' contains the document and its metadata inside of an
461− 'EsResult' when the document was successfully found.
463−data EsResultFound a = EsResultFound { _version :: DocVersion
464− , _source :: a } deriving (Eq, Show)
468−{-| 'DocVersion' is an integer version number for a document between 1
469−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
471−newtype DocVersion = DocVersion {
472− docVersionNumber :: Int
473− } deriving (Eq, Show, Ord, ToJSON)
475−-- | Smart constructor for in-range doc version
476−mkDocVersion :: Int -> Maybe DocVersion
478− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
480− | otherwise = Nothing
483−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
484−own version numbers instead of ones from ES.
486−newtype ExternalDocVersion = ExternalDocVersion DocVersion
487− deriving (Eq, Show, Ord, Bounded, Enum, ToJSON)
489−{-| 'VersionControl' is specified when indexing documents as a
490−optimistic concurrency control.
492−data VersionControl = NoVersionControl
493− -- ^ Don't send a version. This is a pure overwrite.
494− | InternalVersion DocVersion
495− -- ^ Use the default ES versioning scheme. Only
496− -- index the document if the version is the same
497− -- as the one specified. Only applicable to
498− -- updates, as you should be getting Version from
500− | ExternalGT ExternalDocVersion
501− -- ^ Use your own version numbering. Only index
502− -- the document if the version is strictly higher
503− -- OR the document doesn't exist. The given
504− -- version will be used as the new version number
505− -- for the stored document. N.B. All updates must
506− -- increment this number, meaning there is some
507− -- global, external ordering of updates.
508− | ExternalGTE ExternalDocVersion
509− -- ^ Use your own version numbering. Only index
510− -- the document if the version is equal or higher
511− -- than the stored version. Will succeed if there
512− -- is no existing document. The given version will
513− -- be used as the new version number for the
514− -- stored document. Use with care, as this could
515− -- result in data loss.
516− | ForceVersion ExternalDocVersion
517− -- ^ The document will always be indexed and the
518− -- given version will be the new version. This is
519− -- typically used for correcting errors. Use with
520− -- care, as this could result in data loss.
521− deriving (Show, Eq, Ord)
523−{-| 'DocumentParent' is used to specify a parent document.
525−newtype DocumentParent = DocumentParent DocId
528−{-| 'IndexDocumentSettings' are special settings supplied when indexing
529−a document. For the best backwards compatiblity when new fields are
530−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
532−data IndexDocumentSettings =
533− IndexDocumentSettings { idsVersionControl :: VersionControl
534− , idsParent :: Maybe DocumentParent
535− } deriving (Eq, Show)
537−{-| Reasonable default settings. Chooses no version control and no parent.
539−defaultIndexDocumentSettings :: IndexDocumentSettings
540−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
542−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
543− dependent with later sorts acting as tie-breakers for earlier sorts.
545−type Sort = [SortSpec]
547−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
548− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
549− 'DistanceUnit' to express "nearness" to a single geographical point as a
552−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
554−data SortSpec = DefaultSortSpec DefaultSort
555− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show)
557−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
558− 'mkSort' convenience function for when you want to specify only the most
561−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
564− DefaultSort { sortFieldName :: FieldName
565− , sortOrder :: SortOrder
567− , ignoreUnmapped :: Bool
568− , sortMode :: Maybe SortMode
569− , missingSort :: Maybe Missing
570− , nestedFilter :: Maybe Filter } deriving (Eq, Show)
572−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
573− encoded into "asc" or "desc" when turned into JSON.
575−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
577−data SortOrder = Ascending
578− | Descending deriving (Eq, Show)
580−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
581− sorted last, first, or using a custom value as a substitute.
583−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
585−data Missing = LastMissing
587− | CustomMissing Text deriving (Eq, Show)
589−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
591−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
593−data SortMode = SortMin
596− | SortAvg deriving (Eq, Show)
598−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
599− that you can concisely describe the usual kind of 'SortSpec's you want.
601−mkSort :: FieldName -> SortOrder -> DefaultSort
602−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
604−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
605− 'Query's cannot be cached.
607−type Cache = Bool -- caching on/off
608−defaultCache :: Cache
611−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
613−type PrefixValue = Text
615−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
616− JSON encoding baked in. Used all over the place.
618−data BooleanOperator = And | Or deriving (Eq, Show)
620−{-| 'ShardCount' is part of 'IndexSettings'
622−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic)
624−{-| 'ReplicaCount' is part of 'IndexSettings'
626−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic)
628−{-| 'Server' is used with the client functions to point at the ES instance
630−newtype Server = Server Text deriving (Eq, Show)
632−{-| 'IndexName' is used to describe which index to query/create/delete
634−newtype IndexName = IndexName Text deriving (Eq, Generic, Show)
636−{-| 'TemplateName' is used to describe which template to query/create/delete
638−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic)
640−{-| 'TemplatePattern' represents a pattern which is matched against index names
642−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic)
644−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
645− the data in the indices.
647−newtype MappingName = MappingName Text deriving (Eq, Generic, Show)
649−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
650− Can be set by the user or created by ES itself. Often used in client
651− functions for poking at specific documents.
653−newtype DocId = DocId Text deriving (Eq, Generic, Show)
655−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
657−newtype QueryString = QueryString Text deriving (Eq, Generic, Show)
659−{-| 'FieldName' is used all over the place wherever a specific field within
660− a document needs to be specified, usually in 'Query's or 'Filter's.
662−newtype FieldName = FieldName Text deriving (Eq, Show)
665−{-| 'Script' is often used in place of 'FieldName' to specify more
666−complex ways of extracting a value from a document.
668−newtype Script = Script { scriptText :: Text } deriving (Eq, Show)
670−{-| 'CacheName' is used in 'RegexpFilter' for describing the
671− 'CacheKey' keyed caching behavior.
673−newtype CacheName = CacheName Text deriving (Eq, Show)
675−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
678− CacheKey Text deriving (Eq, Show)
680− Existence Bool deriving (Eq, Show)
682− NullValue Bool deriving (Eq, Show)
683−newtype CutoffFrequency =
684− CutoffFrequency Double deriving (Eq, Show, Generic)
686− Analyzer Text deriving (Eq, Show, Generic)
687−newtype MaxExpansions =
688− MaxExpansions Int deriving (Eq, Show, Generic)
690−{-| 'Lenient', if set to true, will cause format based failures to be
691− ignored. I don't know what the bloody default is, Elasticsearch
692− documentation didn't say what it was. Let me know if you figure it out.
695− Lenient Bool deriving (Eq, Show, Generic)
697− Tiebreaker Double deriving (Eq, Show, Generic)
699− Boost Double deriving (Eq, Show, Generic)
701− BoostTerms Double deriving (Eq, Show, Generic)
703−{-| 'MinimumMatch' controls how many should clauses in the bool query should
704− match. Can be an absolute value (2) or a percentage (30%) or a
705− combination of both.
707−newtype MinimumMatch =
708− MinimumMatch Int deriving (Eq, Show, Generic)
709−newtype MinimumMatchText =
710− MinimumMatchText Text deriving (Eq, Show)
711−newtype DisableCoord =
712− DisableCoord Bool deriving (Eq, Show, Generic)
713−newtype IgnoreTermFrequency =
714− IgnoreTermFrequency Bool deriving (Eq, Show, Generic)
715−newtype MinimumTermFrequency =
716− MinimumTermFrequency Int deriving (Eq, Show, Generic)
717−newtype MaxQueryTerms =
718− MaxQueryTerms Int deriving (Eq, Show, Generic)
720− Fuzziness Double deriving (Eq, Show, Generic)
722−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
723−newtype PrefixLength =
724− PrefixLength Int deriving (Eq, Show, Generic)
726− TypeName Text deriving (Eq, Show, Generic)
727−newtype PercentMatch =
728− PercentMatch Double deriving (Eq, Show, Generic)
730− StopWord Text deriving (Eq, Show, Generic)
732− QueryPath Text deriving (Eq, Show, Generic)
734−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
735− heavy, because all terms in the index need to be examined, just in case
736− they match. Leading wildcards can be disabled by setting
737− 'AllowLeadingWildcard' to false. -}
738−newtype AllowLeadingWildcard =
739− AllowLeadingWildcard Bool deriving (Eq, Show, Generic)
740−newtype LowercaseExpanded =
741− LowercaseExpanded Bool deriving (Eq, Show, Generic)
742−newtype EnablePositionIncrements =
743− EnablePositionIncrements Bool deriving (Eq, Show, Generic)
745−{-| By default, wildcard terms in a query are not analyzed.
746− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
748−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic)
750−{-| 'GeneratePhraseQueries' defaults to false.
752−newtype GeneratePhraseQueries =
753− GeneratePhraseQueries Bool deriving (Eq, Show, Generic)
755−{-| 'Locale' is used for string conversions - defaults to ROOT.
757−newtype Locale = Locale Text deriving (Eq, Show, Generic)
758−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic)
759−newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic)
761−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
762− phrase matches. Default is 0.
764−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic)
765−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic)
766−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic)
768{-| 'unpackId' is a silly convenience function that gets used once.
430{-| 'unpackId' is a silly convenience function that gets used once.
@@ -771,8 +433,6 @@ unpackId :: DocId -> Text
771unpackId (DocId docId) = docId
433unpackId (DocId docId) = docId
773type TrackSortScores = Bool
435type TrackSortScores = Bool
774−newtype From = From Int deriving (Eq, Show, ToJSON)
775−newtype Size = Size Int deriving (Eq, Show, ToJSON)
777data Search = Search { queryBody :: Maybe Query
437data Search = Search { queryBody :: Maybe Query
778 , filterBody :: Maybe Filter
438 , filterBody :: Maybe Filter
@@ -784,1638 +444,87 @@ data Search = Search { queryBody :: Maybe Query
784 , from :: From
444 , from :: From
785 , size :: Size
445 , size :: Size
786 , searchType :: SearchType
446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
787 , fields :: Maybe [FieldName]
448 , fields :: Maybe [FieldName]
449+ , scriptFields :: Maybe ScriptFields
788− , source :: Maybe Source } deriving (Eq, Show)
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)
790data SearchType = SearchTypeQueryThenFetch
480data SearchType = SearchTypeQueryThenFetch
791 | SearchTypeDfsQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
794− | SearchTypeQueryAndFetch
795− | SearchTypeDfsQueryAndFetch
796 deriving (Eq, Show)
482 deriving (Eq, Show)
798data Source =
484data Source =
799− NoSource
485+ NoSource
800 | SourcePatterns PatternOrPatterns
486 | SourcePatterns PatternOrPatterns
801 | SourceIncludeExclude Include Exclude
487 | SourceIncludeExclude Include Exclude
802− deriving (Show, Eq)
488+ deriving (Eq, Show)
804−data PatternOrPatterns = PopPattern Pattern
805− | PopPatterns [Pattern] deriving (Eq, Show)
807−data Include = Include [Pattern] deriving (Eq, Show)
808−data Exclude = Exclude [Pattern] deriving (Eq, Show)
810−newtype Pattern = Pattern Text deriving (Eq, Show)
812−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
813− , highlightFields :: [FieldHighlight]
814− } deriving (Show, Eq)
816−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
820−data HighlightSettings = Plain PlainHighlight
821− | Postings PostingsHighlight
822− | FastVector FastVectorHighlight
824−data PlainHighlight =
825− PlainHighlight { plainCommon :: Maybe CommonHighlight
826− , plainNonPost :: Maybe NonPostings } deriving (Show, Eq)
828− -- This requires that index_options are set to 'offset' in the mapping.
829−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq)
831−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
832−data FastVectorHighlight =
833− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
834− , fvNonPostSettings :: Maybe NonPostings
835− , boundaryChars :: Maybe Text
836− , boundaryMaxScan :: Maybe Int
837− , fragmentOffset :: Maybe Int
838− , matchedFields :: [Text]
839− , phraseLimit :: Maybe Int
840− } deriving (Show, Eq)
842−data CommonHighlight =
843− CommonHighlight { order :: Maybe Text
844− , forceSource :: Maybe Bool
845− , tag :: Maybe HighlightTag
846− , encoder :: Maybe HighlightEncoder
847− , noMatchSize :: Maybe Int
848− , highlightQuery :: Maybe Query
849− , requireFieldMatch :: Maybe Bool
850− } deriving (Show, Eq)
852−-- Settings that are only applicable to FastVector and Plain highlighters.
854− NonPostings { fragmentSize :: Maybe Int
855− , numberOfFragments :: Maybe Int} deriving (Show, Eq)
857−data HighlightEncoder = DefaultEncoder
861−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
862−data HighlightTag = TagSchema Text
863− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
868− TermQuery Term (Maybe Boost)
869− | TermsQuery (NonEmpty Term)
870− | QueryMatchQuery MatchQuery
871− | QueryMultiMatchQuery MultiMatchQuery
872− | QueryBoolQuery BoolQuery
873− | QueryBoostingQuery BoostingQuery
874− | QueryCommonTermsQuery CommonTermsQuery
875− | ConstantScoreFilter Filter Boost
876− | ConstantScoreQuery Query Boost
877− | QueryDisMaxQuery DisMaxQuery
878− | QueryFilteredQuery FilteredQuery
879− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
880− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
881− | QueryFuzzyQuery FuzzyQuery
882− | QueryHasChildQuery HasChildQuery
883− | QueryHasParentQuery HasParentQuery
884− | IdsQuery MappingName [DocId]
885− | QueryIndicesQuery IndicesQuery
886− | MatchAllQuery (Maybe Boost)
887− | QueryMoreLikeThisQuery MoreLikeThisQuery
888− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
889− | QueryNestedQuery NestedQuery
890− | QueryPrefixQuery PrefixQuery
891− | QueryQueryStringQuery QueryStringQuery
892− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
893− | QueryRangeQuery RangeQuery
894− | QueryRegexpQuery RegexpQuery
898− RegexpQuery { regexpQueryField :: FieldName
899− , regexpQuery :: Regexp
900− , regexpQueryFlags :: RegexpFlags
901− , regexpQueryBoost :: Maybe Boost
902− } deriving (Eq, Show)
905− RangeQuery { rangeQueryField :: FieldName
906− , rangeQueryRange :: RangeValue
907− , rangeQueryBoost :: Boost } deriving (Eq, Show)
909−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
910−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
912−data SimpleQueryStringQuery =
913− SimpleQueryStringQuery
914− { simpleQueryStringQuery :: QueryString
915− , simpleQueryStringField :: Maybe FieldOrFields
916− , simpleQueryStringOperator :: Maybe BooleanOperator
917− , simpleQueryStringAnalyzer :: Maybe Analyzer
918− , simpleQueryStringFlags :: Maybe [SimpleQueryFlag]
919− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
920− , simpleQueryStringLocale :: Maybe Locale
921− } deriving (Eq, Show)
923−data SimpleQueryFlag =
930− | SimpleQueryPrecedence
932− | SimpleQueryWhitespace
935− | SimpleQuerySlop deriving (Eq, Show)
937−-- use_dis_max and tie_breaker when fields are plural?
938−data QueryStringQuery =
940− { queryStringQuery :: QueryString
941− , queryStringDefaultField :: Maybe FieldName
942− , queryStringOperator :: Maybe BooleanOperator
943− , queryStringAnalyzer :: Maybe Analyzer
944− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
945− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
946− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
947− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
948− , queryStringFuzziness :: Maybe Fuzziness
949− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
950− , queryStringPhraseSlop :: Maybe PhraseSlop
951− , queryStringBoost :: Maybe Boost
952− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
953− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
954− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
955− , queryStringLenient :: Maybe Lenient
956− , queryStringLocale :: Maybe Locale
957− } deriving (Eq, Show)
959−mkQueryStringQuery :: QueryString -> QueryStringQuery
960−mkQueryStringQuery qs =
961− QueryStringQuery qs Nothing Nothing
962− Nothing Nothing Nothing Nothing
963− Nothing Nothing Nothing Nothing
964− Nothing Nothing Nothing Nothing
967−data FieldOrFields = FofField FieldName
968− | FofFields [FieldName] deriving (Eq, Show)
972− { prefixQueryField :: FieldName
973− , prefixQueryPrefixValue :: Text
974− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show)
978− { nestedQueryPath :: QueryPath
979− , nestedQueryScoreType :: ScoreType
980− , nestedQuery :: Query } deriving (Eq, Show)
982−data MoreLikeThisFieldQuery =
983− MoreLikeThisFieldQuery
984− { moreLikeThisFieldText :: Text
985− , moreLikeThisFieldFields :: FieldName
986− -- default 0.3 (30%)
987− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
988− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
989− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
990− , moreLikeThisFieldStopWords :: Maybe [StopWord]
991− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
992− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
993− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
994− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
995− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
996− , moreLikeThisFieldBoost :: Maybe Boost
997− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
998− } deriving (Eq, Show)
1000−data MoreLikeThisQuery =
1002− { moreLikeThisText :: Text
1003− , moreLikeThisFields :: Maybe [FieldName]
1004− -- default 0.3 (30%)
1005− , moreLikeThisPercentMatch :: Maybe PercentMatch
1006− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1007− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1008− , moreLikeThisStopWords :: Maybe [StopWord]
1009− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1010− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1011− , moreLikeThisMinWordLength :: Maybe MinWordLength
1012− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1013− , moreLikeThisBoostTerms :: Maybe BoostTerms
1014− , moreLikeThisBoost :: Maybe Boost
1015− , moreLikeThisAnalyzer :: Maybe Analyzer
1016− } deriving (Eq, Show)
1020− { indicesQueryIndices :: [IndexName]
1021− , indicesQuery :: Query
1023− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show)
1025−data HasParentQuery =
1027− { hasParentQueryType :: TypeName
1028− , hasParentQuery :: Query
1029− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1031−data HasChildQuery =
1033− { hasChildQueryType :: TypeName
1034− , hasChildQuery :: Query
1035− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1041− | ScoreTypeNone deriving (Eq, Show)
1044− FuzzyQuery { fuzzyQueryField :: FieldName
1045− , fuzzyQueryValue :: Text
1046− , fuzzyQueryPrefixLength :: PrefixLength
1047− , fuzzyQueryMaxExpansions :: MaxExpansions
1048− , fuzzyQueryFuzziness :: Fuzziness
1049− , fuzzyQueryBoost :: Maybe Boost
1050− } deriving (Eq, Show)
1052−data FuzzyLikeFieldQuery =
1053− FuzzyLikeFieldQuery
1054− { fuzzyLikeField :: FieldName
1055− -- anaphora is good for the soul.
1056− , fuzzyLikeFieldText :: Text
1057− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1058− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1059− , fuzzyLikeFieldFuzziness :: Fuzziness
1060− , fuzzyLikeFieldPrefixLength :: PrefixLength
1061− , fuzzyLikeFieldBoost :: Boost
1062− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1063− } deriving (Eq, Show)
1065−data FuzzyLikeThisQuery =
1067− { fuzzyLikeFields :: [FieldName]
1068− , fuzzyLikeText :: Text
1069− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1070− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1071− , fuzzyLikeFuzziness :: Fuzziness
1072− , fuzzyLikePrefixLength :: PrefixLength
1073− , fuzzyLikeBoost :: Boost
1074− , fuzzyLikeAnalyzer :: Maybe Analyzer
1075− } deriving (Eq, Show)
1077−data FilteredQuery =
1079− { filteredQuery :: Query
1080− , filteredFilter :: Filter } deriving (Eq, Show)
1083− DisMaxQuery { disMaxQueries :: [Query]
1085− , disMaxTiebreaker :: Tiebreaker
1086− , disMaxBoost :: Maybe Boost
1087− } deriving (Eq, Show)
1090− MatchQuery { matchQueryField :: FieldName
1091− , matchQueryQueryString :: QueryString
1092− , matchQueryOperator :: BooleanOperator
1093− , matchQueryZeroTerms :: ZeroTermsQuery
1094− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1095− , matchQueryMatchType :: Maybe MatchQueryType
1096− , matchQueryAnalyzer :: Maybe Analyzer
1097− , matchQueryMaxExpansions :: Maybe MaxExpansions
1098− , matchQueryLenient :: Maybe Lenient
1099− , matchQueryBoost :: Maybe Boost } deriving (Eq, Show)
1101−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1102− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1104−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1105−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1107−data MatchQueryType =
1109− | MatchPhrasePrefix deriving (Eq, Show)
1111−data MultiMatchQuery =
1112− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1113− , multiMatchQueryString :: QueryString
1114− , multiMatchQueryOperator :: BooleanOperator
1115− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1116− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1117− , multiMatchQueryType :: Maybe MultiMatchQueryType
1118− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1119− , multiMatchQueryAnalyzer :: Maybe Analyzer
1120− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1121− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show)
1123−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1124− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1125− make a 'MultiMatchQuery'.
1128−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1129−mkMultiMatchQuery matchFields query =
1130− MultiMatchQuery matchFields query
1131− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1133−data MultiMatchQueryType =
1134− MultiMatchBestFields
1135− | MultiMatchMostFields
1136− | MultiMatchCrossFields
1138− | MultiMatchPhrasePrefix deriving (Eq, Show)
1141− BoolQuery { boolQueryMustMatch :: [Query]
1142− , boolQueryMustNotMatch :: [Query]
1143− , boolQueryShouldMatch :: [Query]
1144− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1145− , boolQueryBoost :: Maybe Boost
1146− , boolQueryDisableCoord :: Maybe DisableCoord
1147− } deriving (Eq, Show)
1149−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1150−mkBoolQuery must mustNot should =
1151− BoolQuery must mustNot should Nothing Nothing Nothing
1153−data BoostingQuery =
1154− BoostingQuery { positiveQuery :: Query
1155− , negativeQuery :: Query
1156− , negativeBoost :: Boost } deriving (Eq, Show)
1158−data CommonTermsQuery =
1159− CommonTermsQuery { commonField :: FieldName
1160− , commonQuery :: QueryString
1161− , commonCutoffFrequency :: CutoffFrequency
1162− , commonLowFreqOperator :: BooleanOperator
1163− , commonHighFreqOperator :: BooleanOperator
1164− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1165− , commonBoost :: Maybe Boost
1166− , commonAnalyzer :: Maybe Analyzer
1167− , commonDisableCoord :: Maybe DisableCoord
1168− } deriving (Eq, Show)
1170−data CommonMinimumMatch =
1171− CommonMinimumMatchHighLow MinimumMatchHighLow
1172− | CommonMinimumMatch MinimumMatch
1173− deriving (Eq, Show)
1175−data MinimumMatchHighLow =
1176− MinimumMatchHighLow { lowFreq :: MinimumMatch
1177− , highFreq :: MinimumMatch } deriving (Eq, Show)
1179−data Filter = AndFilter [Filter] Cache
1180− | OrFilter [Filter] Cache
1181− | NotFilter Filter Cache
1183− | BoolFilter BoolMatch
1184− | ExistsFilter FieldName -- always cached
1185− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1186− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1187− | GeoDistanceRangeFilter GeoPoint DistanceRange
1188− | GeoPolygonFilter FieldName [LatLon]
1189− | IdsFilter MappingName [DocId]
1191− | MissingFilter FieldName Existence NullValue
1192− | PrefixFilter FieldName PrefixValue Cache
1193− | QueryFilter Query Cache
1194− | RangeFilter FieldName RangeValue RangeExecution Cache
1195− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1196− | TermFilter Term Cache
1197− deriving (Eq, Show)
1199−data ZeroTermsQuery = ZeroTermsNone
1200− | ZeroTermsAll deriving (Eq, Show)
1202−data RangeExecution = RangeExecutionIndex
1203− | RangeExecutionFielddata deriving (Eq, Show)
1205−newtype Regexp = Regexp Text deriving (Eq, Show)
1207−data RegexpFlags = AllRegexpFlags
1209− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show)
1211−data RegexpFlag = AnyString
1216− | Interval deriving (Eq, Show)
1218−newtype LessThan = LessThan Double deriving (Eq, Show)
1219−newtype LessThanEq = LessThanEq Double deriving (Eq, Show)
1220−newtype GreaterThan = GreaterThan Double deriving (Eq, Show)
1221−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show)
1223−newtype LessThanD = LessThanD UTCTime deriving (Eq, Show)
1224−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show)
1225−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show)
1226−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show)
1228−data RangeValue = RangeDateLte LessThanEqD
1229− | RangeDateLt LessThanD
1230− | RangeDateGte GreaterThanEqD
1231− | RangeDateGt GreaterThanD
1232− | RangeDateGtLt GreaterThanD LessThanD
1233− | RangeDateGteLte GreaterThanEqD LessThanEqD
1234− | RangeDateGteLt GreaterThanEqD LessThanD
1235− | RangeDateGtLte GreaterThanD LessThanEqD
1236− | RangeDoubleLte LessThanEq
1237− | RangeDoubleLt LessThan
1238− | RangeDoubleGte GreaterThanEq
1239− | RangeDoubleGt GreaterThan
1240− | RangeDoubleGtLt GreaterThan LessThan
1241− | RangeDoubleGteLte GreaterThanEq LessThanEq
1242− | RangeDoubleGteLt GreaterThanEq LessThan
1243− | RangeDoubleGtLte GreaterThan LessThanEq
1244− deriving (Eq, Show)
1246−rangeValueToPair :: RangeValue -> [Pair]
1247−rangeValueToPair rv = case rv of
1248− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1249− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1250− RangeDateLt (LessThanD t) -> ["lt" .= t]
1251− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1252− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1253− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1254− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1255− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1256− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1257− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1258− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1259− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1260− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1261− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1262− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1263− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1265−data Term = Term { termField :: Text
1266− , termValue :: Text } deriving (Eq, Show)
1268−data BoolMatch = MustMatch Term Cache
1269− | MustNotMatch Term Cache
1270− | ShouldMatch [Term] Cache deriving (Eq, Show)
1272−-- "memory" or "indexed"
1273−data GeoFilterType = GeoFilterMemory
1274− | GeoFilterIndexed deriving (Eq, Show)
1276−data LatLon = LatLon { lat :: Double
1277− , lon :: Double } deriving (Eq, Show)
1279−data GeoBoundingBox =
1280− GeoBoundingBox { topLeft :: LatLon
1281− , bottomRight :: LatLon } deriving (Eq, Show)
1283−data GeoBoundingBoxConstraint =
1284− GeoBoundingBoxConstraint { geoBBField :: FieldName
1285− , constraintBox :: GeoBoundingBox
1286− , bbConstraintcache :: Cache
1287− , geoType :: GeoFilterType
1288− } deriving (Eq, Show)
1291− GeoPoint { geoField :: FieldName
1292− , latLon :: LatLon} deriving (Eq, Show)
1294−data DistanceUnit = Miles
1302− | NauticalMiles deriving (Eq, Show)
1304−data DistanceType = Arc
1305− | SloppyArc -- doesn't exist <1.0
1306− | Plane deriving (Eq, Show)
1308−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1309− | NoOptimizeBbox deriving (Eq, Show)
1312− Distance { coefficient :: Double
1313− , unit :: DistanceUnit } deriving (Eq, Show)
1315−data DistanceRange =
1316− DistanceRange { distanceFrom :: Distance
1317− , distanceTo :: Distance } deriving (Eq, Show)
1319−data SearchResult a =
1320− SearchResult { took :: Int
1322− , shards :: ShardResult
1323− , searchHits :: SearchHits a
1324− , aggregations :: Maybe AggregationResults
1325− , scrollId :: Maybe ScrollId } deriving (Eq, Show)
1327−type ScrollId = Text -- Fixme: Newtype
1329−type Score = Maybe Double
1332− SearchHits { hitsTotal :: Int
1333− , maxScore :: Score
1334− , hits :: [Hit a] } deriving (Eq, Show)
1337−instance Monoid (SearchHits a) where
1338− mempty = SearchHits 0 Nothing mempty
1339− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1340− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1344− Hit { hitIndex :: IndexName
1345− , hitType :: MappingName
1346− , hitDocId :: DocId
1347− , hitScore :: Score
1349− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show)
1352− ShardResult { shardTotal :: Int
1353− , shardsSuccessful :: Int
1354− , shardsFailed :: Int } deriving (Eq, Show, Generic)
1356−type HitHighlight = M.Map Text [Text]
1358−showText :: Show a => a -> Text
1359−showText = T.pack . show
1361−type Aggregations = M.Map Text Aggregation
1363−emptyAggregations :: Aggregations
1364−emptyAggregations = M.empty
1366−mkAggregations :: Text -> Aggregation -> Aggregations
1367−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1369−data TermOrder = TermOrder{ termSortField :: Text
1370− , termSortOrder :: SortOrder } deriving (Eq, Show)
1372−data TermInclusion = TermInclusion Text
1373− | TermPattern Text Text deriving (Eq, Show)
1375−data CollectionMode = BreadthFirst
1376− | DepthFirst deriving (Eq, Show)
1378−data ExecutionHint = Ordinals
1380− | GlobalOrdinalsHash
1381− | GlobalOrdinalsLowCardinality
1382− | Map deriving (Eq, Show)
1384−data TimeInterval = Weeks
1388− | Seconds deriving (Eq)
1390−data Interval = Year
1398− | FractionalInterval Float TimeInterval deriving (Eq, Show)
1400−data Aggregation = TermsAgg TermsAggregation
1401− | DateHistogramAgg DateHistogramAggregation
1402− | ValueCountAgg ValueCountAggregation
1403− | FilterAgg FilterAggregation deriving (Eq, Show)
1406−data TermsAggregation = TermsAggregation { term :: Either Text Text
1407− , termInclude :: Maybe TermInclusion
1408− , termExclude :: Maybe TermInclusion
1409− , termOrder :: Maybe TermOrder
1410− , termMinDocCount :: Maybe Int
1411− , termSize :: Maybe Int
1412− , termShardSize :: Maybe Int
1413− , termCollectMode :: Maybe CollectionMode
1414− , termExecutionHint :: Maybe ExecutionHint
1415− , termAggs :: Maybe Aggregations
1416− } deriving (Eq, Show)
1418−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1419− , dateInterval :: Interval
1420− , dateFormat :: Maybe Text
1421− -- pre and post deprecated in 1.5
1422− , datePreZone :: Maybe Text
1423− , datePostZone :: Maybe Text
1424− , datePreOffset :: Maybe Text
1425− , datePostOffset :: Maybe Text
1426− , dateAggs :: Maybe Aggregations
1427− } deriving (Eq, Show)
1429−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1430−data ValueCountAggregation = FieldValueCount FieldName
1431− | ScriptValueCount Script deriving (Eq, Show)
1433−-- | 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.
1434−data FilterAggregation = FilterAggregation { faFilter :: Filter
1435− , faAggs :: Maybe Aggregations} deriving (Eq, Show)
1437−mkTermsAggregation :: Text -> TermsAggregation
1438−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1440−mkTermsScriptAggregation :: Text -> TermsAggregation
1441−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1443−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1444−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1446−instance ToJSON TermOrder where
1447− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1449−instance ToJSON TermInclusion where
1450− toJSON (TermInclusion x) = toJSON x
1451− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1454−instance ToJSON CollectionMode where
1455− toJSON BreadthFirst = "breadth_first"
1456− toJSON DepthFirst = "depth_first"
1458−instance ToJSON ExecutionHint where
1459− toJSON Ordinals = "ordinals"
1460− toJSON GlobalOrdinals = "global_ordinals"
1461− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1462− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1465−instance ToJSON Interval where
1466− toJSON Year = "year"
1467− toJSON Quarter = "quarter"
1468− toJSON Month = "month"
1469− toJSON Week = "week"
1471− toJSON Hour = "hour"
1472− toJSON Minute = "minute"
1473− toJSON Second = "second"
1474− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1476−instance Show TimeInterval where
1483−instance ToJSON Aggregation where
1484− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1485− omitNulls ["terms" .= omitNulls [ toJSON' term,
1486− "include" .= include,
1487− "exclude" .= exclude,
1489− "min_doc_count" .= minDocCount,
1491− "shard_size" .= shardSize,
1492− "collect_mode" .= collectMode,
1493− "execution_hint" .= executionHint
1495− "aggs" .= termAggs ]
1497− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1499− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1500− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1501− "interval" .= interval,
1502− "format" .= format,
1503− "pre_zone" .= preZone,
1504− "post_zone" .= postZone,
1505− "pre_offset" .= preOffset,
1506− "post_offset" .= postOffset
1508− "aggs" .= dateHistoAggs ]
1509− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1510− where v = case a of
1511− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1512− (ScriptValueCount (Script s)) -> object ["script" .= s]
1513− toJSON (FilterAgg (FilterAggregation filt ags)) =
1514− omitNulls [ "filter" .= filt
1517−type AggregationResults = M.Map Text Value
1519−class BucketAggregation a where
1521− docCount :: a -> Int
1522− aggs :: a -> Maybe AggregationResults
1525−data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1527−data TermsResult = TermsResult { termKey :: Text
1528− , termsDocCount :: Int
1529− , termsAggs :: Maybe AggregationResults } deriving (Show)
1531−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1532− , dateKeyStr :: Maybe Text
1533− , dateDocCount :: Int
1534− , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1536−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1537−toTerms t a = M.lookup t a >>= deserialize
1538− where deserialize = parseMaybe parseJSON
1540−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1541−toDateHistogram t a = M.lookup t a >>= deserialize
1542− where deserialize = parseMaybe parseJSON
1544−instance BucketAggregation TermsResult where
1546− docCount = termsDocCount
1549−instance BucketAggregation DateHistogramResult where
1550− key = showText . dateKey
1551− docCount = dateDocCount
1552− aggs = dateHistogramAggs
1554−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1555− parseJSON (Object v) = Bucket <$>
1557− parseJSON _ = mempty
1559−instance FromJSON TermsResult where
1560− parseJSON (Object v) = TermsResult <$>
1562− v .: "doc_count" <*>
1563− v .:? "aggregations"
1564− parseJSON _ = mempty
1566−instance FromJSON DateHistogramResult where
1567− parseJSON (Object v) = DateHistogramResult <$>
1569− v .:? "key_as_string" <*>
1570− v .: "doc_count" <*>
1571− v .:? "aggregations"
1572− parseJSON _ = mempty
1574−instance Monoid Filter where
1575− mempty = IdentityFilter
1576− mappend a b = AndFilter [a, b] defaultCache
1578−instance Seminearring Filter where
1579− a <||> b = OrFilter [a, b] defaultCache
1581−instance ToJSON Filter where
1582− toJSON (AndFilter filters cache) =
1584− object [ "filters" .= fmap toJSON filters
1585− , "_cache" .= cache]]
1587− toJSON (OrFilter filters cache) =
1589− object [ "filters" .= fmap toJSON filters
1590− , "_cache" .= cache]]
1592− toJSON (NotFilter notFilter cache) =
1594− object ["filter" .= notFilter
1595− , "_cache" .= cache]]
1597− toJSON (IdentityFilter) =
1598− object ["match_all" .= object []]
1600− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1601− object ["term" .= object base]
1602− where base = [termFilterField .= termFilterValue,
1605− toJSON (ExistsFilter (FieldName fieldName)) =
1606− object ["exists" .= object
1607− ["field" .= fieldName]]
1609− toJSON (BoolFilter boolMatch) =
1610− object ["bool" .= boolMatch]
1612− toJSON (GeoBoundingBoxFilter bbConstraint) =
1613− object ["geo_bounding_box" .= bbConstraint]
1615− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1616− distance distanceType optimizeBbox cache) =
1617− object ["geo_distance" .=
1618− object ["distance" .= distance
1619− , "distance_type" .= distanceType
1620− , "optimize_bbox" .= optimizeBbox
1621− , distanceGeoField .= geoDistLatLon
1622− , "_cache" .= cache]]
1624− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1625− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1626− object ["geo_distance_range" .=
1627− object ["from" .= geoDistRangeDistFrom
1628− , "to" .= drDistanceTo
1629− , gddrField .= drLatLon]]
1631− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1632− object ["geo_polygon" .=
1633− object [geoPolygonFilterField .=
1634− object ["points" .= fmap toJSON latLons]]]
1636− toJSON (IdsFilter (MappingName mappingName) values) =
1638− object ["type" .= mappingName
1639− , "values" .= fmap unpackId values]]
1641− toJSON (LimitFilter limit) =
1642− object ["limit" .= object ["value" .= limit]]
1644− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1645− object ["missing" .=
1646− object ["field" .= fieldName
1647− , "existence" .= existence
1648− , "null_value" .= nullValue]]
1650− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1651− object ["prefix" .=
1652− object [fieldName .= fieldValue
1653− , "_cache" .= cache]]
1655− toJSON (QueryFilter query False) =
1656− object ["query" .= toJSON query ]
1657− toJSON (QueryFilter query True) =
1658− object ["fquery" .=
1659− object [ "query" .= toJSON query
1660− , "_cache" .= True ]]
1662− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1664− object [ fieldName .= object (rangeValueToPair rangeValue)
1665− , "execution" .= rangeExecution
1666− , "_cache" .= cache]]
1668− toJSON (RegexpFilter (FieldName fieldName)
1669− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1670− object ["regexp" .=
1671− object [fieldName .=
1672− object ["value" .= regexText
1673− , "flags" .= flags]
1674− , "_name" .= cacheName
1675− , "_cache" .= cache
1676− , "_cache_key" .= cacheKey]]
1678−instance ToJSON GeoPoint where
1679− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
1680− object [ geoPointField .= geoPointLatLon ]
1683−instance ToJSON Query where
1684− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
1686− object [termQueryField .= object merged]]
1688− base = [ "value" .= termQueryValue ]
1689− boosted = maybe [] (return . ("boost" .=)) boost
1690− merged = mappend base boosted
1692− toJSON (TermsQuery terms) =
1693− object [ "terms" .= object conjoined ]
1694− where conjoined = [ getTermsField terms .=
1695− fmap (toJSON . getTermValue) (toList terms)]
1696− getTermsField ((Term f _ ) :| _) = f
1697− getTermValue (Term _ v) = v
1698− toJSON (IdsQuery idsQueryMappingName docIds) =
1699− object [ "ids" .= object conjoined ]
1700− where conjoined = [ "type" .= idsQueryMappingName
1701− , "values" .= fmap toJSON docIds ]
1703− toJSON (QueryQueryStringQuery qQueryStringQuery) =
1704− object [ "query_string" .= qQueryStringQuery ]
1706− toJSON (QueryMatchQuery matchQuery) =
1707− object [ "match" .= matchQuery ]
1709− toJSON (QueryMultiMatchQuery multiMatchQuery) =
1710− toJSON multiMatchQuery
1712− toJSON (QueryBoolQuery boolQuery) =
1713− object [ "bool" .= boolQuery ]
1715− toJSON (QueryBoostingQuery boostingQuery) =
1716− object [ "boosting" .= boostingQuery ]
1718− toJSON (QueryCommonTermsQuery commonTermsQuery) =
1719− object [ "common" .= commonTermsQuery ]
1721− toJSON (ConstantScoreFilter csFilter boost) =
1722− object [ "constant_score" .= csFilter
1723− , "boost" .= boost]
1725− toJSON (ConstantScoreQuery query boost) =
1726− object [ "constant_score" .= query
1727− , "boost" .= boost]
1729− toJSON (QueryDisMaxQuery disMaxQuery) =
1730− object [ "dis_max" .= disMaxQuery ]
1732− toJSON (QueryFilteredQuery qFilteredQuery) =
1733− object [ "filtered" .= qFilteredQuery ]
1735− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
1736− object [ "fuzzy_like_this" .= fuzzyQuery ]
1738− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
1739− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
1741− toJSON (QueryFuzzyQuery fuzzyQuery) =
1742− object [ "fuzzy" .= fuzzyQuery ]
1744− toJSON (QueryHasChildQuery childQuery) =
1745− object [ "has_child" .= childQuery ]
1747− toJSON (QueryHasParentQuery parentQuery) =
1748− object [ "has_parent" .= parentQuery ]
1750− toJSON (QueryIndicesQuery qIndicesQuery) =
1751− object [ "indices" .= qIndicesQuery ]
1753− toJSON (MatchAllQuery boost) =
1754− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
1756− toJSON (QueryMoreLikeThisQuery query) =
1757− object [ "more_like_this" .= query ]
1759− toJSON (QueryMoreLikeThisFieldQuery query) =
1760− object [ "more_like_this_field" .= query ]
1762− toJSON (QueryNestedQuery query) =
1763− object [ "nested" .= query ]
1765− toJSON (QueryPrefixQuery query) =
1766− object [ "prefix" .= query ]
1768− toJSON (QueryRangeQuery query) =
1769− object [ "range" .= query ]
1771− toJSON (QueryRegexpQuery query) =
1772− object [ "regexp" .= query ]
1774− toJSON (QuerySimpleQueryStringQuery query) =
1775− object [ "simple_query_string" .= query ]
1778−omitNulls :: [(Text, Value)] -> Value
1779−omitNulls = object . filter notNull where
1780− notNull (_, Null) = False
1781− notNull (_, Array a) = (not . V.null) a
1785−instance ToJSON SimpleQueryStringQuery where
1786− toJSON SimpleQueryStringQuery {..} =
1787− omitNulls (base ++ maybeAdd)
1788− where base = [ "query" .= simpleQueryStringQuery ]
1789− maybeAdd = [ "fields" .= simpleQueryStringField
1790− , "default_operator" .= simpleQueryStringOperator
1791− , "analyzer" .= simpleQueryStringAnalyzer
1792− , "flags" .= simpleQueryStringFlags
1793− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
1794− , "locale" .= simpleQueryStringLocale ]
1797−instance ToJSON FieldOrFields where
1798− toJSON (FofField fieldName) =
1800− toJSON (FofFields fieldNames) =
1803−instance ToJSON SimpleQueryFlag where
1804− toJSON SimpleQueryAll = "ALL"
1805− toJSON SimpleQueryNone = "NONE"
1806− toJSON SimpleQueryAnd = "AND"
1807− toJSON SimpleQueryOr = "OR"
1808− toJSON SimpleQueryPrefix = "PREFIX"
1809− toJSON SimpleQueryPhrase = "PHRASE"
1810− toJSON SimpleQueryPrecedence = "PRECEDENCE"
1811− toJSON SimpleQueryEscape = "ESCAPE"
1812− toJSON SimpleQueryWhitespace = "WHITESPACE"
1813− toJSON SimpleQueryFuzzy = "FUZZY"
1814− toJSON SimpleQueryNear = "NEAR"
1815− toJSON SimpleQuerySlop = "SLOP"
1818−instance ToJSON RegexpQuery where
1819− toJSON (RegexpQuery (FieldName rqQueryField)
1820− (Regexp regexpQueryQuery) rqQueryFlags
1822− object [ rqQueryField .= omitNulls base ]
1823− where base = [ "value" .= regexpQueryQuery
1824− , "flags" .= rqQueryFlags
1825− , "boost" .= rqQueryBoost ]
1828−instance ToJSON QueryStringQuery where
1829− toJSON (QueryStringQuery qsQueryString
1830− qsDefaultField qsOperator
1831− qsAnalyzer qsAllowWildcard
1832− qsLowercaseExpanded qsEnablePositionIncrements
1833− qsFuzzyMaxExpansions qsFuzziness
1834− qsFuzzyPrefixLength qsPhraseSlop
1835− qsBoost qsAnalyzeWildcard
1836− qsGeneratePhraseQueries qsMinimumShouldMatch
1837− qsLenient qsLocale) =
1840− base = [ "query" .= qsQueryString
1841− , "default_field" .= qsDefaultField
1842− , "default_operator" .= qsOperator
1843− , "analyzer" .= qsAnalyzer
1844− , "allow_leading_wildcard" .= qsAllowWildcard
1845− , "lowercase_expanded_terms" .= qsLowercaseExpanded
1846− , "enable_position_increments" .= qsEnablePositionIncrements
1847− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
1848− , "fuzziness" .= qsFuzziness
1849− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
1850− , "phrase_slop" .= qsPhraseSlop
1851− , "boost" .= qsBoost
1852− , "analyze_wildcard" .= qsAnalyzeWildcard
1853− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
1854− , "minimum_should_match" .= qsMinimumShouldMatch
1855− , "lenient" .= qsLenient
1856− , "locale" .= qsLocale ]
1859−instance ToJSON RangeQuery where
1860− toJSON (RangeQuery (FieldName fieldName) range boost) =
1861− object [ fieldName .= conjoined ]
1862− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
1865−instance ToJSON PrefixQuery where
1866− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
1867− object [ fieldName .= omitNulls base ]
1868− where base = [ "value" .= queryValue
1869− , "boost" .= boost ]
1872−instance ToJSON NestedQuery where
1873− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
1874− object [ "path" .= nqPath
1875− , "score_mode" .= nqScoreType
1876− , "query" .= nqQuery ]
1879−instance ToJSON MoreLikeThisFieldQuery where
1880− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
1881− percent mtf mqt stopwords mindf maxdf
1882− minwl maxwl boostTerms boost analyzer) =
1883− object [ fieldName .= omitNulls base ]
1884− where base = [ "like_text" .= text
1885− , "percent_terms_to_match" .= percent
1886− , "min_term_freq" .= mtf
1887− , "max_query_terms" .= mqt
1888− , "stop_words" .= stopwords
1889− , "min_doc_freq" .= mindf
1890− , "max_doc_freq" .= maxdf
1891− , "min_word_length" .= minwl
1892− , "max_word_length" .= maxwl
1893− , "boost_terms" .= boostTerms
1895− , "analyzer" .= analyzer ]
1898−instance ToJSON MoreLikeThisQuery where
1899− toJSON (MoreLikeThisQuery text fields percent
1900− mtf mqt stopwords mindf maxdf
1901− minwl maxwl boostTerms boost analyzer) =
1903− where base = [ "like_text" .= text
1904− , "fields" .= fields
1905− , "percent_terms_to_match" .= percent
1906− , "min_term_freq" .= mtf
1907− , "max_query_terms" .= mqt
1908− , "stop_words" .= stopwords
1909− , "min_doc_freq" .= mindf
1910− , "max_doc_freq" .= maxdf
1911− , "min_word_length" .= minwl
1912− , "max_word_length" .= maxwl
1913− , "boost_terms" .= boostTerms
1915− , "analyzer" .= analyzer ]
1918−instance ToJSON IndicesQuery where
1919− toJSON (IndicesQuery indices query noMatch) =
1920− omitNulls [ "indices" .= indices
1921− , "no_match_query" .= noMatch
1922− , "query" .= query ]
1925−instance ToJSON HasParentQuery where
1926− toJSON (HasParentQuery queryType query scoreType) =
1927− omitNulls [ "parent_type" .= queryType
1928− , "score_type" .= scoreType
1929− , "query" .= query ]
1932−instance ToJSON HasChildQuery where
1933− toJSON (HasChildQuery queryType query scoreType) =
1934− omitNulls [ "query" .= query
1935− , "score_type" .= scoreType
1936− , "type" .= queryType ]
1939−instance ToJSON FuzzyQuery where
1940− toJSON (FuzzyQuery (FieldName fieldName) queryText
1941− prefixLength maxEx fuzziness boost) =
1942− object [ fieldName .= omitNulls base ]
1943− where base = [ "value" .= queryText
1944− , "fuzziness" .= fuzziness
1945− , "prefix_length" .= prefixLength
1947− , "max_expansions" .= maxEx ]
1950−instance ToJSON FuzzyLikeFieldQuery where
1951− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
1952− fieldText maxTerms ignoreFreq fuzziness prefixLength
1954− object [ fieldName .=
1955− omitNulls [ "like_text" .= fieldText
1956− , "max_query_terms" .= maxTerms
1957− , "ignore_tf" .= ignoreFreq
1958− , "fuzziness" .= fuzziness
1959− , "prefix_length" .= prefixLength
1960− , "analyzer" .= analyzer
1961− , "boost" .= boost ]]
1964−instance ToJSON FuzzyLikeThisQuery where
1965− toJSON (FuzzyLikeThisQuery fields text maxTerms
1966− ignoreFreq fuzziness prefixLength boost analyzer) =
1968− where base = [ "fields" .= fields
1969− , "like_text" .= text
1970− , "max_query_terms" .= maxTerms
1971− , "ignore_tf" .= ignoreFreq
1972− , "fuzziness" .= fuzziness
1973− , "prefix_length" .= prefixLength
1974− , "analyzer" .= analyzer
1975− , "boost" .= boost ]
1978−instance ToJSON FilteredQuery where
1979− toJSON (FilteredQuery query fFilter) =
1980− object [ "query" .= query
1981− , "filter" .= fFilter ]
1984−instance ToJSON DisMaxQuery where
1985− toJSON (DisMaxQuery queries tiebreaker boost) =
1987− where base = [ "queries" .= queries
1989− , "tie_breaker" .= tiebreaker ]
1992−instance ToJSON CommonTermsQuery where
1993− toJSON (CommonTermsQuery (FieldName fieldName)
1994− (QueryString query) cf lfo hfo msm
1995− boost analyzer disableCoord) =
1996− object [fieldName .= omitNulls base ]
1997− where base = [ "query" .= query
1998− , "cutoff_frequency" .= cf
1999− , "low_freq_operator" .= lfo
2000− , "minimum_should_match" .= msm
2002− , "analyzer" .= analyzer
2003− , "disable_coord" .= disableCoord
2004− , "high_freq_operator" .= hfo ]
2007−instance ToJSON CommonMinimumMatch where
2008− toJSON (CommonMinimumMatch mm) = toJSON mm
2009− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2010− object [ "low_freq" .= lowF
2011− , "high_freq" .= highF ]
2013−instance ToJSON BoostingQuery where
2014− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2015− object [ "positive" .= bqPositiveQuery
2016− , "negative" .= bqNegativeQuery
2017− , "negative_boost" .= bqNegativeBoost ]
2020−instance ToJSON BoolQuery where
2021− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2023− where base = [ "must" .= mustM
2024− , "must_not" .= notM
2025− , "should" .= shouldM
2026− , "minimum_should_match" .= bqMin
2028− , "disable_coord" .= disableCoord ]
2031−instance ToJSON MatchQuery where
2032− toJSON (MatchQuery (FieldName fieldName)
2033− (QueryString mqQueryString) booleanOperator
2034− zeroTermsQuery cutoffFrequency matchQueryType
2035− analyzer maxExpansions lenient boost) =
2036− object [ fieldName .= omitNulls base ]
2037− where base = [ "query" .= mqQueryString
2038− , "operator" .= booleanOperator
2039− , "zero_terms_query" .= zeroTermsQuery
2040− , "cutoff_frequency" .= cutoffFrequency
2041− , "type" .= matchQueryType
2042− , "analyzer" .= analyzer
2043− , "max_expansions" .= maxExpansions
2044− , "lenient" .= lenient
2045− , "boost" .= boost ]
2048−instance ToJSON MultiMatchQuery where
2049− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2050− ztQ tb mmqt cf analyzer maxEx lenient) =
2051− object ["multi_match" .= omitNulls base]
2052− where base = [ "fields" .= fmap toJSON fields
2054− , "operator" .= boolOp
2055− , "zero_terms_query" .= ztQ
2056− , "tiebreaker" .= tb
2058− , "cutoff_frequency" .= cf
2059− , "analyzer" .= analyzer
2060− , "max_expansions" .= maxEx
2061− , "lenient" .= lenient ]
2064−instance ToJSON MultiMatchQueryType where
2065− toJSON MultiMatchBestFields = "best_fields"
2066− toJSON MultiMatchMostFields = "most_fields"
2067− toJSON MultiMatchCrossFields = "cross_fields"
2068− toJSON MultiMatchPhrase = "phrase"
2069− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2071−instance ToJSON BooleanOperator where
2072− toJSON And = String "and"
2073− toJSON Or = String "or"
2075−instance ToJSON ZeroTermsQuery where
2076− toJSON ZeroTermsNone = String "none"
2077− toJSON ZeroTermsAll = String "all"
2079−instance ToJSON MatchQueryType where
2080− toJSON MatchPhrase = "phrase"
2081− toJSON MatchPhrasePrefix = "phrase_prefix"
2083−instance ToJSON FieldName where
2084− toJSON (FieldName fieldName) = String fieldName
2086−instance ToJSON ReplicaCount
2087−instance ToJSON ShardCount
2088−instance ToJSON CutoffFrequency
2089−instance ToJSON Analyzer
2090−instance ToJSON MaxExpansions
2091−instance ToJSON Lenient
2092−instance ToJSON Boost
2093−instance ToJSON Version
2094−instance ToJSON Tiebreaker
2095−instance ToJSON MinimumMatch
2096−instance ToJSON DisableCoord
2097−instance ToJSON PrefixLength
2098−instance ToJSON Fuzziness
2099−instance ToJSON IgnoreTermFrequency
2100−instance ToJSON MaxQueryTerms
2101−instance ToJSON TypeName
2102−instance ToJSON IndexName
2103−instance ToJSON TemplateName
2104−instance ToJSON TemplatePattern
2105−instance ToJSON BoostTerms
2106−instance ToJSON MaxWordLength
2107−instance ToJSON MinWordLength
2108−instance ToJSON MaxDocFrequency
2109−instance ToJSON MinDocFrequency
2110−instance ToJSON PhraseSlop
2111−instance ToJSON StopWord
2112−instance ToJSON QueryPath
2113−instance ToJSON MinimumTermFrequency
2114−instance ToJSON PercentMatch
2115−instance ToJSON MappingName
2116−instance ToJSON DocId
2117−instance ToJSON QueryString
2118−instance ToJSON AllowLeadingWildcard
2119−instance ToJSON LowercaseExpanded
2120−instance ToJSON AnalyzeWildcard
2121−instance ToJSON GeneratePhraseQueries
2122−instance ToJSON Locale
2123−instance ToJSON EnablePositionIncrements
2124−instance FromJSON Version
2125−instance FromJSON IndexName
2126−instance FromJSON MappingName
2127−instance FromJSON DocId
2130−instance FromJSON Status where
2131− parseJSON (Object v) = Status <$>
2137− parseJSON _ = empty
2140−instance ToJSON IndexSettings where
2141− toJSON (IndexSettings s r) = object ["settings" .=
2143− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2147−instance ToJSON IndexTemplate where
2148− toJSON (IndexTemplate p s m) = merge
2149− (object [ "template" .= p
2150− , "mappings" .= foldl' merge (object []) m
2154− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
2156− merge _ _ = undefined
2158−instance (FromJSON a) => FromJSON (EsResult a) where
2159− parseJSON jsonVal@(Object v) = do
2160− found <- v .:? "found" .!= False
2162− then parseJSON jsonVal
2163− else return Nothing
2164− EsResult <$> v .: "_index" <*>
2168− parseJSON _ = empty
2170−instance (FromJSON a) => FromJSON (EsResultFound a) where
2171− parseJSON (Object v) = EsResultFound <$>
2172− v .: "_version" <*>
2174− parseJSON _ = empty
2176−instance ToJSON Search where
2177− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
2178− omitNulls [ "query" .= query
2179− , "filter" .= sFilter
2181− , "aggregations" .= searchAggs
2182− , "highlight" .= highlight
2185− , "track_scores" .= sTrackSortScores
2186− , "fields" .= sFields
2187− , "_source" .= sSource]
2190instance ToJSON Source where
490instance ToJSON Source where
2191 toJSON NoSource = toJSON False
491 toJSON NoSource = toJSON False
2192 toJSON (SourcePatterns patterns) = toJSON patterns
492 toJSON (SourcePatterns patterns) = toJSON patterns
2193− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
495+data PatternOrPatterns = PopPattern Pattern
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
2195instance ToJSON PatternOrPatterns where
498instance ToJSON PatternOrPatterns where
2196 toJSON (PopPattern pattern) = toJSON pattern
499 toJSON (PopPattern pattern) = toJSON pattern
2197 toJSON (PopPatterns patterns) = toJSON patterns
500 toJSON (PopPatterns patterns) = toJSON patterns
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
2199instance ToJSON Include where
505instance ToJSON Include where
2200 toJSON (Include patterns) = toJSON patterns
506 toJSON (Include patterns) = toJSON patterns
2202instance ToJSON Exclude where
508instance ToJSON Exclude where
2203 toJSON (Exclude patterns) = toJSON patterns
509 toJSON (Exclude patterns) = toJSON patterns
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
2205instance ToJSON Pattern where
513instance ToJSON Pattern where
2206 toJSON (Pattern pattern) = toJSON pattern
514 toJSON (Pattern pattern) = toJSON pattern
2208−
516+data SearchResult a =
2209−instance ToJSON FieldHighlight where
517+ SearchResult { took :: Int
2210− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
518+ , timedOut :: Bool
2211− object [ fName .= fSettings ]
519+ , shards :: ShardResult
2212− toJSON (FieldHighlight (FieldName fName) Nothing) =
520+ , searchHits :: SearchHits a
2213− object [ fName .= emptyObject ]
521+ , aggregations :: Maybe AggregationResults
2214−
522+ , scrollId :: Maybe ScrollId
2215−instance ToJSON Highlights where
523+ -- ^ Only one Suggestion request / response per
2216− toJSON (Highlights global fields) =
524+ -- Search is supported.
2217− omitNulls (("fields" .= fields)
525+ , suggest :: Maybe NamedSuggestionResponse
2218− : highlightSettingsPairs global)
526+ }
2219−
527+ deriving (Eq, Show)
2220−instance ToJSON HighlightSettings where
2221− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
2223−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
2224−highlightSettingsPairs Nothing = []
2225−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
2226−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
2227−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
2230−plainHighPairs :: Maybe PlainHighlight -> [Pair]
2231−plainHighPairs Nothing = []
2232−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
2233− [ "type" .= String "plain"]
2234− ++ commonHighlightPairs plCom
2235− ++ nonPostingsToPairs plNonPost
2237−postHighPairs :: Maybe PostingsHighlight -> [Pair]
2238−postHighPairs Nothing = []
2239−postHighPairs (Just (PostingsHighlight pCom)) =
2240− ("type" .= String "postings")
2241− : commonHighlightPairs pCom
2243−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
2244−fastVectorHighPairs Nothing = []
2245−fastVectorHighPairs (Just
2246− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
2247− fvBoundMaxScan fvFragOff fvMatchedFields
2249− [ "type" .= String "fvh"
2250− , "boundary_chars" .= fvBoundChars
2251− , "boundary_max_scan" .= fvBoundMaxScan
2252− , "fragment_offset" .= fvFragOff
2253− , "matched_fields" .= fvMatchedFields
2254− , "phraseLimit" .= fvPhraseLim]
2255− ++ commonHighlightPairs fvCom
2256− ++ nonPostingsToPairs fvNonPostSettings
2258−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
2259−commonHighlightPairs Nothing = []
2260−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
2261− chNoMatchSize chHighlightQuery
2262− chRequireFieldMatch)) =
2263− [ "order" .= chScore
2264− , "force_source" .= chForceSource
2265− , "encoder" .= chEncoder
2266− , "no_match_size" .= chNoMatchSize
2267− , "highlight_query" .= chHighlightQuery
2268− , "require_fieldMatch" .= chRequireFieldMatch]
2269− ++ highlightTagToPairs chTag
2272−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
2273−nonPostingsToPairs Nothing = []
2274−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
2275− [ "fragment_size" .= npFragSize
2276− , "number_of_fragments" .= npNumOfFrags]
2280−instance ToJSON HighlightEncoder where
2281− toJSON DefaultEncoder = String "default"
2282− toJSON HTMLEncoder = String "html"
2284−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
2285−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
2286−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
2287− , "post_tags" .= post]
2288−highlightTagToPairs Nothing = []
2290−instance ToJSON SortSpec where
2291− toJSON (DefaultSortSpec
2292− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
2293− dsSortMode dsMissingSort dsNestedFilter)) =
2294− object [dsSortFieldName .= omitNulls base] where
2295− base = [ "order" .= dsSortOrder
2296− , "ignore_unmapped" .= dsIgnoreUnmapped
2297− , "mode" .= dsSortMode
2298− , "missing" .= dsMissingSort
2299− , "nested_filter" .= dsNestedFilter ]
2301− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
2302− object [ "unit" .= units
2303− , field .= gdsLatLon
2304− , "order" .= gdsSortOrder ]
2307−instance ToJSON SortOrder where
2308− toJSON Ascending = String "asc"
2309− toJSON Descending = String "desc"
2312−instance ToJSON SortMode where
2313− toJSON SortMin = String "min"
2314− toJSON SortMax = String "max"
2315− toJSON SortSum = String "sum"
2316− toJSON SortAvg = String "avg"
2319−instance ToJSON Missing where
2320− toJSON LastMissing = String "_last"
2321− toJSON FirstMissing = String "_first"
2322− toJSON (CustomMissing txt) = String txt
2325−instance ToJSON ScoreType where
2326− toJSON ScoreTypeMax = "max"
2327− toJSON ScoreTypeAvg = "avg"
2328− toJSON ScoreTypeSum = "sum"
2329− toJSON ScoreTypeNone = "none"
2332−instance ToJSON Distance where
2333− toJSON (Distance dCoefficient dUnit) =
2334− String boltedTogether where
2335− coefText = showText dCoefficient
2336− (String unitText) = toJSON dUnit
2337− boltedTogether = mappend coefText unitText
2340−instance ToJSON DistanceUnit where
2341− toJSON Miles = String "mi"
2342− toJSON Yards = String "yd"
2343− toJSON Feet = String "ft"
2344− toJSON Inches = String "in"
2345− toJSON Kilometers = String "km"
2346− toJSON Meters = String "m"
2347− toJSON Centimeters = String "cm"
2348− toJSON Millimeters = String "mm"
2349− toJSON NauticalMiles = String "nmi"
2352−instance ToJSON DistanceType where
2353− toJSON Arc = String "arc"
2354− toJSON SloppyArc = String "sloppy_arc"
2355− toJSON Plane = String "plane"
2358−instance ToJSON OptimizeBbox where
2359− toJSON NoOptimizeBbox = String "none"
2360− toJSON (OptimizeGeoFilterType gft) = toJSON gft
2363−instance ToJSON GeoBoundingBoxConstraint where
2364− toJSON (GeoBoundingBoxConstraint
2365− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
2366− object [gbbcGeoBBField .= gbbcConstraintBox
2367− , "_cache" .= cache
2371−instance ToJSON GeoFilterType where
2372− toJSON GeoFilterMemory = String "memory"
2373− toJSON GeoFilterIndexed = String "indexed"
2376−instance ToJSON GeoBoundingBox where
2377− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
2378− object ["top_left" .= gbbTopLeft
2379− , "bottom_right" .= gbbBottomRight]
2382−instance ToJSON LatLon where
2383− toJSON (LatLon lLat lLon) =
2384− object ["lat" .= lLat
2388−-- index for smaller ranges, fielddata for longer ranges
2389−instance ToJSON RangeExecution where
2390− toJSON RangeExecutionIndex = "index"
2391− toJSON RangeExecutionFielddata = "fielddata"
2394−instance ToJSON RegexpFlags where
2395− toJSON AllRegexpFlags = String "ALL"
2396− toJSON NoRegexpFlags = String "NONE"
2397− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
2398− where flagStrs = map flagStr . nub $ h:fs
2399− flagStr AnyString = "ANYSTRING"
2400− flagStr Automaton = "AUTOMATON"
2401− flagStr Complement = "COMPLEMENT"
2402− flagStr Empty = "EMPTY"
2403− flagStr Intersection = "INTERSECTION"
2404− flagStr Interval = "INTERVAL"
2406−instance ToJSON Term where
2407− toJSON (Term field value) = object ["term" .= object
2411−instance ToJSON BoolMatch where
2412− toJSON (MustMatch term cache) = object ["must" .= term,
2414− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
2416− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
2420instance (FromJSON a) => FromJSON (SearchResult a) where
529instance (FromJSON a) => FromJSON (SearchResult a) where
2421 parseJSON (Object v) = SearchResult <$>
530 parseJSON (Object v) = SearchResult <$>
@@ -2424,52 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
2424 v .: "_shards" <*>
533 v .: "_shards" <*>
2425 v .: "hits" <*>
534 v .: "hits" <*>
2426 v .:? "aggregations" <*>
535 v .:? "aggregations" <*>
2427− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
2428− parseJSON _ = empty
537+ v .:? "suggest"
2430−instance (FromJSON a) => FromJSON (SearchHits a) where
2431− parseJSON (Object v) = SearchHits <$>
2433− v .: "max_score" <*>
2435 parseJSON _ = empty
538 parseJSON _ = empty
2437−instance (FromJSON a) => FromJSON (Hit a) where
540+newtype ScrollId =
2438− parseJSON (Object v) = Hit <$>
541+ ScrollId Text
2439− v .: "_index" <*>
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
2445− parseJSON _ = empty
2447−instance FromJSON ShardResult where
2448− parseJSON (Object v) = ShardResult <$>
2450− v .: "successful" <*>
2452− parseJSON _ = empty
2455−instance FromJSON DocVersion where
2458− maybe (fail "DocVersion out of range") return $ mkDocVersion i
2460−instance Bounded DocVersion where
2461− minBound = DocVersion 1
2462− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
2464−instance Enum DocVersion where
2466− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
2467− | otherwise = succError "DocVersion"
2469− | x /= minBound = DocVersion (pred $ docVersionNumber x)
2470− | otherwise = predError "DocVersion"
2472− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
2473− fromEnum = docVersionNumber
2474− enumFrom = boundedEnumFrom
2475− enumFromThen = boundedEnumFromThen