@@ -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,24 +42,41 @@ 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(..)
60 , AllocationPolicy(..)
73 , AllocationPolicy(..)
61 , ReplicaBounds(..)
75 , ReplicaBounds(..)
62 , Bytes(..)
76 , Bytes(..)
63 , FSType(..)
80 , FSType(..)
64 , InitialShardCount(..)
81 , InitialShardCount(..)
65 , NodeAttrFilter(..)
82 , NodeAttrFilter(..)
@@ -70,6 +87,18 @@ module Database.Bloodhound.Types
71 , EsResult(..)
88 , EsResult(..)
72 , EsResultFound(..)
89 , EsResultFound(..)
91+ , EsProtocolException(..)
94+ , IndexAliasAction(..)
95+ , IndexAliasCreate(..)
96+ , IndexAliasSummary(..)
97+ , IndexAliasesSummary(..)
99+ , SearchAliasRouting(..)
100+ , IndexAliasRouting(..)
73 , DocVersion
102 , DocVersion
74 , ExternalDocVersion(..)
103 , ExternalDocVersion(..)
75 , VersionControl(..)
104 , VersionControl(..)
@@ -79,7 +108,7 @@ module Database.Bloodhound.Types
79 , Search(..)
108 , Search(..)
80 , SearchType(..)
109 , SearchType(..)
81 , SearchResult(..)
110 , SearchResult(..)
82− , ScrollId
111+ , ScrollId(..)
83 , SearchHits(..)
112 , SearchHits(..)
84 , TrackSortScores
113 , TrackSortScores
85 , From(..)
114 , From(..)
@@ -91,8 +120,8 @@ module Database.Bloodhound.Types
91 , Pattern(..)
120 , Pattern(..)
92 , ShardResult(..)
121 , ShardResult(..)
93 , Hit(..)
122 , Hit(..)
94 , Filter(..)
124 , Filter(..)
96 , BoolMatch(..)
125 , BoolMatch(..)
97 , Term(..)
126 , Term(..)
98 , GeoPoint(..)
127 , GeoPoint(..)
@@ -119,8 +148,22 @@ module Database.Bloodhound.Types
119 , RegexpFlags(..)
148 , RegexpFlags(..)
120 , RegexpFlag(..)
149 , RegexpFlag(..)
121 , FieldName(..)
150 , FieldName(..)
122 , Script(..)
154 , Script(..)
155+ , ScriptLanguage(..)
123 , IndexName(..)
161 , IndexName(..)
162+ , IndexSelection(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
124 , TemplateName(..)
167 , TemplateName(..)
125 , TemplatePattern(..)
168 , TemplatePattern(..)
126 , MappingName(..)
169 , MappingName(..)
@@ -144,8 +187,19 @@ module Database.Bloodhound.Types
144 , BoolQuery(..)
187 , BoolQuery(..)
145 , BoostingQuery(..)
188 , BoostingQuery(..)
146 , CommonTermsQuery(..)
189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
198+ , FieldValueFactor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
147 , DisMaxQuery(..)
202 , DisMaxQuery(..)
149 , FuzzyLikeThisQuery(..)
203 , FuzzyLikeThisQuery(..)
150 , FuzzyLikeFieldQuery(..)
204 , FuzzyLikeFieldQuery(..)
151 , FuzzyQuery(..)
205 , FuzzyQuery(..)
@@ -161,10 +215,16 @@ module Database.Bloodhound.Types
161 , RangeQuery(..)
215 , RangeQuery(..)
162 , RegexpQuery(..)
216 , RegexpQuery(..)
163 , QueryString(..)
217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
164 , BooleanOperator(..)
221 , BooleanOperator(..)
165 , ZeroTermsQuery(..)
222 , ZeroTermsQuery(..)
166 , CutoffFrequency(..)
223 , CutoffFrequency(..)
167 , Analyzer(..)
224 , Analyzer(..)
168 , MaxExpansions(..)
228 , MaxExpansions(..)
169 , Lenient(..)
229 , Lenient(..)
170 , MatchQueryType(..)
230 , MatchQueryType(..)
@@ -211,16 +271,118 @@ module Database.Bloodhound.Types
211 , CollectionMode(..)
271 , CollectionMode(..)
212 , TermOrder(..)
272 , TermOrder(..)
213 , 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 (..)
215 , Aggregation(..)
364 , Aggregation(..)
216 , Aggregations
365 , Aggregations
217 , AggregationResults
366 , AggregationResults
218 , Bucket(..)
368 , Bucket(..)
219 , BucketAggregation(..)
369 , BucketAggregation(..)
220 , TermsAggregation(..)
370 , TermsAggregation(..)
371+ , MissingAggregation(..)
221 , ValueCountAggregation(..)
372 , ValueCountAggregation(..)
222 , FilterAggregation(..)
373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
223 , DateHistogramAggregation(..)
376 , DateHistogramAggregation(..)
377+ , DateRangeAggregation(..)
378+ , DateRangeAggRange(..)
380+ , DateMathAnchor(..)
381+ , DateMathModifier(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
225 , Highlights(..)
387 , Highlights(..)
226 , FieldHighlight(..)
388 , FieldHighlight(..)
@@ -234,573 +396,36 @@ module Database.Bloodhound.Types
234 , HighlightTag(..)
396 , HighlightTag(..)
235 , HitHighlight
397 , HitHighlight
237 , TermsResult(..)
400 , TermsResult(..)
238 , DateHistogramResult(..)
401 , DateHistogramResult(..)
239− ) where
402+ , DateRangeResult(..)
240−
403+ , TopHitResult(..)
241−import Control.Applicative
404+
242−import Control.Monad.Catch
405+ , EsUsername(..)
243−import Control.Monad.Except
406+ , EsPassword(..)
244−import Control.Monad.Reader
407+
245−import Control.Monad.State
408+ , Analysis(..)
246−import Control.Monad.Writer
409+ , AnalyzerDefinition(..)
247−import Data.Aeson
410+ , TokenizerDefinition(..)
248−import Data.Aeson.Types (Pair, emptyObject, parseMaybe)
411+ , TokenFilterDefinition(..)
249−import qualified Data.ByteString.Lazy.Char8 as L
412+ , CharFilterDefinition(..)
250−import qualified Data.HashMap.Strict as HM (union)
413+ , Ngram(..)
251−import Data.List (foldl', nub)
414+ , TokenChar(..)
252−import Data.List.NonEmpty (NonEmpty (..), toList)
415+ , Shingle(..)
253−import qualified Data.Map.Strict as M
416+ , Language(..)
254−import Data.Maybe
417+ ) where
255−import Data.Text (Text)
418+
256−import qualified Data.Text as T
419+import Bloodhound.Import
257−import Data.Time.Clock (UTCTime, NominalDiffTime)
420+
258−import qualified Data.Vector as V
421+import Database.Bloodhound.Internal.Aggregation
259−import GHC.Enum
422+import Database.Bloodhound.Internal.Analysis
260−import GHC.Generics (Generic)
423+import Database.Bloodhound.Internal.Client
261−import Network.HTTP.Client
424+import Database.Bloodhound.Internal.Highlight
262−import qualified Network.HTTP.Types.Method as NHTM
425+import Database.Bloodhound.Internal.Newtypes
263−
426+import Database.Bloodhound.Internal.Query
264−import Database.Bloodhound.Types.Class
427+import Database.Bloodhound.Internal.Sort
265−
428+import Database.Bloodhound.Internal.Suggest
267−-- >>> :set -XOverloadedStrings
268−-- >>> import Database.Bloodhound
269−-- >>> let testServer = (Server "http://localhost:9200")
270−-- >>> let testIndex = IndexName "twitter"
271−-- >>> let testMapping = MappingName "tweet"
272−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
274−-- defaultIndexSettings is exported by Database.Bloodhound as well
275−-- no trailing slashes in servers, library handles building the path.
277−{-| Common environment for Elasticsearch calls. Connections will be
278− pipelined according to the provided HTTP connection manager.
280−data BHEnv = BHEnv { bhServer :: Server
281− , bhManager :: Manager
284−{-| All API calls to Elasticsearch operate within
285− MonadBH. The idea is that it can be easily embedded in your
286− own monad transformer stack. A default instance for a ReaderT and
287− alias 'BH' is provided for the simple case.
289−class (Functor m, Applicative m, MonadIO m) => MonadBH m where
292−newtype BH m a = BH {
293− unBH :: ReaderT BHEnv m a
294− } deriving ( Functor
308−instance MonadTrans BH where
311−instance (MonadReader r m) => MonadReader r (BH m) where
313− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
316−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
317− getBHEnv = BH getBHEnv
320−instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where
323−runBH :: BHEnv -> BH m a -> m a
324−runBH e f = runReaderT (unBH f) e
326−{-| 'Version' is embedded in 'Status' -}
327−data Version = Version { number :: Text
328− , build_hash :: Text
329− , build_timestamp :: UTCTime
330− , build_snapshot :: Bool
331− , lucene_version :: Text } deriving (Eq, Show, Generic)
333−{-| 'Status' is a data type for describing the JSON body returned by
334− Elasticsearch when you query its status. This was deprecated in 1.2.0.
336− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
339−data Status = Status { ok :: Maybe Bool
342− , version :: Version
343− , tagline :: Text } deriving (Eq, Show)
345−{-| 'IndexSettings' is used to configure the shards and replicas when you create
346− an Elasticsearch Index.
348− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
352− IndexSettings { indexShards :: ShardCount
353− , indexReplicas :: ReplicaCount } deriving (Eq, Show)
355−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
356−defaultIndexSettings :: IndexSettings
357−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
359−{-| 'IndexSettingUpdate' is used to update an index' settings piecemeal.
361− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
363−data IndexSettingUpdate = NumberOfReplicas Int
364− | AutoExpandReplicas ReplicaBounds
365− | BlocksReadOnly Bool
368− | BlocksMetaData Bool
369− | RefreshInterval NominalDiffTime
370− | IndexConcurrency Int
371− | FailOnMergeFailure Bool
372− | TranslogFlushThresholdOps Int
373− | TranslogFlushThresholdSize Bytes
374− | TranslogFlushThresholdPeriod NominalDiffTime
375− | TranslogDisableFlush Bool
376− | CacheFilterMaxSize (Maybe Bytes)
377− | CacheFilterExpire (Maybe NominalDiffTime)
378− | GatewaySnapshotInterval NominalDiffTime
379− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
380− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
381− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
382− | RoutingAllocationDisable Bool
383− | RoutingAllocationDisableNew Bool
384− | RoutingAllocationDisableReplica Bool
385− | RoutingAllocationEnable AllocationPolicy
386− | RoutingAllocationShardsPerNode ShardCount
387− | RecoveryInitialShards InitialShardCount
388− | GCDeletes NominalDiffTime
389− | TTLDisablePurge Bool
390− | TranslogFSType FSType
391− | IndexCompoundFormat CompoundFormat
392− | IndexCompoundOnFlush Bool
393− | WarmerEnabled Bool
394− --TODO: figure out allocation options
396−data AllocationPolicy = AllocAll
401−data ReplicaBounds = ReplicasBounded Int Int
402− | ReplicasLowerBounded Int
405−newtype Bytes = Bytes Int deriving (Eq, Show, Ord, ToJSON)
407−data FSType = FSSimple
408− | FSBuffered deriving (Eq, Show, Ord)
410−data InitialShardCount = QuorumShards
411− | QuorumMinus1Shards
414− | ExplicitShards Int
416−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
417− , nodeAttrFilterValues :: NonEmpty Text}
419−newtype NodeAttrName = NodeAttrName Text
421−data CompoundFormat = CompoundFileFormat Bool
422− | MergeSegmentVsTotalIndex Double
423− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
425−newtype NominalDiffTimeJSON = NominalDiffTimeJSON NominalDiffTime
427−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
428−type Reply = Network.HTTP.Client.Response L.ByteString
429−type Method = NHTM.Method
431−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
433− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
435−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show)
437−data FieldType = GeoPointType
443− | ByteType deriving (Eq, Show)
445−data FieldDefinition =
446− FieldDefinition { fieldType :: FieldType } deriving (Eq, Show)
448−{-| An 'IndexTemplate' defines a template that will automatically be
449− applied to new indices created. The templates include both
450− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
451− controls if the template will be applied to the index created.
452− Specify mappings as follows: @[toJSON TweetMapping, ...]@
454− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
457− IndexTemplate { templatePattern :: TemplatePattern
458− , templateSettings :: Maybe IndexSettings
459− , templateMappings :: [Value]
463− MappingField { mappingFieldName :: FieldName
464− , fieldDefinition :: FieldDefinition } deriving (Eq, Show)
466−{-| Support for type reification of 'Mapping's is currently incomplete, for
467− now the mapping API verbiage expects a 'ToJSON'able blob.
469− Indexes have mappings, mappings are schemas for the documents contained in the
470− index. I'd recommend having only one mapping per index, always having a mapping,
471− and keeping different kinds of documents separated if possible.
473−data Mapping = Mapping { typeName :: TypeName
474− , mappingFields :: [MappingField] } deriving (Eq, Show)
476−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
477− operation index, create, delete, and update. 'BulkIndex' behaves like an
478− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
480− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
483− BulkIndex IndexName MappingName DocId Value
484− | BulkCreate IndexName MappingName DocId Value
485− | BulkDelete IndexName MappingName DocId
486− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show)
488−{-| 'EsResult' describes the standard wrapper JSON document that you see in
489− successful Elasticsearch lookups or lookups that couldn't find the document.
491−data EsResult a = EsResult { _index :: Text
494− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show)
497−{-| 'EsResultFound' contains the document and its metadata inside of an
498− 'EsResult' when the document was successfully found.
500−data EsResultFound a = EsResultFound { _version :: DocVersion
501− , _source :: a } deriving (Eq, Show)
505−{-| 'DocVersion' is an integer version number for a document between 1
506−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
508−newtype DocVersion = DocVersion {
509− docVersionNumber :: Int
510− } deriving (Eq, Show, Ord, ToJSON)
512−-- | Smart constructor for in-range doc version
513−mkDocVersion :: Int -> Maybe DocVersion
515− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
517− | otherwise = Nothing
520−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
521−own version numbers instead of ones from ES.
523−newtype ExternalDocVersion = ExternalDocVersion DocVersion
524− deriving (Eq, Show, Ord, Bounded, Enum, ToJSON)
526−{-| 'VersionControl' is specified when indexing documents as a
527−optimistic concurrency control.
529−data VersionControl = NoVersionControl
530− -- ^ Don't send a version. This is a pure overwrite.
531− | InternalVersion DocVersion
532− -- ^ Use the default ES versioning scheme. Only
533− -- index the document if the version is the same
534− -- as the one specified. Only applicable to
535− -- updates, as you should be getting Version from
537− | ExternalGT ExternalDocVersion
538− -- ^ Use your own version numbering. Only index
539− -- the document if the version is strictly higher
540− -- OR the document doesn't exist. The given
541− -- version will be used as the new version number
542− -- for the stored document. N.B. All updates must
543− -- increment this number, meaning there is some
544− -- global, external ordering of updates.
545− | ExternalGTE ExternalDocVersion
546− -- ^ Use your own version numbering. Only index
547− -- the document if the version is equal or higher
548− -- than the stored version. Will succeed if there
549− -- is no existing document. The given version will
550− -- be used as the new version number for the
551− -- stored document. Use with care, as this could
552− -- result in data loss.
553− | ForceVersion ExternalDocVersion
554− -- ^ The document will always be indexed and the
555− -- given version will be the new version. This is
556− -- typically used for correcting errors. Use with
557− -- care, as this could result in data loss.
558− deriving (Show, Eq, Ord)
560−{-| 'DocumentParent' is used to specify a parent document.
562−newtype DocumentParent = DocumentParent DocId
565−{-| 'IndexDocumentSettings' are special settings supplied when indexing
566−a document. For the best backwards compatiblity when new fields are
567−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
569−data IndexDocumentSettings =
570− IndexDocumentSettings { idsVersionControl :: VersionControl
571− , idsParent :: Maybe DocumentParent
572− } deriving (Eq, Show)
574−{-| Reasonable default settings. Chooses no version control and no parent.
576−defaultIndexDocumentSettings :: IndexDocumentSettings
577−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
579−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
580− dependent with later sorts acting as tie-breakers for earlier sorts.
582−type Sort = [SortSpec]
584−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
585− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
586− 'DistanceUnit' to express "nearness" to a single geographical point as a
589−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
591−data SortSpec = DefaultSortSpec DefaultSort
592− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show)
594−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
595− 'mkSort' convenience function for when you want to specify only the most
598−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
601− DefaultSort { sortFieldName :: FieldName
602− , sortOrder :: SortOrder
604− , ignoreUnmapped :: Bool
605− , sortMode :: Maybe SortMode
606− , missingSort :: Maybe Missing
607− , nestedFilter :: Maybe Filter } deriving (Eq, Show)
609−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
610− encoded into "asc" or "desc" when turned into JSON.
612−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
614−data SortOrder = Ascending
615− | Descending deriving (Eq, Show)
617−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
618− sorted last, first, or using a custom value as a substitute.
620−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
622−data Missing = LastMissing
624− | CustomMissing Text deriving (Eq, Show)
626−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
628−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
630−data SortMode = SortMin
633− | SortAvg deriving (Eq, Show)
635−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
636− that you can concisely describe the usual kind of 'SortSpec's you want.
638−mkSort :: FieldName -> SortOrder -> DefaultSort
639−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
641−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
642− 'Query's cannot be cached.
644−type Cache = Bool -- caching on/off
645−defaultCache :: Cache
648−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
650−type PrefixValue = Text
652−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
653− JSON encoding baked in. Used all over the place.
655−data BooleanOperator = And | Or deriving (Eq, Show)
657−{-| 'ShardCount' is part of 'IndexSettings'
659−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic)
661−{-| 'ReplicaCount' is part of 'IndexSettings'
663−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic)
665−{-| 'Server' is used with the client functions to point at the ES instance
667−newtype Server = Server Text deriving (Eq, Show)
669−{-| 'IndexName' is used to describe which index to query/create/delete
671−newtype IndexName = IndexName Text deriving (Eq, Generic, Show)
673−{-| 'TemplateName' is used to describe which template to query/create/delete
675−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic)
677−{-| 'TemplatePattern' represents a pattern which is matched against index names
679−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic)
681−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
682− the data in the indices.
684−newtype MappingName = MappingName Text deriving (Eq, Generic, Show)
686−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
687− Can be set by the user or created by ES itself. Often used in client
688− functions for poking at specific documents.
690−newtype DocId = DocId Text deriving (Eq, Generic, Show)
692−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
694−newtype QueryString = QueryString Text deriving (Eq, Generic, Show)
696−{-| 'FieldName' is used all over the place wherever a specific field within
697− a document needs to be specified, usually in 'Query's or 'Filter's.
699−newtype FieldName = FieldName Text deriving (Eq, Show)
702−{-| 'Script' is often used in place of 'FieldName' to specify more
703−complex ways of extracting a value from a document.
705−newtype Script = Script { scriptText :: Text } deriving (Eq, Show)
707−{-| 'CacheName' is used in 'RegexpFilter' for describing the
708− 'CacheKey' keyed caching behavior.
710−newtype CacheName = CacheName Text deriving (Eq, Show)
712−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
715− CacheKey Text deriving (Eq, Show)
717− Existence Bool deriving (Eq, Show)
719− NullValue Bool deriving (Eq, Show)
720−newtype CutoffFrequency =
721− CutoffFrequency Double deriving (Eq, Show, Generic)
723− Analyzer Text deriving (Eq, Show, Generic)
724−newtype MaxExpansions =
725− MaxExpansions Int deriving (Eq, Show, Generic)
727−{-| 'Lenient', if set to true, will cause format based failures to be
728− ignored. I don't know what the bloody default is, Elasticsearch
729− documentation didn't say what it was. Let me know if you figure it out.
732− Lenient Bool deriving (Eq, Show, Generic)
734− Tiebreaker Double deriving (Eq, Show, Generic)
736− Boost Double deriving (Eq, Show, Generic)
738− BoostTerms Double deriving (Eq, Show, Generic)
740−{-| 'MinimumMatch' controls how many should clauses in the bool query should
741− match. Can be an absolute value (2) or a percentage (30%) or a
742− combination of both.
744−newtype MinimumMatch =
745− MinimumMatch Int deriving (Eq, Show, Generic)
746−newtype MinimumMatchText =
747− MinimumMatchText Text deriving (Eq, Show)
748−newtype DisableCoord =
749− DisableCoord Bool deriving (Eq, Show, Generic)
750−newtype IgnoreTermFrequency =
751− IgnoreTermFrequency Bool deriving (Eq, Show, Generic)
752−newtype MinimumTermFrequency =
753− MinimumTermFrequency Int deriving (Eq, Show, Generic)
754−newtype MaxQueryTerms =
755− MaxQueryTerms Int deriving (Eq, Show, Generic)
757− Fuzziness Double deriving (Eq, Show, Generic)
759−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
760−newtype PrefixLength =
761− PrefixLength Int deriving (Eq, Show, Generic)
763− TypeName Text deriving (Eq, Show, Generic)
764−newtype PercentMatch =
765− PercentMatch Double deriving (Eq, Show, Generic)
767− StopWord Text deriving (Eq, Show, Generic)
769− QueryPath Text deriving (Eq, Show, Generic)
771−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
772− heavy, because all terms in the index need to be examined, just in case
773− they match. Leading wildcards can be disabled by setting
774− 'AllowLeadingWildcard' to false. -}
775−newtype AllowLeadingWildcard =
776− AllowLeadingWildcard Bool deriving (Eq, Show, Generic)
777−newtype LowercaseExpanded =
778− LowercaseExpanded Bool deriving (Eq, Show, Generic)
779−newtype EnablePositionIncrements =
780− EnablePositionIncrements Bool deriving (Eq, Show, Generic)
782−{-| By default, wildcard terms in a query are not analyzed.
783− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
785−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic)
787−{-| 'GeneratePhraseQueries' defaults to false.
789−newtype GeneratePhraseQueries =
790− GeneratePhraseQueries Bool deriving (Eq, Show, Generic)
792−{-| 'Locale' is used for string conversions - defaults to ROOT.
794−newtype Locale = Locale Text deriving (Eq, Show, Generic)
795−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic)
796−newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic)
798−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
799− phrase matches. Default is 0.
801−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic)
802−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic)
803−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic)
805{-| 'unpackId' is a silly convenience function that gets used once.
430{-| 'unpackId' is a silly convenience function that gets used once.
@@ -808,8 +433,6 @@ unpackId :: DocId -> Text
808unpackId (DocId docId) = docId
433unpackId (DocId docId) = docId
810type TrackSortScores = Bool
435type TrackSortScores = Bool
811−newtype From = From Int deriving (Eq, Show, ToJSON)
812−newtype Size = Size Int deriving (Eq, Show, ToJSON)
814data Search = Search { queryBody :: Maybe Query
437data Search = Search { queryBody :: Maybe Query
815 , filterBody :: Maybe Filter
438 , filterBody :: Maybe Filter
@@ -821,1708 +444,87 @@ data Search = Search { queryBody :: Maybe Query
821 , from :: From
444 , from :: From
822 , size :: Size
445 , size :: Size
823 , searchType :: SearchType
446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
824 , fields :: Maybe [FieldName]
448 , fields :: Maybe [FieldName]
449+ , scriptFields :: Maybe ScriptFields
825− , 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)
827data SearchType = SearchTypeQueryThenFetch
480data SearchType = SearchTypeQueryThenFetch
828 | SearchTypeDfsQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
831− | SearchTypeQueryAndFetch
832− | SearchTypeDfsQueryAndFetch
833 deriving (Eq, Show)
482 deriving (Eq, Show)
835data Source =
484data Source =
836− NoSource
485+ NoSource
837 | SourcePatterns PatternOrPatterns
486 | SourcePatterns PatternOrPatterns
838 | SourceIncludeExclude Include Exclude
487 | SourceIncludeExclude Include Exclude
839− deriving (Show, Eq)
488+ deriving (Eq, Show)
841−data PatternOrPatterns = PopPattern Pattern
842− | PopPatterns [Pattern] deriving (Eq, Show)
844−data Include = Include [Pattern] deriving (Eq, Show)
845−data Exclude = Exclude [Pattern] deriving (Eq, Show)
847−newtype Pattern = Pattern Text deriving (Eq, Show)
849−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
850− , highlightFields :: [FieldHighlight]
851− } deriving (Show, Eq)
853−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
857−data HighlightSettings = Plain PlainHighlight
858− | Postings PostingsHighlight
859− | FastVector FastVectorHighlight
861−data PlainHighlight =
862− PlainHighlight { plainCommon :: Maybe CommonHighlight
863− , plainNonPost :: Maybe NonPostings } deriving (Show, Eq)
865− -- This requires that index_options are set to 'offset' in the mapping.
866−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq)
868−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
869−data FastVectorHighlight =
870− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
871− , fvNonPostSettings :: Maybe NonPostings
872− , boundaryChars :: Maybe Text
873− , boundaryMaxScan :: Maybe Int
874− , fragmentOffset :: Maybe Int
875− , matchedFields :: [Text]
876− , phraseLimit :: Maybe Int
877− } deriving (Show, Eq)
879−data CommonHighlight =
880− CommonHighlight { order :: Maybe Text
881− , forceSource :: Maybe Bool
882− , tag :: Maybe HighlightTag
883− , encoder :: Maybe HighlightEncoder
884− , noMatchSize :: Maybe Int
885− , highlightQuery :: Maybe Query
886− , requireFieldMatch :: Maybe Bool
887− } deriving (Show, Eq)
889−-- Settings that are only applicable to FastVector and Plain highlighters.
891− NonPostings { fragmentSize :: Maybe Int
892− , numberOfFragments :: Maybe Int} deriving (Show, Eq)
894−data HighlightEncoder = DefaultEncoder
898−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
899−data HighlightTag = TagSchema Text
900− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
905− TermQuery Term (Maybe Boost)
906− | TermsQuery (NonEmpty Term)
907− | QueryMatchQuery MatchQuery
908− | QueryMultiMatchQuery MultiMatchQuery
909− | QueryBoolQuery BoolQuery
910− | QueryBoostingQuery BoostingQuery
911− | QueryCommonTermsQuery CommonTermsQuery
912− | ConstantScoreFilter Filter Boost
913− | ConstantScoreQuery Query Boost
914− | QueryDisMaxQuery DisMaxQuery
915− | QueryFilteredQuery FilteredQuery
916− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
917− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
918− | QueryFuzzyQuery FuzzyQuery
919− | QueryHasChildQuery HasChildQuery
920− | QueryHasParentQuery HasParentQuery
921− | IdsQuery MappingName [DocId]
922− | QueryIndicesQuery IndicesQuery
923− | MatchAllQuery (Maybe Boost)
924− | QueryMoreLikeThisQuery MoreLikeThisQuery
925− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
926− | QueryNestedQuery NestedQuery
927− | QueryPrefixQuery PrefixQuery
928− | QueryQueryStringQuery QueryStringQuery
929− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
930− | QueryRangeQuery RangeQuery
931− | QueryRegexpQuery RegexpQuery
935− RegexpQuery { regexpQueryField :: FieldName
936− , regexpQuery :: Regexp
937− , regexpQueryFlags :: RegexpFlags
938− , regexpQueryBoost :: Maybe Boost
939− } deriving (Eq, Show)
942− RangeQuery { rangeQueryField :: FieldName
943− , rangeQueryRange :: RangeValue
944− , rangeQueryBoost :: Boost } deriving (Eq, Show)
946−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
947−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
949−data SimpleQueryStringQuery =
950− SimpleQueryStringQuery
951− { simpleQueryStringQuery :: QueryString
952− , simpleQueryStringField :: Maybe FieldOrFields
953− , simpleQueryStringOperator :: Maybe BooleanOperator
954− , simpleQueryStringAnalyzer :: Maybe Analyzer
955− , simpleQueryStringFlags :: Maybe [SimpleQueryFlag]
956− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
957− , simpleQueryStringLocale :: Maybe Locale
958− } deriving (Eq, Show)
960−data SimpleQueryFlag =
967− | SimpleQueryPrecedence
969− | SimpleQueryWhitespace
972− | SimpleQuerySlop deriving (Eq, Show)
974−-- use_dis_max and tie_breaker when fields are plural?
975−data QueryStringQuery =
977− { queryStringQuery :: QueryString
978− , queryStringDefaultField :: Maybe FieldName
979− , queryStringOperator :: Maybe BooleanOperator
980− , queryStringAnalyzer :: Maybe Analyzer
981− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
982− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
983− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
984− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
985− , queryStringFuzziness :: Maybe Fuzziness
986− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
987− , queryStringPhraseSlop :: Maybe PhraseSlop
988− , queryStringBoost :: Maybe Boost
989− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
990− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
991− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
992− , queryStringLenient :: Maybe Lenient
993− , queryStringLocale :: Maybe Locale
994− } deriving (Eq, Show)
996−mkQueryStringQuery :: QueryString -> QueryStringQuery
997−mkQueryStringQuery qs =
998− QueryStringQuery qs Nothing Nothing
999− Nothing Nothing Nothing Nothing
1000− Nothing Nothing Nothing Nothing
1001− Nothing Nothing Nothing Nothing
1004−data FieldOrFields = FofField FieldName
1005− | FofFields [FieldName] deriving (Eq, Show)
1009− { prefixQueryField :: FieldName
1010− , prefixQueryPrefixValue :: Text
1011− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show)
1015− { nestedQueryPath :: QueryPath
1016− , nestedQueryScoreType :: ScoreType
1017− , nestedQuery :: Query } deriving (Eq, Show)
1019−data MoreLikeThisFieldQuery =
1020− MoreLikeThisFieldQuery
1021− { moreLikeThisFieldText :: Text
1022− , moreLikeThisFieldFields :: FieldName
1023− -- default 0.3 (30%)
1024− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1025− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1026− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1027− , moreLikeThisFieldStopWords :: Maybe [StopWord]
1028− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1029− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1030− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1031− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1032− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1033− , moreLikeThisFieldBoost :: Maybe Boost
1034− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1035− } deriving (Eq, Show)
1037−data MoreLikeThisQuery =
1039− { moreLikeThisText :: Text
1040− , moreLikeThisFields :: Maybe [FieldName]
1041− -- default 0.3 (30%)
1042− , moreLikeThisPercentMatch :: Maybe PercentMatch
1043− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1044− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1045− , moreLikeThisStopWords :: Maybe [StopWord]
1046− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1047− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1048− , moreLikeThisMinWordLength :: Maybe MinWordLength
1049− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1050− , moreLikeThisBoostTerms :: Maybe BoostTerms
1051− , moreLikeThisBoost :: Maybe Boost
1052− , moreLikeThisAnalyzer :: Maybe Analyzer
1053− } deriving (Eq, Show)
1057− { indicesQueryIndices :: [IndexName]
1058− , indicesQuery :: Query
1060− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show)
1062−data HasParentQuery =
1064− { hasParentQueryType :: TypeName
1065− , hasParentQuery :: Query
1066− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1068−data HasChildQuery =
1070− { hasChildQueryType :: TypeName
1071− , hasChildQuery :: Query
1072− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1078− | ScoreTypeNone deriving (Eq, Show)
1081− FuzzyQuery { fuzzyQueryField :: FieldName
1082− , fuzzyQueryValue :: Text
1083− , fuzzyQueryPrefixLength :: PrefixLength
1084− , fuzzyQueryMaxExpansions :: MaxExpansions
1085− , fuzzyQueryFuzziness :: Fuzziness
1086− , fuzzyQueryBoost :: Maybe Boost
1087− } deriving (Eq, Show)
1089−data FuzzyLikeFieldQuery =
1090− FuzzyLikeFieldQuery
1091− { fuzzyLikeField :: FieldName
1092− -- anaphora is good for the soul.
1093− , fuzzyLikeFieldText :: Text
1094− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1095− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1096− , fuzzyLikeFieldFuzziness :: Fuzziness
1097− , fuzzyLikeFieldPrefixLength :: PrefixLength
1098− , fuzzyLikeFieldBoost :: Boost
1099− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1100− } deriving (Eq, Show)
1102−data FuzzyLikeThisQuery =
1104− { fuzzyLikeFields :: [FieldName]
1105− , fuzzyLikeText :: Text
1106− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1107− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1108− , fuzzyLikeFuzziness :: Fuzziness
1109− , fuzzyLikePrefixLength :: PrefixLength
1110− , fuzzyLikeBoost :: Boost
1111− , fuzzyLikeAnalyzer :: Maybe Analyzer
1112− } deriving (Eq, Show)
1114−data FilteredQuery =
1116− { filteredQuery :: Query
1117− , filteredFilter :: Filter } deriving (Eq, Show)
1120− DisMaxQuery { disMaxQueries :: [Query]
1122− , disMaxTiebreaker :: Tiebreaker
1123− , disMaxBoost :: Maybe Boost
1124− } deriving (Eq, Show)
1127− MatchQuery { matchQueryField :: FieldName
1128− , matchQueryQueryString :: QueryString
1129− , matchQueryOperator :: BooleanOperator
1130− , matchQueryZeroTerms :: ZeroTermsQuery
1131− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1132− , matchQueryMatchType :: Maybe MatchQueryType
1133− , matchQueryAnalyzer :: Maybe Analyzer
1134− , matchQueryMaxExpansions :: Maybe MaxExpansions
1135− , matchQueryLenient :: Maybe Lenient
1136− , matchQueryBoost :: Maybe Boost } deriving (Eq, Show)
1138−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1139− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1141−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1142−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1144−data MatchQueryType =
1146− | MatchPhrasePrefix deriving (Eq, Show)
1148−data MultiMatchQuery =
1149− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1150− , multiMatchQueryString :: QueryString
1151− , multiMatchQueryOperator :: BooleanOperator
1152− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1153− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1154− , multiMatchQueryType :: Maybe MultiMatchQueryType
1155− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1156− , multiMatchQueryAnalyzer :: Maybe Analyzer
1157− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1158− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show)
1160−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1161− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1162− make a 'MultiMatchQuery'.
1165−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1166−mkMultiMatchQuery matchFields query =
1167− MultiMatchQuery matchFields query
1168− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1170−data MultiMatchQueryType =
1171− MultiMatchBestFields
1172− | MultiMatchMostFields
1173− | MultiMatchCrossFields
1175− | MultiMatchPhrasePrefix deriving (Eq, Show)
1178− BoolQuery { boolQueryMustMatch :: [Query]
1179− , boolQueryMustNotMatch :: [Query]
1180− , boolQueryShouldMatch :: [Query]
1181− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1182− , boolQueryBoost :: Maybe Boost
1183− , boolQueryDisableCoord :: Maybe DisableCoord
1184− } deriving (Eq, Show)
1186−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1187−mkBoolQuery must mustNot should =
1188− BoolQuery must mustNot should Nothing Nothing Nothing
1190−data BoostingQuery =
1191− BoostingQuery { positiveQuery :: Query
1192− , negativeQuery :: Query
1193− , negativeBoost :: Boost } deriving (Eq, Show)
1195−data CommonTermsQuery =
1196− CommonTermsQuery { commonField :: FieldName
1197− , commonQuery :: QueryString
1198− , commonCutoffFrequency :: CutoffFrequency
1199− , commonLowFreqOperator :: BooleanOperator
1200− , commonHighFreqOperator :: BooleanOperator
1201− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1202− , commonBoost :: Maybe Boost
1203− , commonAnalyzer :: Maybe Analyzer
1204− , commonDisableCoord :: Maybe DisableCoord
1205− } deriving (Eq, Show)
1207−data CommonMinimumMatch =
1208− CommonMinimumMatchHighLow MinimumMatchHighLow
1209− | CommonMinimumMatch MinimumMatch
1210− deriving (Eq, Show)
1212−data MinimumMatchHighLow =
1213− MinimumMatchHighLow { lowFreq :: MinimumMatch
1214− , highFreq :: MinimumMatch } deriving (Eq, Show)
1216−data Filter = AndFilter [Filter] Cache
1217− | OrFilter [Filter] Cache
1218− | NotFilter Filter Cache
1220− | BoolFilter BoolMatch
1221− | ExistsFilter FieldName -- always cached
1222− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1223− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1224− | GeoDistanceRangeFilter GeoPoint DistanceRange
1225− | GeoPolygonFilter FieldName [LatLon]
1226− | IdsFilter MappingName [DocId]
1228− | MissingFilter FieldName Existence NullValue
1229− | PrefixFilter FieldName PrefixValue Cache
1230− | QueryFilter Query Cache
1231− | RangeFilter FieldName RangeValue RangeExecution Cache
1232− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1233− | TermFilter Term Cache
1234− deriving (Eq, Show)
1236−data ZeroTermsQuery = ZeroTermsNone
1237− | ZeroTermsAll deriving (Eq, Show)
1239−data RangeExecution = RangeExecutionIndex
1240− | RangeExecutionFielddata deriving (Eq, Show)
1242−newtype Regexp = Regexp Text deriving (Eq, Show)
1244−data RegexpFlags = AllRegexpFlags
1246− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show)
1248−data RegexpFlag = AnyString
1253− | Interval deriving (Eq, Show)
1255−newtype LessThan = LessThan Double deriving (Eq, Show)
1256−newtype LessThanEq = LessThanEq Double deriving (Eq, Show)
1257−newtype GreaterThan = GreaterThan Double deriving (Eq, Show)
1258−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show)
1260−newtype LessThanD = LessThanD UTCTime deriving (Eq, Show)
1261−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show)
1262−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show)
1263−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show)
1265−data RangeValue = RangeDateLte LessThanEqD
1266− | RangeDateLt LessThanD
1267− | RangeDateGte GreaterThanEqD
1268− | RangeDateGt GreaterThanD
1269− | RangeDateGtLt GreaterThanD LessThanD
1270− | RangeDateGteLte GreaterThanEqD LessThanEqD
1271− | RangeDateGteLt GreaterThanEqD LessThanD
1272− | RangeDateGtLte GreaterThanD LessThanEqD
1273− | RangeDoubleLte LessThanEq
1274− | RangeDoubleLt LessThan
1275− | RangeDoubleGte GreaterThanEq
1276− | RangeDoubleGt GreaterThan
1277− | RangeDoubleGtLt GreaterThan LessThan
1278− | RangeDoubleGteLte GreaterThanEq LessThanEq
1279− | RangeDoubleGteLt GreaterThanEq LessThan
1280− | RangeDoubleGtLte GreaterThan LessThanEq
1281− deriving (Eq, Show)
1283−rangeValueToPair :: RangeValue -> [Pair]
1284−rangeValueToPair rv = case rv of
1285− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1286− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1287− RangeDateLt (LessThanD t) -> ["lt" .= t]
1288− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1289− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1290− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1291− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1292− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1293− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1294− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1295− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1296− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1297− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1298− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1299− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1300− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1302−data Term = Term { termField :: Text
1303− , termValue :: Text } deriving (Eq, Show)
1305−data BoolMatch = MustMatch Term Cache
1306− | MustNotMatch Term Cache
1307− | ShouldMatch [Term] Cache deriving (Eq, Show)
1309−-- "memory" or "indexed"
1310−data GeoFilterType = GeoFilterMemory
1311− | GeoFilterIndexed deriving (Eq, Show)
1313−data LatLon = LatLon { lat :: Double
1314− , lon :: Double } deriving (Eq, Show)
1316−data GeoBoundingBox =
1317− GeoBoundingBox { topLeft :: LatLon
1318− , bottomRight :: LatLon } deriving (Eq, Show)
1320−data GeoBoundingBoxConstraint =
1321− GeoBoundingBoxConstraint { geoBBField :: FieldName
1322− , constraintBox :: GeoBoundingBox
1323− , bbConstraintcache :: Cache
1324− , geoType :: GeoFilterType
1325− } deriving (Eq, Show)
1328− GeoPoint { geoField :: FieldName
1329− , latLon :: LatLon} deriving (Eq, Show)
1331−data DistanceUnit = Miles
1339− | NauticalMiles deriving (Eq, Show)
1341−data DistanceType = Arc
1342− | SloppyArc -- doesn't exist <1.0
1343− | Plane deriving (Eq, Show)
1345−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1346− | NoOptimizeBbox deriving (Eq, Show)
1349− Distance { coefficient :: Double
1350− , unit :: DistanceUnit } deriving (Eq, Show)
1352−data DistanceRange =
1353− DistanceRange { distanceFrom :: Distance
1354− , distanceTo :: Distance } deriving (Eq, Show)
1356−data SearchResult a =
1357− SearchResult { took :: Int
1359− , shards :: ShardResult
1360− , searchHits :: SearchHits a
1361− , aggregations :: Maybe AggregationResults
1362− , scrollId :: Maybe ScrollId } deriving (Eq, Show)
1364−type ScrollId = Text -- Fixme: Newtype
1366−type Score = Maybe Double
1369− SearchHits { hitsTotal :: Int
1370− , maxScore :: Score
1371− , hits :: [Hit a] } deriving (Eq, Show)
1374−instance Monoid (SearchHits a) where
1375− mempty = SearchHits 0 Nothing mempty
1376− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1377− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1381− Hit { hitIndex :: IndexName
1382− , hitType :: MappingName
1383− , hitDocId :: DocId
1384− , hitScore :: Score
1386− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show)
1389− ShardResult { shardTotal :: Int
1390− , shardsSuccessful :: Int
1391− , shardsFailed :: Int } deriving (Eq, Show, Generic)
1393−type HitHighlight = M.Map Text [Text]
1395−showText :: Show a => a -> Text
1396−showText = T.pack . show
1398−type Aggregations = M.Map Text Aggregation
1400−emptyAggregations :: Aggregations
1401−emptyAggregations = M.empty
1403−mkAggregations :: Text -> Aggregation -> Aggregations
1404−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1406−data TermOrder = TermOrder{ termSortField :: Text
1407− , termSortOrder :: SortOrder } deriving (Eq, Show)
1409−data TermInclusion = TermInclusion Text
1410− | TermPattern Text Text deriving (Eq, Show)
1412−data CollectionMode = BreadthFirst
1413− | DepthFirst deriving (Eq, Show)
1415−data ExecutionHint = Ordinals
1417− | GlobalOrdinalsHash
1418− | GlobalOrdinalsLowCardinality
1419− | Map deriving (Eq, Show)
1421−data TimeInterval = Weeks
1425− | Seconds deriving (Eq)
1427−data Interval = Year
1435− | FractionalInterval Float TimeInterval deriving (Eq, Show)
1437−data Aggregation = TermsAgg TermsAggregation
1438− | DateHistogramAgg DateHistogramAggregation
1439− | ValueCountAgg ValueCountAggregation
1440− | FilterAgg FilterAggregation deriving (Eq, Show)
1443−data TermsAggregation = TermsAggregation { term :: Either Text Text
1444− , termInclude :: Maybe TermInclusion
1445− , termExclude :: Maybe TermInclusion
1446− , termOrder :: Maybe TermOrder
1447− , termMinDocCount :: Maybe Int
1448− , termSize :: Maybe Int
1449− , termShardSize :: Maybe Int
1450− , termCollectMode :: Maybe CollectionMode
1451− , termExecutionHint :: Maybe ExecutionHint
1452− , termAggs :: Maybe Aggregations
1453− } deriving (Eq, Show)
1455−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1456− , dateInterval :: Interval
1457− , dateFormat :: Maybe Text
1458− -- pre and post deprecated in 1.5
1459− , datePreZone :: Maybe Text
1460− , datePostZone :: Maybe Text
1461− , datePreOffset :: Maybe Text
1462− , datePostOffset :: Maybe Text
1463− , dateAggs :: Maybe Aggregations
1464− } deriving (Eq, Show)
1466−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1467−data ValueCountAggregation = FieldValueCount FieldName
1468− | ScriptValueCount Script deriving (Eq, Show)
1470−-- | 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.
1471−data FilterAggregation = FilterAggregation { faFilter :: Filter
1472− , faAggs :: Maybe Aggregations} deriving (Eq, Show)
1474−mkTermsAggregation :: Text -> TermsAggregation
1475−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1477−mkTermsScriptAggregation :: Text -> TermsAggregation
1478−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1480−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1481−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1483−instance ToJSON TermOrder where
1484− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1486−instance ToJSON TermInclusion where
1487− toJSON (TermInclusion x) = toJSON x
1488− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1491−instance ToJSON CollectionMode where
1492− toJSON BreadthFirst = "breadth_first"
1493− toJSON DepthFirst = "depth_first"
1495−instance ToJSON ExecutionHint where
1496− toJSON Ordinals = "ordinals"
1497− toJSON GlobalOrdinals = "global_ordinals"
1498− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1499− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1502−instance ToJSON Interval where
1503− toJSON Year = "year"
1504− toJSON Quarter = "quarter"
1505− toJSON Month = "month"
1506− toJSON Week = "week"
1508− toJSON Hour = "hour"
1509− toJSON Minute = "minute"
1510− toJSON Second = "second"
1511− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1513−instance Show TimeInterval where
1520−instance ToJSON Aggregation where
1521− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1522− omitNulls ["terms" .= omitNulls [ toJSON' term,
1523− "include" .= include,
1524− "exclude" .= exclude,
1526− "min_doc_count" .= minDocCount,
1528− "shard_size" .= shardSize,
1529− "collect_mode" .= collectMode,
1530− "execution_hint" .= executionHint
1532− "aggs" .= termAggs ]
1534− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1536− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1537− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1538− "interval" .= interval,
1539− "format" .= format,
1540− "pre_zone" .= preZone,
1541− "post_zone" .= postZone,
1542− "pre_offset" .= preOffset,
1543− "post_offset" .= postOffset
1545− "aggs" .= dateHistoAggs ]
1546− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1547− where v = case a of
1548− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1549− (ScriptValueCount (Script s)) -> object ["script" .= s]
1550− toJSON (FilterAgg (FilterAggregation filt ags)) =
1551− omitNulls [ "filter" .= filt
1554−type AggregationResults = M.Map Text Value
1556−class BucketAggregation a where
1558− docCount :: a -> Int
1559− aggs :: a -> Maybe AggregationResults
1562−data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1564−data TermsResult = TermsResult { termKey :: Text
1565− , termsDocCount :: Int
1566− , termsAggs :: Maybe AggregationResults } deriving (Show)
1568−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1569− , dateKeyStr :: Maybe Text
1570− , dateDocCount :: Int
1571− , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1573−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1574−toTerms t a = M.lookup t a >>= deserialize
1575− where deserialize = parseMaybe parseJSON
1577−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1578−toDateHistogram t a = M.lookup t a >>= deserialize
1579− where deserialize = parseMaybe parseJSON
1581−instance BucketAggregation TermsResult where
1583− docCount = termsDocCount
1586−instance BucketAggregation DateHistogramResult where
1587− key = showText . dateKey
1588− docCount = dateDocCount
1589− aggs = dateHistogramAggs
1591−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1592− parseJSON (Object v) = Bucket <$>
1594− parseJSON _ = mempty
1596−instance FromJSON TermsResult where
1597− parseJSON (Object v) = TermsResult <$>
1599− v .: "doc_count" <*>
1600− v .:? "aggregations"
1601− parseJSON _ = mempty
1603−instance FromJSON DateHistogramResult where
1604− parseJSON (Object v) = DateHistogramResult <$>
1606− v .:? "key_as_string" <*>
1607− v .: "doc_count" <*>
1608− v .:? "aggregations"
1609− parseJSON _ = mempty
1611−instance Monoid Filter where
1612− mempty = IdentityFilter
1613− mappend a b = AndFilter [a, b] defaultCache
1615−instance Seminearring Filter where
1616− a <||> b = OrFilter [a, b] defaultCache
1618−instance ToJSON Filter where
1619− toJSON (AndFilter filters cache) =
1621− object [ "filters" .= fmap toJSON filters
1622− , "_cache" .= cache]]
1624− toJSON (OrFilter filters cache) =
1626− object [ "filters" .= fmap toJSON filters
1627− , "_cache" .= cache]]
1629− toJSON (NotFilter notFilter cache) =
1631− object ["filter" .= notFilter
1632− , "_cache" .= cache]]
1634− toJSON (IdentityFilter) =
1635− object ["match_all" .= object []]
1637− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1638− object ["term" .= object base]
1639− where base = [termFilterField .= termFilterValue,
1642− toJSON (ExistsFilter (FieldName fieldName)) =
1643− object ["exists" .= object
1644− ["field" .= fieldName]]
1646− toJSON (BoolFilter boolMatch) =
1647− object ["bool" .= boolMatch]
1649− toJSON (GeoBoundingBoxFilter bbConstraint) =
1650− object ["geo_bounding_box" .= bbConstraint]
1652− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1653− distance distanceType optimizeBbox cache) =
1654− object ["geo_distance" .=
1655− object ["distance" .= distance
1656− , "distance_type" .= distanceType
1657− , "optimize_bbox" .= optimizeBbox
1658− , distanceGeoField .= geoDistLatLon
1659− , "_cache" .= cache]]
1661− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1662− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1663− object ["geo_distance_range" .=
1664− object ["from" .= geoDistRangeDistFrom
1665− , "to" .= drDistanceTo
1666− , gddrField .= drLatLon]]
1668− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1669− object ["geo_polygon" .=
1670− object [geoPolygonFilterField .=
1671− object ["points" .= fmap toJSON latLons]]]
1673− toJSON (IdsFilter (MappingName mappingName) values) =
1675− object ["type" .= mappingName
1676− , "values" .= fmap unpackId values]]
1678− toJSON (LimitFilter limit) =
1679− object ["limit" .= object ["value" .= limit]]
1681− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1682− object ["missing" .=
1683− object ["field" .= fieldName
1684− , "existence" .= existence
1685− , "null_value" .= nullValue]]
1687− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1688− object ["prefix" .=
1689− object [fieldName .= fieldValue
1690− , "_cache" .= cache]]
1692− toJSON (QueryFilter query False) =
1693− object ["query" .= toJSON query ]
1694− toJSON (QueryFilter query True) =
1695− object ["fquery" .=
1696− object [ "query" .= toJSON query
1697− , "_cache" .= True ]]
1699− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1701− object [ fieldName .= object (rangeValueToPair rangeValue)
1702− , "execution" .= rangeExecution
1703− , "_cache" .= cache]]
1705− toJSON (RegexpFilter (FieldName fieldName)
1706− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1707− object ["regexp" .=
1708− object [fieldName .=
1709− object ["value" .= regexText
1710− , "flags" .= flags]
1711− , "_name" .= cacheName
1712− , "_cache" .= cache
1713− , "_cache_key" .= cacheKey]]
1715−instance ToJSON GeoPoint where
1716− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
1717− object [ geoPointField .= geoPointLatLon ]
1720−instance ToJSON Query where
1721− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
1723− object [termQueryField .= object merged]]
1725− base = [ "value" .= termQueryValue ]
1726− boosted = maybe [] (return . ("boost" .=)) boost
1727− merged = mappend base boosted
1729− toJSON (TermsQuery terms) =
1730− object [ "terms" .= object conjoined ]
1731− where conjoined = [ getTermsField terms .=
1732− fmap (toJSON . getTermValue) (toList terms)]
1733− getTermsField ((Term f _ ) :| _) = f
1734− getTermValue (Term _ v) = v
1735− toJSON (IdsQuery idsQueryMappingName docIds) =
1736− object [ "ids" .= object conjoined ]
1737− where conjoined = [ "type" .= idsQueryMappingName
1738− , "values" .= fmap toJSON docIds ]
1740− toJSON (QueryQueryStringQuery qQueryStringQuery) =
1741− object [ "query_string" .= qQueryStringQuery ]
1743− toJSON (QueryMatchQuery matchQuery) =
1744− object [ "match" .= matchQuery ]
1746− toJSON (QueryMultiMatchQuery multiMatchQuery) =
1747− toJSON multiMatchQuery
1749− toJSON (QueryBoolQuery boolQuery) =
1750− object [ "bool" .= boolQuery ]
1752− toJSON (QueryBoostingQuery boostingQuery) =
1753− object [ "boosting" .= boostingQuery ]
1755− toJSON (QueryCommonTermsQuery commonTermsQuery) =
1756− object [ "common" .= commonTermsQuery ]
1758− toJSON (ConstantScoreFilter csFilter boost) =
1759− object [ "constant_score" .= csFilter
1760− , "boost" .= boost]
1762− toJSON (ConstantScoreQuery query boost) =
1763− object [ "constant_score" .= query
1764− , "boost" .= boost]
1766− toJSON (QueryDisMaxQuery disMaxQuery) =
1767− object [ "dis_max" .= disMaxQuery ]
1769− toJSON (QueryFilteredQuery qFilteredQuery) =
1770− object [ "filtered" .= qFilteredQuery ]
1772− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
1773− object [ "fuzzy_like_this" .= fuzzyQuery ]
1775− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
1776− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
1778− toJSON (QueryFuzzyQuery fuzzyQuery) =
1779− object [ "fuzzy" .= fuzzyQuery ]
1781− toJSON (QueryHasChildQuery childQuery) =
1782− object [ "has_child" .= childQuery ]
1784− toJSON (QueryHasParentQuery parentQuery) =
1785− object [ "has_parent" .= parentQuery ]
1787− toJSON (QueryIndicesQuery qIndicesQuery) =
1788− object [ "indices" .= qIndicesQuery ]
1790− toJSON (MatchAllQuery boost) =
1791− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
1793− toJSON (QueryMoreLikeThisQuery query) =
1794− object [ "more_like_this" .= query ]
1796− toJSON (QueryMoreLikeThisFieldQuery query) =
1797− object [ "more_like_this_field" .= query ]
1799− toJSON (QueryNestedQuery query) =
1800− object [ "nested" .= query ]
1802− toJSON (QueryPrefixQuery query) =
1803− object [ "prefix" .= query ]
1805− toJSON (QueryRangeQuery query) =
1806− object [ "range" .= query ]
1808− toJSON (QueryRegexpQuery query) =
1809− object [ "regexp" .= query ]
1811− toJSON (QuerySimpleQueryStringQuery query) =
1812− object [ "simple_query_string" .= query ]
1815−omitNulls :: [(Text, Value)] -> Value
1816−omitNulls = object . filter notNull where
1817− notNull (_, Null) = False
1818− notNull (_, Array a) = (not . V.null) a
1822−instance ToJSON SimpleQueryStringQuery where
1823− toJSON SimpleQueryStringQuery {..} =
1824− omitNulls (base ++ maybeAdd)
1825− where base = [ "query" .= simpleQueryStringQuery ]
1826− maybeAdd = [ "fields" .= simpleQueryStringField
1827− , "default_operator" .= simpleQueryStringOperator
1828− , "analyzer" .= simpleQueryStringAnalyzer
1829− , "flags" .= simpleQueryStringFlags
1830− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
1831− , "locale" .= simpleQueryStringLocale ]
1834−instance ToJSON FieldOrFields where
1835− toJSON (FofField fieldName) =
1837− toJSON (FofFields fieldNames) =
1840−instance ToJSON SimpleQueryFlag where
1841− toJSON SimpleQueryAll = "ALL"
1842− toJSON SimpleQueryNone = "NONE"
1843− toJSON SimpleQueryAnd = "AND"
1844− toJSON SimpleQueryOr = "OR"
1845− toJSON SimpleQueryPrefix = "PREFIX"
1846− toJSON SimpleQueryPhrase = "PHRASE"
1847− toJSON SimpleQueryPrecedence = "PRECEDENCE"
1848− toJSON SimpleQueryEscape = "ESCAPE"
1849− toJSON SimpleQueryWhitespace = "WHITESPACE"
1850− toJSON SimpleQueryFuzzy = "FUZZY"
1851− toJSON SimpleQueryNear = "NEAR"
1852− toJSON SimpleQuerySlop = "SLOP"
1855−instance ToJSON RegexpQuery where
1856− toJSON (RegexpQuery (FieldName rqQueryField)
1857− (Regexp regexpQueryQuery) rqQueryFlags
1859− object [ rqQueryField .= omitNulls base ]
1860− where base = [ "value" .= regexpQueryQuery
1861− , "flags" .= rqQueryFlags
1862− , "boost" .= rqQueryBoost ]
1865−instance ToJSON QueryStringQuery where
1866− toJSON (QueryStringQuery qsQueryString
1867− qsDefaultField qsOperator
1868− qsAnalyzer qsAllowWildcard
1869− qsLowercaseExpanded qsEnablePositionIncrements
1870− qsFuzzyMaxExpansions qsFuzziness
1871− qsFuzzyPrefixLength qsPhraseSlop
1872− qsBoost qsAnalyzeWildcard
1873− qsGeneratePhraseQueries qsMinimumShouldMatch
1874− qsLenient qsLocale) =
1877− base = [ "query" .= qsQueryString
1878− , "default_field" .= qsDefaultField
1879− , "default_operator" .= qsOperator
1880− , "analyzer" .= qsAnalyzer
1881− , "allow_leading_wildcard" .= qsAllowWildcard
1882− , "lowercase_expanded_terms" .= qsLowercaseExpanded
1883− , "enable_position_increments" .= qsEnablePositionIncrements
1884− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
1885− , "fuzziness" .= qsFuzziness
1886− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
1887− , "phrase_slop" .= qsPhraseSlop
1888− , "boost" .= qsBoost
1889− , "analyze_wildcard" .= qsAnalyzeWildcard
1890− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
1891− , "minimum_should_match" .= qsMinimumShouldMatch
1892− , "lenient" .= qsLenient
1893− , "locale" .= qsLocale ]
1896−instance ToJSON RangeQuery where
1897− toJSON (RangeQuery (FieldName fieldName) range boost) =
1898− object [ fieldName .= conjoined ]
1899− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
1902−instance ToJSON PrefixQuery where
1903− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
1904− object [ fieldName .= omitNulls base ]
1905− where base = [ "value" .= queryValue
1906− , "boost" .= boost ]
1909−instance ToJSON NestedQuery where
1910− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
1911− object [ "path" .= nqPath
1912− , "score_mode" .= nqScoreType
1913− , "query" .= nqQuery ]
1916−instance ToJSON MoreLikeThisFieldQuery where
1917− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
1918− percent mtf mqt stopwords mindf maxdf
1919− minwl maxwl boostTerms boost analyzer) =
1920− object [ fieldName .= omitNulls base ]
1921− where base = [ "like_text" .= text
1922− , "percent_terms_to_match" .= percent
1923− , "min_term_freq" .= mtf
1924− , "max_query_terms" .= mqt
1925− , "stop_words" .= stopwords
1926− , "min_doc_freq" .= mindf
1927− , "max_doc_freq" .= maxdf
1928− , "min_word_length" .= minwl
1929− , "max_word_length" .= maxwl
1930− , "boost_terms" .= boostTerms
1932− , "analyzer" .= analyzer ]
1935−instance ToJSON MoreLikeThisQuery where
1936− toJSON (MoreLikeThisQuery text fields percent
1937− mtf mqt stopwords mindf maxdf
1938− minwl maxwl boostTerms boost analyzer) =
1940− where base = [ "like_text" .= text
1941− , "fields" .= fields
1942− , "percent_terms_to_match" .= percent
1943− , "min_term_freq" .= mtf
1944− , "max_query_terms" .= mqt
1945− , "stop_words" .= stopwords
1946− , "min_doc_freq" .= mindf
1947− , "max_doc_freq" .= maxdf
1948− , "min_word_length" .= minwl
1949− , "max_word_length" .= maxwl
1950− , "boost_terms" .= boostTerms
1952− , "analyzer" .= analyzer ]
1955−instance ToJSON IndicesQuery where
1956− toJSON (IndicesQuery indices query noMatch) =
1957− omitNulls [ "indices" .= indices
1958− , "no_match_query" .= noMatch
1959− , "query" .= query ]
1962−instance ToJSON HasParentQuery where
1963− toJSON (HasParentQuery queryType query scoreType) =
1964− omitNulls [ "parent_type" .= queryType
1965− , "score_type" .= scoreType
1966− , "query" .= query ]
1969−instance ToJSON HasChildQuery where
1970− toJSON (HasChildQuery queryType query scoreType) =
1971− omitNulls [ "query" .= query
1972− , "score_type" .= scoreType
1973− , "type" .= queryType ]
1976−instance ToJSON FuzzyQuery where
1977− toJSON (FuzzyQuery (FieldName fieldName) queryText
1978− prefixLength maxEx fuzziness boost) =
1979− object [ fieldName .= omitNulls base ]
1980− where base = [ "value" .= queryText
1981− , "fuzziness" .= fuzziness
1982− , "prefix_length" .= prefixLength
1984− , "max_expansions" .= maxEx ]
1987−instance ToJSON FuzzyLikeFieldQuery where
1988− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
1989− fieldText maxTerms ignoreFreq fuzziness prefixLength
1991− object [ fieldName .=
1992− omitNulls [ "like_text" .= fieldText
1993− , "max_query_terms" .= maxTerms
1994− , "ignore_tf" .= ignoreFreq
1995− , "fuzziness" .= fuzziness
1996− , "prefix_length" .= prefixLength
1997− , "analyzer" .= analyzer
1998− , "boost" .= boost ]]
2001−instance ToJSON FuzzyLikeThisQuery where
2002− toJSON (FuzzyLikeThisQuery fields text maxTerms
2003− ignoreFreq fuzziness prefixLength boost analyzer) =
2005− where base = [ "fields" .= fields
2006− , "like_text" .= text
2007− , "max_query_terms" .= maxTerms
2008− , "ignore_tf" .= ignoreFreq
2009− , "fuzziness" .= fuzziness
2010− , "prefix_length" .= prefixLength
2011− , "analyzer" .= analyzer
2012− , "boost" .= boost ]
2015−instance ToJSON FilteredQuery where
2016− toJSON (FilteredQuery query fFilter) =
2017− object [ "query" .= query
2018− , "filter" .= fFilter ]
2021−instance ToJSON DisMaxQuery where
2022− toJSON (DisMaxQuery queries tiebreaker boost) =
2024− where base = [ "queries" .= queries
2026− , "tie_breaker" .= tiebreaker ]
2029−instance ToJSON CommonTermsQuery where
2030− toJSON (CommonTermsQuery (FieldName fieldName)
2031− (QueryString query) cf lfo hfo msm
2032− boost analyzer disableCoord) =
2033− object [fieldName .= omitNulls base ]
2034− where base = [ "query" .= query
2035− , "cutoff_frequency" .= cf
2036− , "low_freq_operator" .= lfo
2037− , "minimum_should_match" .= msm
2039− , "analyzer" .= analyzer
2040− , "disable_coord" .= disableCoord
2041− , "high_freq_operator" .= hfo ]
2044−instance ToJSON CommonMinimumMatch where
2045− toJSON (CommonMinimumMatch mm) = toJSON mm
2046− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2047− object [ "low_freq" .= lowF
2048− , "high_freq" .= highF ]
2050−instance ToJSON BoostingQuery where
2051− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2052− object [ "positive" .= bqPositiveQuery
2053− , "negative" .= bqNegativeQuery
2054− , "negative_boost" .= bqNegativeBoost ]
2057−instance ToJSON BoolQuery where
2058− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2060− where base = [ "must" .= mustM
2061− , "must_not" .= notM
2062− , "should" .= shouldM
2063− , "minimum_should_match" .= bqMin
2065− , "disable_coord" .= disableCoord ]
2068−instance ToJSON MatchQuery where
2069− toJSON (MatchQuery (FieldName fieldName)
2070− (QueryString mqQueryString) booleanOperator
2071− zeroTermsQuery cutoffFrequency matchQueryType
2072− analyzer maxExpansions lenient boost) =
2073− object [ fieldName .= omitNulls base ]
2074− where base = [ "query" .= mqQueryString
2075− , "operator" .= booleanOperator
2076− , "zero_terms_query" .= zeroTermsQuery
2077− , "cutoff_frequency" .= cutoffFrequency
2078− , "type" .= matchQueryType
2079− , "analyzer" .= analyzer
2080− , "max_expansions" .= maxExpansions
2081− , "lenient" .= lenient
2082− , "boost" .= boost ]
2085−instance ToJSON MultiMatchQuery where
2086− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2087− ztQ tb mmqt cf analyzer maxEx lenient) =
2088− object ["multi_match" .= omitNulls base]
2089− where base = [ "fields" .= fmap toJSON fields
2091− , "operator" .= boolOp
2092− , "zero_terms_query" .= ztQ
2093− , "tiebreaker" .= tb
2095− , "cutoff_frequency" .= cf
2096− , "analyzer" .= analyzer
2097− , "max_expansions" .= maxEx
2098− , "lenient" .= lenient ]
2101−instance ToJSON MultiMatchQueryType where
2102− toJSON MultiMatchBestFields = "best_fields"
2103− toJSON MultiMatchMostFields = "most_fields"
2104− toJSON MultiMatchCrossFields = "cross_fields"
2105− toJSON MultiMatchPhrase = "phrase"
2106− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2108−instance ToJSON BooleanOperator where
2109− toJSON And = String "and"
2110− toJSON Or = String "or"
2112−instance ToJSON ZeroTermsQuery where
2113− toJSON ZeroTermsNone = String "none"
2114− toJSON ZeroTermsAll = String "all"
2116−instance ToJSON MatchQueryType where
2117− toJSON MatchPhrase = "phrase"
2118− toJSON MatchPhrasePrefix = "phrase_prefix"
2120−instance ToJSON FieldName where
2121− toJSON (FieldName fieldName) = String fieldName
2123−instance ToJSON ReplicaCount
2124−instance ToJSON ShardCount
2125−instance ToJSON CutoffFrequency
2126−instance ToJSON Analyzer
2127−instance ToJSON MaxExpansions
2128−instance ToJSON Lenient
2129−instance ToJSON Boost
2130−instance ToJSON Version
2131−instance ToJSON Tiebreaker
2132−instance ToJSON MinimumMatch
2133−instance ToJSON DisableCoord
2134−instance ToJSON PrefixLength
2135−instance ToJSON Fuzziness
2136−instance ToJSON IgnoreTermFrequency
2137−instance ToJSON MaxQueryTerms
2138−instance ToJSON TypeName
2139−instance ToJSON IndexName
2140−instance ToJSON TemplateName
2141−instance ToJSON TemplatePattern
2142−instance ToJSON BoostTerms
2143−instance ToJSON MaxWordLength
2144−instance ToJSON MinWordLength
2145−instance ToJSON MaxDocFrequency
2146−instance ToJSON MinDocFrequency
2147−instance ToJSON PhraseSlop
2148−instance ToJSON StopWord
2149−instance ToJSON QueryPath
2150−instance ToJSON MinimumTermFrequency
2151−instance ToJSON PercentMatch
2152−instance ToJSON MappingName
2153−instance ToJSON DocId
2154−instance ToJSON QueryString
2155−instance ToJSON AllowLeadingWildcard
2156−instance ToJSON LowercaseExpanded
2157−instance ToJSON AnalyzeWildcard
2158−instance ToJSON GeneratePhraseQueries
2159−instance ToJSON Locale
2160−instance ToJSON EnablePositionIncrements
2161−instance FromJSON Version
2162−instance FromJSON IndexName
2163−instance FromJSON MappingName
2164−instance FromJSON DocId
2167−instance FromJSON Status where
2168− parseJSON (Object v) = Status <$>
2174− parseJSON _ = empty
2177−instance ToJSON IndexSettings where
2178− toJSON (IndexSettings s r) = object ["settings" .=
2180− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2184−instance ToJSON IndexSettingUpdate where
2185− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2186− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2187− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2188− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2189− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2190− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2191− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2192− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2193− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2194− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2195− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2196− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2197− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2198− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2199− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2200− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2201− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2202− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2203− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2204− toJSON (RoutingAllocationDisable x) = oPath ("index" :| ["routing", "allocation", "disable_allocation"]) x
2205− toJSON (RoutingAllocationDisableNew x) = oPath ("index" :| ["routing", "allocation", "disable_new_allocation"]) x
2206− toJSON (RoutingAllocationDisableReplica x) = oPath ("index" :| ["routing", "allocation", "disable_replica_allocation"]) x
2207− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2208− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2209− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2210− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2211− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2212− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2213− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2214− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2215− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2217−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2218−oPath (k :| []) v = object [k .= v]
2219−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2221−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2222−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2223− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2225−instance ToJSON ReplicaBounds where
2226− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2227− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2228− toJSON ReplicasUnbounded = Bool False
2230−instance ToJSON AllocationPolicy where
2231− toJSON AllocAll = String "all"
2232− toJSON AllocPrimaries = String "primaries"
2233− toJSON AllocNewPrimaries = String "new_primaries"
2234− toJSON AllocNone = String "none"
2236−instance ToJSON InitialShardCount where
2237− toJSON QuorumShards = String "quorum"
2238− toJSON QuorumMinus1Shards = String "quorum-1"
2239− toJSON FullShards = String "full"
2240− toJSON FullMinus1Shards = String "full-1"
2241− toJSON (ExplicitShards x) = toJSON x
2243−instance ToJSON FSType where
2244− toJSON FSSimple = "simple"
2245− toJSON FSBuffered = "buffered"
2247−instance ToJSON CompoundFormat where
2248− toJSON (CompoundFileFormat x) = Bool x
2249− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
2251−instance ToJSON NominalDiffTimeJSON where
2252− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
2254−instance ToJSON IndexTemplate where
2255− toJSON (IndexTemplate p s m) = merge
2256− (object [ "template" .= p
2257− , "mappings" .= foldl' merge (object []) m
2261− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
2263− merge _ _ = undefined
2265−instance (FromJSON a) => FromJSON (EsResult a) where
2266− parseJSON jsonVal@(Object v) = do
2267− found <- v .:? "found" .!= False
2269− then parseJSON jsonVal
2270− else return Nothing
2271− EsResult <$> v .: "_index" <*>
2275− parseJSON _ = empty
2277−instance (FromJSON a) => FromJSON (EsResultFound a) where
2278− parseJSON (Object v) = EsResultFound <$>
2279− v .: "_version" <*>
2281− parseJSON _ = empty
2283−instance ToJSON Search where
2284− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
2285− omitNulls [ "query" .= query
2286− , "filter" .= sFilter
2288− , "aggregations" .= searchAggs
2289− , "highlight" .= highlight
2292− , "track_scores" .= sTrackSortScores
2293− , "fields" .= sFields
2294− , "_source" .= sSource]
2297instance ToJSON Source where
490instance ToJSON Source where
2298 toJSON NoSource = toJSON False
491 toJSON NoSource = toJSON False
2299 toJSON (SourcePatterns patterns) = toJSON patterns
492 toJSON (SourcePatterns patterns) = toJSON patterns
2300− 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)
2302instance ToJSON PatternOrPatterns where
498instance ToJSON PatternOrPatterns where
2303 toJSON (PopPattern pattern) = toJSON pattern
499 toJSON (PopPattern pattern) = toJSON pattern
2304 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)
2306instance ToJSON Include where
505instance ToJSON Include where
2307 toJSON (Include patterns) = toJSON patterns
506 toJSON (Include patterns) = toJSON patterns
2309instance ToJSON Exclude where
508instance ToJSON Exclude where
2310 toJSON (Exclude patterns) = toJSON patterns
509 toJSON (Exclude patterns) = toJSON patterns
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
2312instance ToJSON Pattern where
513instance ToJSON Pattern where
2313 toJSON (Pattern pattern) = toJSON pattern
514 toJSON (Pattern pattern) = toJSON pattern
2315−
516+data SearchResult a =
2316−instance ToJSON FieldHighlight where
517+ SearchResult { took :: Int
2317− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
518+ , timedOut :: Bool
2318− object [ fName .= fSettings ]
519+ , shards :: ShardResult
2319− toJSON (FieldHighlight (FieldName fName) Nothing) =
520+ , searchHits :: SearchHits a
2320− object [ fName .= emptyObject ]
521+ , aggregations :: Maybe AggregationResults
2321−
522+ , scrollId :: Maybe ScrollId
2322−instance ToJSON Highlights where
523+ -- ^ Only one Suggestion request / response per
2323− toJSON (Highlights global fields) =
524+ -- Search is supported.
2324− omitNulls (("fields" .= fields)
525+ , suggest :: Maybe NamedSuggestionResponse
2325− : highlightSettingsPairs global)
526+ }
2326−
527+ deriving (Eq, Show)
2327−instance ToJSON HighlightSettings where
2328− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
2330−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
2331−highlightSettingsPairs Nothing = []
2332−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
2333−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
2334−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
2337−plainHighPairs :: Maybe PlainHighlight -> [Pair]
2338−plainHighPairs Nothing = []
2339−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
2340− [ "type" .= String "plain"]
2341− ++ commonHighlightPairs plCom
2342− ++ nonPostingsToPairs plNonPost
2344−postHighPairs :: Maybe PostingsHighlight -> [Pair]
2345−postHighPairs Nothing = []
2346−postHighPairs (Just (PostingsHighlight pCom)) =
2347− ("type" .= String "postings")
2348− : commonHighlightPairs pCom
2350−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
2351−fastVectorHighPairs Nothing = []
2352−fastVectorHighPairs (Just
2353− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
2354− fvBoundMaxScan fvFragOff fvMatchedFields
2356− [ "type" .= String "fvh"
2357− , "boundary_chars" .= fvBoundChars
2358− , "boundary_max_scan" .= fvBoundMaxScan
2359− , "fragment_offset" .= fvFragOff
2360− , "matched_fields" .= fvMatchedFields
2361− , "phraseLimit" .= fvPhraseLim]
2362− ++ commonHighlightPairs fvCom
2363− ++ nonPostingsToPairs fvNonPostSettings
2365−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
2366−commonHighlightPairs Nothing = []
2367−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
2368− chNoMatchSize chHighlightQuery
2369− chRequireFieldMatch)) =
2370− [ "order" .= chScore
2371− , "force_source" .= chForceSource
2372− , "encoder" .= chEncoder
2373− , "no_match_size" .= chNoMatchSize
2374− , "highlight_query" .= chHighlightQuery
2375− , "require_fieldMatch" .= chRequireFieldMatch]
2376− ++ highlightTagToPairs chTag
2379−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
2380−nonPostingsToPairs Nothing = []
2381−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
2382− [ "fragment_size" .= npFragSize
2383− , "number_of_fragments" .= npNumOfFrags]
2387−instance ToJSON HighlightEncoder where
2388− toJSON DefaultEncoder = String "default"
2389− toJSON HTMLEncoder = String "html"
2391−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
2392−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
2393−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
2394− , "post_tags" .= post]
2395−highlightTagToPairs Nothing = []
2397−instance ToJSON SortSpec where
2398− toJSON (DefaultSortSpec
2399− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
2400− dsSortMode dsMissingSort dsNestedFilter)) =
2401− object [dsSortFieldName .= omitNulls base] where
2402− base = [ "order" .= dsSortOrder
2403− , "ignore_unmapped" .= dsIgnoreUnmapped
2404− , "mode" .= dsSortMode
2405− , "missing" .= dsMissingSort
2406− , "nested_filter" .= dsNestedFilter ]
2408− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
2409− object [ "unit" .= units
2410− , field .= gdsLatLon
2411− , "order" .= gdsSortOrder ]
2414−instance ToJSON SortOrder where
2415− toJSON Ascending = String "asc"
2416− toJSON Descending = String "desc"
2419−instance ToJSON SortMode where
2420− toJSON SortMin = String "min"
2421− toJSON SortMax = String "max"
2422− toJSON SortSum = String "sum"
2423− toJSON SortAvg = String "avg"
2426−instance ToJSON Missing where
2427− toJSON LastMissing = String "_last"
2428− toJSON FirstMissing = String "_first"
2429− toJSON (CustomMissing txt) = String txt
2432−instance ToJSON ScoreType where
2433− toJSON ScoreTypeMax = "max"
2434− toJSON ScoreTypeAvg = "avg"
2435− toJSON ScoreTypeSum = "sum"
2436− toJSON ScoreTypeNone = "none"
2439−instance ToJSON Distance where
2440− toJSON (Distance dCoefficient dUnit) =
2441− String boltedTogether where
2442− coefText = showText dCoefficient
2443− (String unitText) = toJSON dUnit
2444− boltedTogether = mappend coefText unitText
2447−instance ToJSON DistanceUnit where
2448− toJSON Miles = String "mi"
2449− toJSON Yards = String "yd"
2450− toJSON Feet = String "ft"
2451− toJSON Inches = String "in"
2452− toJSON Kilometers = String "km"
2453− toJSON Meters = String "m"
2454− toJSON Centimeters = String "cm"
2455− toJSON Millimeters = String "mm"
2456− toJSON NauticalMiles = String "nmi"
2459−instance ToJSON DistanceType where
2460− toJSON Arc = String "arc"
2461− toJSON SloppyArc = String "sloppy_arc"
2462− toJSON Plane = String "plane"
2465−instance ToJSON OptimizeBbox where
2466− toJSON NoOptimizeBbox = String "none"
2467− toJSON (OptimizeGeoFilterType gft) = toJSON gft
2470−instance ToJSON GeoBoundingBoxConstraint where
2471− toJSON (GeoBoundingBoxConstraint
2472− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
2473− object [gbbcGeoBBField .= gbbcConstraintBox
2474− , "_cache" .= cache
2478−instance ToJSON GeoFilterType where
2479− toJSON GeoFilterMemory = String "memory"
2480− toJSON GeoFilterIndexed = String "indexed"
2483−instance ToJSON GeoBoundingBox where
2484− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
2485− object ["top_left" .= gbbTopLeft
2486− , "bottom_right" .= gbbBottomRight]
2489−instance ToJSON LatLon where
2490− toJSON (LatLon lLat lLon) =
2491− object ["lat" .= lLat
2495−-- index for smaller ranges, fielddata for longer ranges
2496−instance ToJSON RangeExecution where
2497− toJSON RangeExecutionIndex = "index"
2498− toJSON RangeExecutionFielddata = "fielddata"
2501−instance ToJSON RegexpFlags where
2502− toJSON AllRegexpFlags = String "ALL"
2503− toJSON NoRegexpFlags = String "NONE"
2504− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
2505− where flagStrs = map flagStr . nub $ h:fs
2506− flagStr AnyString = "ANYSTRING"
2507− flagStr Automaton = "AUTOMATON"
2508− flagStr Complement = "COMPLEMENT"
2509− flagStr Empty = "EMPTY"
2510− flagStr Intersection = "INTERSECTION"
2511− flagStr Interval = "INTERVAL"
2513−instance ToJSON Term where
2514− toJSON (Term field value) = object ["term" .= object
2518−instance ToJSON BoolMatch where
2519− toJSON (MustMatch term cache) = object ["must" .= term,
2521− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
2523− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
2527instance (FromJSON a) => FromJSON (SearchResult a) where
529instance (FromJSON a) => FromJSON (SearchResult a) where
2528 parseJSON (Object v) = SearchResult <$>
530 parseJSON (Object v) = SearchResult <$>
@@ -2531,52 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
2531 v .: "_shards" <*>
533 v .: "_shards" <*>
2532 v .: "hits" <*>
534 v .: "hits" <*>
2533 v .:? "aggregations" <*>
535 v .:? "aggregations" <*>
2534− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
2535− parseJSON _ = empty
537+ v .:? "suggest"
2537−instance (FromJSON a) => FromJSON (SearchHits a) where
2538− parseJSON (Object v) = SearchHits <$>
2540− v .: "max_score" <*>
2542 parseJSON _ = empty
538 parseJSON _ = empty
2544−instance (FromJSON a) => FromJSON (Hit a) where
540+newtype ScrollId =
2545− parseJSON (Object v) = Hit <$>
541+ ScrollId Text
2546− v .: "_index" <*>
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
2552− parseJSON _ = empty
2554−instance FromJSON ShardResult where
2555− parseJSON (Object v) = ShardResult <$>
2557− v .: "successful" <*>
2559− parseJSON _ = empty
2562−instance FromJSON DocVersion where
2565− maybe (fail "DocVersion out of range") return $ mkDocVersion i
2567−instance Bounded DocVersion where
2568− minBound = DocVersion 1
2569− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
2571−instance Enum DocVersion where
2573− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
2574− | otherwise = succError "DocVersion"
2576− | x /= minBound = DocVersion (pred $ docVersionNumber x)
2577− | otherwise = predError "DocVersion"
2579− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
2580− fromEnum = docVersionNumber
2581− enumFrom = boundedEnumFrom
2582− enumFromThen = boundedEnumFromThen