@@ -1,10 +1,7 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE FlexibleContexts #-}
1{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
2{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
7−-- {-# LANGUAGE NoMonomorphismRestriction #-}
8{-# LANGUAGE NamedFieldPuns #-}
5{-# LANGUAGE NamedFieldPuns #-}
9{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
10{-# LANGUAGE RecordWildCards #-}
7{-# LANGUAGE RecordWildCards #-}
@@ -13,11 +10,11 @@
13-------------------------------------------------------------------------------
10-------------------------------------------------------------------------------
15-- Module : Database.Bloodhound.Types
12-- Module : Database.Bloodhound.Types
16−-- Copyright : (C) 2014, 2015, 2016 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
17-- License : BSD-style (see the file LICENSE)
14-- License : BSD-style (see the file LICENSE)
18-- Maintainer : Chris Allen <cma@bitemyapp.com
15-- Maintainer : Chris Allen <cma@bitemyapp.com
19-- Stability : provisional
16-- Stability : provisional
20−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
22-- Data types for describing actions and data structures performed to interact
19-- Data types for describing actions and data structures performed to interact
23-- with Elasticsearch. The two main buckets your queries against Elasticsearch
20-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -45,11 +42,15 @@ module Database.Bloodhound.Types
45 , mkTermsAggregation
42 , mkTermsAggregation
46 , mkTermsScriptAggregation
43 , mkTermsScriptAggregation
47 , mkDateHistogram
44 , mkDateHistogram
45+ , mkCardinalityAggregation
48 , mkDocVersion
46 , mkDocVersion
48+ , mkExtendedStatsAggregation
49 , docVersionNumber
49 , docVersionNumber
50 , toMissing
50 , toMissing
52 , toDateHistogram
52 , toDateHistogram
53 , omitNulls
54 , omitNulls
@@ -60,6 +61,9 @@ module Database.Bloodhound.Types
61 , MonadBH(..)
62 , MonadBH(..)
62 , Version(..)
63 , Version(..)
63 , Status(..)
67 , Status(..)
64 , Existence(..)
68 , Existence(..)
65 , NullValue(..)
69 , NullValue(..)
@@ -67,6 +71,7 @@ module Database.Bloodhound.Types
67 , UpdatableIndexSetting(..)
71 , UpdatableIndexSetting(..)
68 , IndexSettingsSummary(..)
72 , IndexSettingsSummary(..)
69 , AllocationPolicy(..)
73 , AllocationPolicy(..)
70 , ReplicaBounds(..)
75 , ReplicaBounds(..)
71 , Bytes(..)
76 , Bytes(..)
72 , gigabytes
77 , gigabytes
@@ -115,8 +120,8 @@ module Database.Bloodhound.Types
115 , Pattern(..)
120 , Pattern(..)
116 , ShardResult(..)
121 , ShardResult(..)
117 , Hit(..)
122 , Hit(..)
118 , Filter(..)
124 , Filter(..)
120 , BoolMatch(..)
125 , BoolMatch(..)
121 , Term(..)
126 , Term(..)
122 , GeoPoint(..)
127 , GeoPoint(..)
@@ -143,11 +148,22 @@ module Database.Bloodhound.Types
143 , RegexpFlags(..)
148 , RegexpFlags(..)
144 , RegexpFlag(..)
149 , RegexpFlag(..)
145 , FieldName(..)
150 , FieldName(..)
146 , Script(..)
154 , Script(..)
155+ , ScriptLanguage(..)
147 , IndexName(..)
161 , IndexName(..)
148 , IndexSelection(..)
162 , IndexSelection(..)
149− , IndexOptimizationSettings(..)
163+ , NodeSelection(..)
150− , defaultIndexOptimizationSettings
164+ , NodeSelector(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
151 , TemplateName(..)
167 , TemplateName(..)
152 , TemplatePattern(..)
168 , TemplatePattern(..)
153 , MappingName(..)
169 , MappingName(..)
@@ -171,8 +187,19 @@ module Database.Bloodhound.Types
171 , BoolQuery(..)
187 , BoolQuery(..)
172 , BoostingQuery(..)
188 , BoostingQuery(..)
173 , CommonTermsQuery(..)
189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
198+ , FieldValueFactor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
174 , DisMaxQuery(..)
202 , DisMaxQuery(..)
176 , FuzzyLikeThisQuery(..)
203 , FuzzyLikeThisQuery(..)
177 , FuzzyLikeFieldQuery(..)
204 , FuzzyLikeFieldQuery(..)
178 , FuzzyQuery(..)
205 , FuzzyQuery(..)
@@ -188,10 +215,16 @@ module Database.Bloodhound.Types
188 , RangeQuery(..)
215 , RangeQuery(..)
189 , RegexpQuery(..)
216 , RegexpQuery(..)
190 , QueryString(..)
217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
191 , BooleanOperator(..)
221 , BooleanOperator(..)
192 , ZeroTermsQuery(..)
222 , ZeroTermsQuery(..)
193 , CutoffFrequency(..)
223 , CutoffFrequency(..)
194 , Analyzer(..)
224 , Analyzer(..)
195 , MaxExpansions(..)
228 , MaxExpansions(..)
196 , Lenient(..)
229 , Lenient(..)
197 , MatchQueryType(..)
230 , MatchQueryType(..)
@@ -252,6 +285,51 @@ module Database.Bloodhound.Types
252 , SnapshotNodeVerification(..)
285 , SnapshotNodeVerification(..)
253 , FullNodeId(..)
286 , FullNodeId(..)
254 , NodeName(..)
287 , NodeName(..)
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(..)
255 , FsSnapshotRepo(..)
333 , FsSnapshotRepo(..)
256 , SnapshotCreateSettings(..)
334 , SnapshotCreateSettings(..)
257 , defaultSnapshotCreateSettings
335 , defaultSnapshotCreateSettings
@@ -270,6 +348,18 @@ module Database.Bloodhound.Types
270 , rrGroupRefNum
348 , rrGroupRefNum
271 , mkRRGroupRefNum
349 , mkRRGroupRefNum
272 , RestoreIndexSettings(..)
350 , RestoreIndexSettings(..)
353+ , PhraseSuggester(..)
354+ , PhraseSuggesterHighlighter(..)
355+ , PhraseSuggesterCollate(..)
357+ , SuggestOptions(..)
358+ , SuggestResponse(..)
359+ , NamedSuggestionResponse(..)
360+ , DirectGenerators(..)
361+ , mkDirectGenerators
362+ , DirectGeneratorSuggestModeTypes (..)
274 , Aggregation(..)
364 , Aggregation(..)
275 , Aggregations
365 , Aggregations
@@ -281,6 +371,8 @@ module Database.Bloodhound.Types
281 , MissingAggregation(..)
371 , MissingAggregation(..)
282 , ValueCountAggregation(..)
372 , ValueCountAggregation(..)
283 , FilterAggregation(..)
373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
284 , DateHistogramAggregation(..)
376 , DateHistogramAggregation(..)
285 , DateRangeAggregation(..)
377 , DateRangeAggregation(..)
286 , DateRangeAggRange(..)
378 , DateRangeAggRange(..)
@@ -288,6 +380,9 @@ module Database.Bloodhound.Types
288 , DateMathAnchor(..)
380 , DateMathAnchor(..)
289 , DateMathModifier(..)
381 , DateMathModifier(..)
290 , DateMathUnit(..)
382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
292 , Highlights(..)
387 , Highlights(..)
293 , FieldHighlight(..)
388 , FieldHighlight(..)
@@ -305,698 +400,32 @@ module Database.Bloodhound.Types
305 , TermsResult(..)
400 , TermsResult(..)
306 , DateHistogramResult(..)
401 , DateHistogramResult(..)
307 , DateRangeResult(..)
402 , DateRangeResult(..)
309 , EsUsername(..)
405 , EsUsername(..)
310 , EsPassword(..)
406 , EsPassword(..)
313−import Control.Applicative as A
408+ , Analysis(..)
314−import Control.Monad.Catch
409+ , AnalyzerDefinition(..)
315−import Control.Monad.Except
410+ , TokenizerDefinition(..)
316−import Control.Monad.Reader
411+ , TokenFilterDefinition(..)
317−import Control.Monad.State
412+ , CharFilterDefinition(..)
318−import Control.Monad.Writer
413+ , Ngram(..)
319−import Data.Aeson
414+ , TokenChar(..)
320−import Data.Aeson.Types (Pair, Parser, emptyObject,
415+ , Shingle(..)
321− parseEither, parseMaybe)
416+ , Language(..)
322−import qualified Data.ByteString.Lazy.Char8 as L
417+ ) where
324−import Data.Hashable (Hashable)
419+import Bloodhound.Import
325−import qualified Data.HashMap.Strict as HM
420+
326−import Data.List (foldl', nub)
421+import Database.Bloodhound.Internal.Aggregation
327−import Data.List.NonEmpty (NonEmpty (..), toList)
422+import Database.Bloodhound.Internal.Analysis
328−import qualified Data.Map.Strict as M
423+import Database.Bloodhound.Internal.Client
329−import Data.Maybe
424+import Database.Bloodhound.Internal.Highlight
330−import Data.Scientific (Scientific)
425+import Database.Bloodhound.Internal.Newtypes
331−import Data.Text (Text)
426+import Database.Bloodhound.Internal.Query
332−import qualified Data.Text as T
427+import Database.Bloodhound.Internal.Sort
333−import Data.Time.Calendar
428+import Database.Bloodhound.Internal.Suggest
334−import Data.Time.Clock (NominalDiffTime, UTCTime)
335−import Data.Time.Clock.POSIX
336−import qualified Data.Traversable as DT
337−import Data.Typeable (Typeable)
338−import qualified Data.Vector as V
340−import GHC.Generics (Generic)
341−import Network.HTTP.Client
342−import qualified Network.HTTP.Types.Method as NHTM
343−import qualified Text.Read as TR
345−import Database.Bloodhound.Types.Class
346−import Database.Bloodhound.Types.Internal
349−-- >>> :set -XOverloadedStrings
350−-- >>> import Data.Aeson
351−-- >>> import Database.Bloodhound
352−-- >>> let testServer = (Server "http://localhost:9200")
353−-- >>> let testIndex = IndexName "twitter"
354−-- >>> let testMapping = MappingName "tweet"
355−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
357−-- defaultIndexSettings is exported by Database.Bloodhound as well
358−-- no trailing slashes in servers, library handles building the path.
360−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
361−-- will be a noop. You can use the exported fields to customize it further, e.g.:
363−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
364−mkBHEnv :: Server -> Manager -> BHEnv
365−mkBHEnv s m = BHEnv s m return
367−newtype BH m a = BH {
368− unBH :: ReaderT BHEnv m a
369− } deriving ( Functor
383−instance MonadTrans BH where
386−instance (MonadReader r m) => MonadReader r (BH m) where
388− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
391−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
392− getBHEnv = BH getBHEnv
394−runBH :: BHEnv -> BH m a -> m a
395−runBH e f = runReaderT (unBH f) e
397−{-| 'Version' is embedded in 'Status' -}
398−data Version = Version { number :: Text
399− , build_hash :: Text
400− , build_timestamp :: UTCTime
401− , build_snapshot :: Bool
402− , lucene_version :: Text } deriving (Eq, Read, Show, Generic, Typeable)
404−{-| 'Status' is a data type for describing the JSON body returned by
405− Elasticsearch when you query its status. This was deprecated in 1.2.0.
407− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
410−data Status = Status { ok :: Maybe Bool
413− , version :: Version
414− , tagline :: Text } deriving (Eq, Read, Show, Generic)
416−{-| 'IndexSettings' is used to configure the shards and replicas when you create
417− an Elasticsearch Index.
419− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
423− IndexSettings { indexShards :: ShardCount
424− , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
426−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
427−defaultIndexSettings :: IndexSettings
428−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
431−{-| 'IndexOptimizationSettings' is used to configure index optimization. See
432− <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
435−data IndexOptimizationSettings =
436− IndexOptimizationSettings { maxNumSegments :: Maybe Int
437− -- ^ Number of segments to optimize to. 1 will fully optimize the index. If omitted, the default behavior is to only optimize if the server deems it necessary.
438− , onlyExpungeDeletes :: Bool
439− -- ^ Should the optimize process only expunge segments with deletes in them? If the purpose of the optimization is to free disk space, this should be set to True.
440− , flushAfterOptimize :: Bool
441− -- ^ Should a flush be performed after the optimize.
442− } deriving (Eq, Show, Generic, Typeable)
445−{-| 'defaultIndexOptimizationSettings' implements the default settings that
446− ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
447− 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
449−defaultIndexOptimizationSettings :: IndexOptimizationSettings
450−defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
452−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
454− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
456−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
457− -- ^ The number of replicas each shard has.
458− | AutoExpandReplicas ReplicaBounds
459− | BlocksReadOnly Bool
460− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
462− -- ^ Set to True to disable read operations against the index.
464− -- ^ Set to True to disable write operations against the index.
465− | BlocksMetaData Bool
466− -- ^ Set to True to disable metadata operations against the index.
467− | RefreshInterval NominalDiffTime
468− -- ^ The async refresh interval of a shard
469− | IndexConcurrency Int
470− | FailOnMergeFailure Bool
471− | TranslogFlushThresholdOps Int
472− -- ^ When to flush on operations.
473− | TranslogFlushThresholdSize Bytes
474− -- ^ When to flush based on translog (bytes) size.
475− | TranslogFlushThresholdPeriod NominalDiffTime
476− -- ^ When to flush based on a period of not flushing.
477− | TranslogDisableFlush Bool
478− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
479− | CacheFilterMaxSize (Maybe Bytes)
480− -- ^ The maximum size of filter cache (per segment in shard).
481− | CacheFilterExpire (Maybe NominalDiffTime)
482− -- ^ The expire after access time for filter cache.
483− | GatewaySnapshotInterval NominalDiffTime
484− -- ^ The gateway snapshot interval (only applies to shared gateways).
485− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
486− -- ^ A node matching any rule will be allowed to host shards from the index.
487− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
488− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
489− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
490− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
491− | RoutingAllocationEnable AllocationPolicy
492− -- ^ Enables shard allocation for a specific index.
493− | RoutingAllocationShardsPerNode ShardCount
494− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
495− | RecoveryInitialShards InitialShardCount
496− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
497− | GCDeletes NominalDiffTime
498− | TTLDisablePurge Bool
499− -- ^ Disables temporarily the purge of expired docs.
500− | TranslogFSType FSType
501− | IndexCompoundFormat CompoundFormat
502− | IndexCompoundOnFlush Bool
503− | WarmerEnabled Bool
504− deriving (Eq, Show, Generic, Typeable)
506−data AllocationPolicy = AllocAll
507− -- ^ Allows shard allocation for all shards.
509− -- ^ Allows shard allocation only for primary shards.
511− -- ^ Allows shard allocation only for primary shards for new indices.
513− -- ^ No shard allocation is allowed
514− deriving (Eq, Read, Show, Generic, Typeable)
516−data ReplicaBounds = ReplicasBounded Int Int
517− | ReplicasLowerBounded Int
519− deriving (Eq, Read, Show, Generic, Typeable)
521−-- | A measure of bytes used for various configurations. You may want
522−-- to use smart constructors like 'gigabytes' for larger values.
532−newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
534−gigabytes :: Int -> Bytes
535−gigabytes n = megabytes (1000 * n)
538−megabytes :: Int -> Bytes
539−megabytes n = kilobytes (1000 * n)
542−kilobytes :: Int -> Bytes
543−kilobytes n = Bytes (1000 * n)
546−data FSType = FSSimple
547− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
549−data InitialShardCount = QuorumShards
550− | QuorumMinus1Shards
553− | ExplicitShards Int
554− deriving (Eq, Read, Show, Generic, Typeable)
556−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
557− , nodeAttrFilterValues :: NonEmpty Text}
558− deriving (Eq, Read, Show, Generic, Ord)
560−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
562−data CompoundFormat = CompoundFileFormat Bool
563− | MergeSegmentVsTotalIndex Double
564− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
565− deriving (Eq, Read, Show, Generic, Typeable)
567−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
569−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
570− , sSummaryFixedSettings :: IndexSettings
571− , sSummaryUpdateable :: [UpdatableIndexSetting]}
572− deriving (Eq, Show, Generic, Typeable)
574−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
575−type Reply = Network.HTTP.Client.Response L.ByteString
576−type Method = NHTM.Method
578−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
580− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
582−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
584−data FieldType = GeoPointType
590− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
592−data FieldDefinition =
593− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
595−{-| An 'IndexTemplate' defines a template that will automatically be
596− applied to new indices created. The templates include both
597− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
598− controls if the template will be applied to the index created.
599− Specify mappings as follows: @[toJSON TweetMapping, ...]@
601− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
604− IndexTemplate { templatePattern :: TemplatePattern
605− , templateSettings :: Maybe IndexSettings
606− , templateMappings :: [Value]
610− MappingField { mappingFieldName :: FieldName
611− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
613−{-| Support for type reification of 'Mapping's is currently incomplete, for
614− now the mapping API verbiage expects a 'ToJSON'able blob.
616− Indexes have mappings, mappings are schemas for the documents contained in the
617− index. I'd recommend having only one mapping per index, always having a mapping,
618− and keeping different kinds of documents separated if possible.
620−data Mapping = Mapping { typeName :: TypeName
621− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
623−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
624− operation index, create, delete, and update. 'BulkIndex' behaves like an
625− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
627− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
630− BulkIndex IndexName MappingName DocId Value
631− | BulkCreate IndexName MappingName DocId Value
632− | BulkDelete IndexName MappingName DocId
633− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
635−{-| 'EsResult' describes the standard wrapper JSON document that you see in
636− successful Elasticsearch lookups or lookups that couldn't find the document.
638−data EsResult a = EsResult { _index :: Text
641− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
643−{-| 'EsResultFound' contains the document and its metadata inside of an
644− 'EsResult' when the document was successfully found.
646−data EsResultFound a = EsResultFound { _version :: DocVersion
647− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
649−{-| 'EsError' is the generic type that will be returned when there was a
650− problem. If you can't parse the expected response, its a good idea to
653−data EsError = EsError { errorStatus :: Int
654− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
656−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
657−returned by the ElasticSearch server. If you encounter this error, please
658−verify that your domain data types and FromJSON instances are working properly
659−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
660−sure that your mappings are correct, then this error may be an indication of an
661−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
662−and be sure to include the exception body.
664−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
665− deriving (Eq, Read, Show, Generic, Typeable)
667−instance Exception EsProtocolException
669−data IndexAlias = IndexAlias { srcIndex :: IndexName
670− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
672−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
674−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
675− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
677−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
678− , aliasCreateFilter :: Maybe Filter}
679− deriving (Read, Show, Eq, Generic, Typeable)
681−data AliasRouting = AllAliasRouting RoutingValue
682− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
683− deriving (Read, Show, Eq, Generic, Typeable)
685−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
687−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
689−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
691−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
693−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
694−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
695− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
697−{-| 'DocVersion' is an integer version number for a document between 1
698−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
700−newtype DocVersion = DocVersion {
701− docVersionNumber :: Int
702− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
704−-- | Smart constructor for in-range doc version
705−mkDocVersion :: Int -> Maybe DocVersion
707− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
709− | otherwise = Nothing
712−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
713−own version numbers instead of ones from ES.
715−newtype ExternalDocVersion = ExternalDocVersion DocVersion
716− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
718−{-| 'VersionControl' is specified when indexing documents as a
719−optimistic concurrency control.
721−data VersionControl = NoVersionControl
722− -- ^ Don't send a version. This is a pure overwrite.
723− | InternalVersion DocVersion
724− -- ^ Use the default ES versioning scheme. Only
725− -- index the document if the version is the same
726− -- as the one specified. Only applicable to
727− -- updates, as you should be getting Version from
729− | ExternalGT ExternalDocVersion
730− -- ^ Use your own version numbering. Only index
731− -- the document if the version is strictly higher
732− -- OR the document doesn't exist. The given
733− -- version will be used as the new version number
734− -- for the stored document. N.B. All updates must
735− -- increment this number, meaning there is some
736− -- global, external ordering of updates.
737− | ExternalGTE ExternalDocVersion
738− -- ^ Use your own version numbering. Only index
739− -- the document if the version is equal or higher
740− -- than the stored version. Will succeed if there
741− -- is no existing document. The given version will
742− -- be used as the new version number for the
743− -- stored document. Use with care, as this could
744− -- result in data loss.
745− | ForceVersion ExternalDocVersion
746− -- ^ The document will always be indexed and the
747− -- given version will be the new version. This is
748− -- typically used for correcting errors. Use with
749− -- care, as this could result in data loss.
750− deriving (Read, Show, Eq, Generic, Ord)
752−{-| 'DocumentParent' is used to specify a parent document.
754−newtype DocumentParent = DocumentParent DocId
755− deriving (Eq, Read, Show, Generic, Typeable)
757−{-| 'IndexDocumentSettings' are special settings supplied when indexing
758−a document. For the best backwards compatiblity when new fields are
759−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
761−data IndexDocumentSettings =
762− IndexDocumentSettings { idsVersionControl :: VersionControl
763− , idsParent :: Maybe DocumentParent
764− } deriving (Eq, Read, Show, Generic, Typeable)
766−{-| Reasonable default settings. Chooses no version control and no parent.
768−defaultIndexDocumentSettings :: IndexDocumentSettings
769−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
771−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
772− dependent with later sorts acting as tie-breakers for earlier sorts.
774−type Sort = [SortSpec]
776−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
777− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
778− 'DistanceUnit' to express "nearness" to a single geographical point as a
781−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
783−data SortSpec = DefaultSortSpec DefaultSort
784− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
786−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
787− 'mkSort' convenience function for when you want to specify only the most
790−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
793− DefaultSort { sortFieldName :: FieldName
794− , sortOrder :: SortOrder
796− , ignoreUnmapped :: Bool
797− , sortMode :: Maybe SortMode
798− , missingSort :: Maybe Missing
799− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
801−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
802− encoded into "asc" or "desc" when turned into JSON.
804−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
806−data SortOrder = Ascending
807− | Descending deriving (Eq, Read, Show, Generic, Typeable)
809−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
810− sorted last, first, or using a custom value as a substitute.
812−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
814−data Missing = LastMissing
816− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
818−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
820−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
822−data SortMode = SortMin
825− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
827−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
828− that you can concisely describe the usual kind of 'SortSpec's you want.
830−mkSort :: FieldName -> SortOrder -> DefaultSort
831−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
833−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
834− 'Query's cannot be cached.
836−type Cache = Bool -- caching on/off
837−defaultCache :: Cache
840−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
842−type PrefixValue = Text
844−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
845− JSON encoding baked in. Used all over the place.
847−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
849−{-| 'ShardCount' is part of 'IndexSettings'
851−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
853−{-| 'ReplicaCount' is part of 'IndexSettings'
855−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
857−{-| 'IndexName' is used to describe which index to query/create/delete
859−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
861−{-| 'IndexSelection' is used for APIs which take a single index, a list of
862− indexes, or the special @_all@ index.
864−--TODO: this does not fully support <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/multi-index.html multi-index syntax>. It wouldn't be too hard to implement but you'd have to add the optional parameters (ignore_unavailable, allow_no_indices, expand_wildcards) to any APIs using it. Also would be a breaking API.
865−data IndexSelection = IndexList (NonEmpty IndexName)
866− | AllIndexes deriving (Eq, Generic, Show, Typeable)
868−{-| 'TemplateName' is used to describe which template to query/create/delete
870−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
872−{-| 'TemplatePattern' represents a pattern which is matched against index names
874−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
876−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
877− the data in the indices.
879−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
881−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
882− Can be set by the user or created by ES itself. Often used in client
883− functions for poking at specific documents.
885−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
887−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
889−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
891−{-| 'FieldName' is used all over the place wherever a specific field within
892− a document needs to be specified, usually in 'Query's or 'Filter's.
894−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
897−{-| 'Script' is often used in place of 'FieldName' to specify more
898−complex ways of extracting a value from a document.
900−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
902−{-| 'CacheName' is used in 'RegexpFilter' for describing the
903− 'CacheKey' keyed caching behavior.
905−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
907−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
910− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
912− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
914− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
915−newtype CutoffFrequency =
916− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
918− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
919−newtype MaxExpansions =
920− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
922−{-| 'Lenient', if set to true, will cause format based failures to be
923− ignored. I don't know what the bloody default is, Elasticsearch
924− documentation didn't say what it was. Let me know if you figure it out.
927− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
929− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
931− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
933− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
935−{-| 'MinimumMatch' controls how many should clauses in the bool query should
936− match. Can be an absolute value (2) or a percentage (30%) or a
937− combination of both.
939−newtype MinimumMatch =
940− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
941−newtype DisableCoord =
942− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
943−newtype IgnoreTermFrequency =
944− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
945−newtype MinimumTermFrequency =
946− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
947−newtype MaxQueryTerms =
948− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
950− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
952−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
953−newtype PrefixLength =
954− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
956− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
957−newtype PercentMatch =
958− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
960− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
962− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
964−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
965− heavy, because all terms in the index need to be examined, just in case
966− they match. Leading wildcards can be disabled by setting
967− 'AllowLeadingWildcard' to false. -}
968−newtype AllowLeadingWildcard =
969− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
970−newtype LowercaseExpanded =
971− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
972−newtype EnablePositionIncrements =
973− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
975−{-| By default, wildcard terms in a query are not analyzed.
976− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
978−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
980−{-| 'GeneratePhraseQueries' defaults to false.
982−newtype GeneratePhraseQueries =
983− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
985−{-| 'Locale' is used for string conversions - defaults to ROOT.
987−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
988−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
989−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
991−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
992− phrase matches. Default is 0.
994−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
995−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
996−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
998−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
999−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
1001{-| 'unpackId' is a silly convenience function that gets used once.
430{-| 'unpackId' is a silly convenience function that gets used once.
@@ -1004,8 +433,6 @@ unpackId :: DocId -> Text
1004unpackId (DocId docId) = docId
433unpackId (DocId docId) = docId
1006type TrackSortScores = Bool
435type TrackSortScores = Bool
1007−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1008−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
1010data Search = Search { queryBody :: Maybe Query
437data Search = Search { queryBody :: Maybe Query
1011 , filterBody :: Maybe Filter
438 , filterBody :: Maybe Filter
@@ -1017,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
1017 , from :: From
444 , from :: From
1018 , size :: Size
445 , size :: Size
1019 , searchType :: SearchType
446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
1020 , fields :: Maybe [FieldName]
448 , fields :: Maybe [FieldName]
449+ , scriptFields :: Maybe ScriptFields
1021− , source :: Maybe Source } deriving (Eq, Read, Show, Generic, Typeable)
450+ , source :: Maybe Source
451+ , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
452+ } deriving (Eq, Show)
455+instance ToJSON Search where
456+ toJSON (Search mquery sFilter sort searchAggs
457+ highlight sTrackSortScores sFrom sSize _ sAfter sFields
458+ sScriptFields sSource sSuggest) =
459+ omitNulls [ "query" .= query'
461+ , "aggregations" .= searchAggs
462+ , "highlight" .= highlight
465+ , "track_scores" .= sTrackSortScores
466+ , "search_after" .= sAfter
467+ , "fields" .= sFields
468+ , "script_fields" .= sScriptFields
469+ , "_source" .= sSource
470+ , "suggest" .= sSuggest]
472+ where query' = case sFilter of
477+ $ mkBoolQuery (maybeToList mquery)
1023data SearchType = SearchTypeQueryThenFetch
480data SearchType = SearchTypeQueryThenFetch
1024 | SearchTypeDfsQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
1027− | SearchTypeQueryAndFetch
1028− | SearchTypeDfsQueryAndFetch
1029− deriving (Eq, Read, Show, Generic, Typeable)
482+ deriving (Eq, Show)
1031data Source =
484data Source =
1032 NoSource
485 NoSource
1033 | SourcePatterns PatternOrPatterns
486 | SourcePatterns PatternOrPatterns
1034 | SourceIncludeExclude Include Exclude
487 | SourceIncludeExclude Include Exclude
1035− deriving (Read, Show, Eq, Generic, Typeable)
488+ deriving (Eq, Show)
1037−data PatternOrPatterns = PopPattern Pattern
1038− | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1040−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1041−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1043−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
1045−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1046− , highlightFields :: [FieldHighlight]
1047− } deriving (Read, Show, Eq, Generic, Typeable)
1049−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1050− deriving (Read, Show, Eq, Generic, Typeable)
1053−data HighlightSettings = Plain PlainHighlight
1054− | Postings PostingsHighlight
1055− | FastVector FastVectorHighlight
1056− deriving (Read, Show, Eq, Generic, Typeable)
1057−data PlainHighlight =
1058− PlainHighlight { plainCommon :: Maybe CommonHighlight
1059− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1061− -- This requires that index_options are set to 'offset' in the mapping.
1062−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1064−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1065−data FastVectorHighlight =
1066− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1067− , fvNonPostSettings :: Maybe NonPostings
1068− , boundaryChars :: Maybe Text
1069− , boundaryMaxScan :: Maybe Int
1070− , fragmentOffset :: Maybe Int
1071− , matchedFields :: [Text]
1072− , phraseLimit :: Maybe Int
1073− } deriving (Read, Show, Eq, Generic, Typeable)
1075−data CommonHighlight =
1076− CommonHighlight { order :: Maybe Text
1077− , forceSource :: Maybe Bool
1078− , tag :: Maybe HighlightTag
1079− , encoder :: Maybe HighlightEncoder
1080− , noMatchSize :: Maybe Int
1081− , highlightQuery :: Maybe Query
1082− , requireFieldMatch :: Maybe Bool
1083− } deriving (Read, Show, Eq, Generic, Typeable)
1085−-- Settings that are only applicable to FastVector and Plain highlighters.
1087− NonPostings { fragmentSize :: Maybe Int
1088− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1090−data HighlightEncoder = DefaultEncoder
1092− deriving (Read, Show, Eq, Generic, Typeable)
1094−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1095−data HighlightTag = TagSchema Text
1096− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1097− deriving (Read, Show, Eq, Generic, Typeable)
1101− TermQuery Term (Maybe Boost)
1102− | TermsQuery Text (NonEmpty Text)
1103− | QueryMatchQuery MatchQuery
1104− | QueryMultiMatchQuery MultiMatchQuery
1105− | QueryBoolQuery BoolQuery
1106− | QueryBoostingQuery BoostingQuery
1107− | QueryCommonTermsQuery CommonTermsQuery
1108− | ConstantScoreFilter Filter Boost
1109− | ConstantScoreQuery Query Boost
1110− | QueryDisMaxQuery DisMaxQuery
1111− | QueryFilteredQuery FilteredQuery
1112− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1113− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1114− | QueryFuzzyQuery FuzzyQuery
1115− | QueryHasChildQuery HasChildQuery
1116− | QueryHasParentQuery HasParentQuery
1117− | IdsQuery MappingName [DocId]
1118− | QueryIndicesQuery IndicesQuery
1119− | MatchAllQuery (Maybe Boost)
1120− | QueryMoreLikeThisQuery MoreLikeThisQuery
1121− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1122− | QueryNestedQuery NestedQuery
1123− | QueryPrefixQuery PrefixQuery
1124− | QueryQueryStringQuery QueryStringQuery
1125− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1126− | QueryRangeQuery RangeQuery
1127− | QueryRegexpQuery RegexpQuery
1128− deriving (Eq, Read, Show, Generic, Typeable)
1131− RegexpQuery { regexpQueryField :: FieldName
1132− , regexpQuery :: Regexp
1133− , regexpQueryFlags :: RegexpFlags
1134− , regexpQueryBoost :: Maybe Boost
1135− } deriving (Eq, Read, Show, Generic, Typeable)
1138− RangeQuery { rangeQueryField :: FieldName
1139− , rangeQueryRange :: RangeValue
1140− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1142−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1143−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1145−data SimpleQueryStringQuery =
1146− SimpleQueryStringQuery
1147− { simpleQueryStringQuery :: QueryString
1148− , simpleQueryStringField :: Maybe FieldOrFields
1149− , simpleQueryStringOperator :: Maybe BooleanOperator
1150− , simpleQueryStringAnalyzer :: Maybe Analyzer
1151− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1152− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1153− , simpleQueryStringLocale :: Maybe Locale
1154− } deriving (Eq, Read, Show, Generic, Typeable)
1156−data SimpleQueryFlag =
1161− | SimpleQueryPrefix
1162− | SimpleQueryPhrase
1163− | SimpleQueryPrecedence
1164− | SimpleQueryEscape
1165− | SimpleQueryWhitespace
1168− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1170−-- use_dis_max and tie_breaker when fields are plural?
1171−data QueryStringQuery =
1173− { queryStringQuery :: QueryString
1174− , queryStringDefaultField :: Maybe FieldName
1175− , queryStringOperator :: Maybe BooleanOperator
1176− , queryStringAnalyzer :: Maybe Analyzer
1177− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1178− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1179− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1180− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1181− , queryStringFuzziness :: Maybe Fuzziness
1182− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1183− , queryStringPhraseSlop :: Maybe PhraseSlop
1184− , queryStringBoost :: Maybe Boost
1185− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1186− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1187− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1188− , queryStringLenient :: Maybe Lenient
1189− , queryStringLocale :: Maybe Locale
1190− } deriving (Eq, Read, Show, Generic, Typeable)
1192−mkQueryStringQuery :: QueryString -> QueryStringQuery
1193−mkQueryStringQuery qs =
1194− QueryStringQuery qs Nothing Nothing
1195− Nothing Nothing Nothing Nothing
1196− Nothing Nothing Nothing Nothing
1197− Nothing Nothing Nothing Nothing
1200−data FieldOrFields = FofField FieldName
1201− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1205− { prefixQueryField :: FieldName
1206− , prefixQueryPrefixValue :: Text
1207− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1209−data NestedQuery =
490+instance ToJSON Source where
1210− NestedQuery
491+ toJSON NoSource = toJSON False
1211− { nestedQueryPath :: QueryPath
492+ toJSON (SourcePatterns patterns) = toJSON patterns
1212− , nestedQueryScoreType :: ScoreType
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1213− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1215−data MoreLikeThisFieldQuery =
1216− MoreLikeThisFieldQuery
1217− { moreLikeThisFieldText :: Text
1218− , moreLikeThisFieldFields :: FieldName
1219− -- default 0.3 (30%)
1220− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1221− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1222− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1223− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1224− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1225− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1226− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1227− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1228− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1229− , moreLikeThisFieldBoost :: Maybe Boost
1230− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1231− } deriving (Eq, Read, Show, Generic, Typeable)
1233−data MoreLikeThisQuery =
1235− { moreLikeThisText :: Text
1236− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1237− -- default 0.3 (30%)
1238− , moreLikeThisPercentMatch :: Maybe PercentMatch
1239− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1240− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1241− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1242− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1243− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1244− , moreLikeThisMinWordLength :: Maybe MinWordLength
1245− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1246− , moreLikeThisBoostTerms :: Maybe BoostTerms
1247− , moreLikeThisBoost :: Maybe Boost
1248− , moreLikeThisAnalyzer :: Maybe Analyzer
1249− } deriving (Eq, Read, Show, Generic, Typeable)
1253− { indicesQueryIndices :: [IndexName]
1254− , indicesQuery :: Query
1256− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1258−data HasParentQuery =
1260− { hasParentQueryType :: TypeName
1261− , hasParentQuery :: Query
1262− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1264−data HasChildQuery =
1266− { hasChildQueryType :: TypeName
1267− , hasChildQuery :: Query
1268− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1274− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1277− FuzzyQuery { fuzzyQueryField :: FieldName
1278− , fuzzyQueryValue :: Text
1279− , fuzzyQueryPrefixLength :: PrefixLength
1280− , fuzzyQueryMaxExpansions :: MaxExpansions
1281− , fuzzyQueryFuzziness :: Fuzziness
1282− , fuzzyQueryBoost :: Maybe Boost
1283− } deriving (Eq, Read, Show, Generic, Typeable)
1285−data FuzzyLikeFieldQuery =
1286− FuzzyLikeFieldQuery
1287− { fuzzyLikeField :: FieldName
1288− -- anaphora is good for the soul.
1289− , fuzzyLikeFieldText :: Text
1290− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1291− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1292− , fuzzyLikeFieldFuzziness :: Fuzziness
1293− , fuzzyLikeFieldPrefixLength :: PrefixLength
1294− , fuzzyLikeFieldBoost :: Boost
1295− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1296− } deriving (Eq, Read, Show, Generic, Typeable)
1298−data FuzzyLikeThisQuery =
1300− { fuzzyLikeFields :: [FieldName]
1301− , fuzzyLikeText :: Text
1302− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1303− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1304− , fuzzyLikeFuzziness :: Fuzziness
1305− , fuzzyLikePrefixLength :: PrefixLength
1306− , fuzzyLikeBoost :: Boost
1307− , fuzzyLikeAnalyzer :: Maybe Analyzer
1308− } deriving (Eq, Read, Show, Generic, Typeable)
1310−data FilteredQuery =
1312− { filteredQuery :: Query
1313− , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1316− DisMaxQuery { disMaxQueries :: [Query]
1318− , disMaxTiebreaker :: Tiebreaker
1319− , disMaxBoost :: Maybe Boost
1320− } deriving (Eq, Read, Show, Generic, Typeable)
1323− MatchQuery { matchQueryField :: FieldName
1324− , matchQueryQueryString :: QueryString
1325− , matchQueryOperator :: BooleanOperator
1326− , matchQueryZeroTerms :: ZeroTermsQuery
1327− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1328− , matchQueryMatchType :: Maybe MatchQueryType
1329− , matchQueryAnalyzer :: Maybe Analyzer
1330− , matchQueryMaxExpansions :: Maybe MaxExpansions
1331− , matchQueryLenient :: Maybe Lenient
1332− , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1334−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1335− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1337−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1338−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1340−data MatchQueryType =
1342− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1344−data MultiMatchQuery =
1345− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1346− , multiMatchQueryString :: QueryString
1347− , multiMatchQueryOperator :: BooleanOperator
1348− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1349− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1350− , multiMatchQueryType :: Maybe MultiMatchQueryType
1351− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1352− , multiMatchQueryAnalyzer :: Maybe Analyzer
1353− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1354− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1356−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1357− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1358− make a 'MultiMatchQuery'.
1361−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1362−mkMultiMatchQuery matchFields query =
1363− MultiMatchQuery matchFields query
1364− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1366−data MultiMatchQueryType =
1367− MultiMatchBestFields
1368− | MultiMatchMostFields
1369− | MultiMatchCrossFields
1371− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1374− BoolQuery { boolQueryMustMatch :: [Query]
1375− , boolQueryMustNotMatch :: [Query]
1376− , boolQueryShouldMatch :: [Query]
1377− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1378− , boolQueryBoost :: Maybe Boost
1379− , boolQueryDisableCoord :: Maybe DisableCoord
1380− } deriving (Eq, Read, Show, Generic, Typeable)
1382−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1383−mkBoolQuery must mustNot should =
1384− BoolQuery must mustNot should Nothing Nothing Nothing
1386−data BoostingQuery =
1387− BoostingQuery { positiveQuery :: Query
1388− , negativeQuery :: Query
1389− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1391−data CommonTermsQuery =
1392− CommonTermsQuery { commonField :: FieldName
1393− , commonQuery :: QueryString
1394− , commonCutoffFrequency :: CutoffFrequency
1395− , commonLowFreqOperator :: BooleanOperator
1396− , commonHighFreqOperator :: BooleanOperator
1397− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1398− , commonBoost :: Maybe Boost
1399− , commonAnalyzer :: Maybe Analyzer
1400− , commonDisableCoord :: Maybe DisableCoord
1401− } deriving (Eq, Read, Show, Generic, Typeable)
1403−data CommonMinimumMatch =
1404− CommonMinimumMatchHighLow MinimumMatchHighLow
1405− | CommonMinimumMatch MinimumMatch
1406− deriving (Eq, Read, Show, Generic, Typeable)
1408−data MinimumMatchHighLow =
1409− MinimumMatchHighLow { lowFreq :: MinimumMatch
1410− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1412−data Filter = AndFilter [Filter] Cache
1413− | OrFilter [Filter] Cache
1414− | NotFilter Filter Cache
1416− | BoolFilter BoolMatch
1417− | ExistsFilter FieldName -- always cached
1418− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1419− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1420− | GeoDistanceRangeFilter GeoPoint DistanceRange
1421− | GeoPolygonFilter FieldName [LatLon]
1422− | IdsFilter MappingName [DocId]
1424− | MissingFilter FieldName Existence NullValue
1425− | PrefixFilter FieldName PrefixValue Cache
1426− | QueryFilter Query Cache
1427− | RangeFilter FieldName RangeValue RangeExecution Cache
1428− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1429− | TermFilter Term Cache
1430− deriving (Eq, Read, Show, Generic, Typeable)
1432−data ZeroTermsQuery = ZeroTermsNone
1433− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1435−data RangeExecution = RangeExecutionIndex
1436− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1438−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1440−data RegexpFlags = AllRegexpFlags
1442− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1444−data RegexpFlag = AnyString
1449− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1451−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1452−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1453−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1454−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1456−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1457−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1458−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1459−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1461−data RangeValue = RangeDateLte LessThanEqD
1462− | RangeDateLt LessThanD
1463− | RangeDateGte GreaterThanEqD
1464− | RangeDateGt GreaterThanD
1465− | RangeDateGtLt GreaterThanD LessThanD
1466− | RangeDateGteLte GreaterThanEqD LessThanEqD
1467− | RangeDateGteLt GreaterThanEqD LessThanD
1468− | RangeDateGtLte GreaterThanD LessThanEqD
1469− | RangeDoubleLte LessThanEq
1470− | RangeDoubleLt LessThan
1471− | RangeDoubleGte GreaterThanEq
1472− | RangeDoubleGt GreaterThan
1473− | RangeDoubleGtLt GreaterThan LessThan
1474− | RangeDoubleGteLte GreaterThanEq LessThanEq
1475− | RangeDoubleGteLt GreaterThanEq LessThan
1476− | RangeDoubleGtLte GreaterThan LessThanEq
1477− deriving (Eq, Read, Show, Generic, Typeable)
1479−rangeValueToPair :: RangeValue -> [Pair]
1480−rangeValueToPair rv = case rv of
1481− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1482− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1483− RangeDateLt (LessThanD t) -> ["lt" .= t]
1484− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1485− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1486− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1487− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1488− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1489− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1490− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1491− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1492− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1493− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1494− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1495− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1496− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1498−data Term = Term { termField :: Text
1499− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1501−data BoolMatch = MustMatch Term Cache
1502− | MustNotMatch Term Cache
1503− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1505−-- "memory" or "indexed"
1506−data GeoFilterType = GeoFilterMemory
1507− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1509−data LatLon = LatLon { lat :: Double
1510− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1512−data GeoBoundingBox =
1513− GeoBoundingBox { topLeft :: LatLon
1514− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1516−data GeoBoundingBoxConstraint =
495+data PatternOrPatterns = PopPattern Pattern
1517− GeoBoundingBoxConstraint { geoBBField :: FieldName
1518− , constraintBox :: GeoBoundingBox
1519− , bbConstraintcache :: Cache
1520− , geoType :: GeoFilterType
1521− } deriving (Eq, Read, Show, Generic, Typeable)
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1523−data GeoPoint =
498+instance ToJSON PatternOrPatterns where
1524− GeoPoint { geoField :: FieldName
499+ toJSON (PopPattern pattern) = toJSON pattern
1525− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
500+ toJSON (PopPatterns patterns) = toJSON patterns
1527−data DistanceUnit = Miles
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
1535− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1537−data DistanceType = Arc
505+instance ToJSON Include where
1538− | SloppyArc -- doesn't exist <1.0
506+ toJSON (Include patterns) = toJSON patterns
1539− | Plane deriving (Eq, Read, Show, Generic, Typeable)
1541−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
508+instance ToJSON Exclude where
1542− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
509+ toJSON (Exclude patterns) = toJSON patterns
1544−data Distance =
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1545− Distance { coefficient :: Double
1546− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1548−data DistanceRange =
513+instance ToJSON Pattern where
1549− DistanceRange { distanceFrom :: Distance
514+ toJSON (Pattern pattern) = toJSON pattern
1550− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
1552data SearchResult a =
516data SearchResult a =
1553 SearchResult { took :: Int
517 SearchResult { took :: Int
@@ -1555,2058 +519,12 @@ data SearchResult a =
1555 , shards :: ShardResult
519 , shards :: ShardResult
1556 , searchHits :: SearchHits a
520 , searchHits :: SearchHits a
1557 , aggregations :: Maybe AggregationResults
521 , aggregations :: Maybe AggregationResults
1558− , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
522+ , scrollId :: Maybe ScrollId
1559−
523+ -- ^ Only one Suggestion request / response per
1560−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
524+ -- Search is supported.
1561−
525+ , suggest :: Maybe NamedSuggestionResponse
1562−type Score = Maybe Double
526+ }
1563−
527+ deriving (Eq, Show)
1565− SearchHits { hitsTotal :: Int
1566− , maxScore :: Score
1567− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1570−instance Monoid (SearchHits a) where
1571− mempty = SearchHits 0 Nothing mempty
1572− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1573− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1577− Hit { hitIndex :: IndexName
1578− , hitType :: MappingName
1579− , hitDocId :: DocId
1580− , hitScore :: Score
1581− , hitSource :: Maybe a
1582− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1585− ShardResult { shardTotal :: Int
1586− , shardsSuccessful :: Int
1587− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1589−type HitHighlight = M.Map Text [Text]
1591−showText :: Show a => a -> Text
1592−showText = T.pack . show
1594−readMay :: Read a => String -> Maybe a
1595−readMay s = case reads s of
1596− (a, ""):_ -> Just a
1599−parseReadText :: Read a => Text -> Parser a
1600−parseReadText = maybe mzero return . readMay . T.unpack
1602−type Aggregations = M.Map Text Aggregation
1604−emptyAggregations :: Aggregations
1605−emptyAggregations = M.empty
1607−mkAggregations :: Text -> Aggregation -> Aggregations
1608−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1610−data TermOrder = TermOrder{ termSortField :: Text
1611− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1613−data TermInclusion = TermInclusion Text
1614− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1616−data CollectionMode = BreadthFirst
1617− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1619−data ExecutionHint = Ordinals
1621− | GlobalOrdinalsHash
1622− | GlobalOrdinalsLowCardinality
1623− | Map deriving (Eq, Read, Show, Generic, Typeable)
1625−data TimeInterval = Weeks
1629− | Seconds deriving Eq
1631−data Interval = Year
1639− | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1641−data Aggregation = TermsAgg TermsAggregation
1642− | DateHistogramAgg DateHistogramAggregation
1643− | ValueCountAgg ValueCountAggregation
1644− | FilterAgg FilterAggregation
1645− | DateRangeAgg DateRangeAggregation
1646− | MissingAgg MissingAggregation deriving (Eq, Read, Show, Generic, Typeable)
1648−data MissingAggregation = MissingAggregation
1650− } deriving (Eq, Read, Show, Generic, Typeable)
1652−data TermsAggregation = TermsAggregation { term :: Either Text Text
1653− , termInclude :: Maybe TermInclusion
1654− , termExclude :: Maybe TermInclusion
1655− , termOrder :: Maybe TermOrder
1656− , termMinDocCount :: Maybe Int
1657− , termSize :: Maybe Int
1658− , termShardSize :: Maybe Int
1659− , termCollectMode :: Maybe CollectionMode
1660− , termExecutionHint :: Maybe ExecutionHint
1661− , termAggs :: Maybe Aggregations
1662− } deriving (Eq, Read, Show, Generic, Typeable)
1664−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1665− , dateInterval :: Interval
1666− , dateFormat :: Maybe Text
1667− -- pre and post deprecated in 1.5
1668− , datePreZone :: Maybe Text
1669− , datePostZone :: Maybe Text
1670− , datePreOffset :: Maybe Text
1671− , datePostOffset :: Maybe Text
1672− , dateAggs :: Maybe Aggregations
1673− } deriving (Eq, Read, Show, Generic, Typeable)
1676−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1677− , draFormat :: Maybe Text
1678− , draRanges :: NonEmpty DateRangeAggRange
1679− } deriving (Eq, Read, Show, Generic, Typeable)
1681−data DateRangeAggRange = DateRangeFrom DateMathExpr
1682− | DateRangeTo DateMathExpr
1683− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1685−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1686−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1689−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1690−data DateMathAnchor = DMNow
1691− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1693−data DateMathModifier = AddTime Int DateMathUnit
1694− | SubtractTime Int DateMathUnit
1695− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1697−data DateMathUnit = DMYear
1703− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1705−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1706−data ValueCountAggregation = FieldValueCount FieldName
1707− | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1709−-- | 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.
1710−data FilterAggregation = FilterAggregation { faFilter :: Filter
1711− , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1713−mkTermsAggregation :: Text -> TermsAggregation
1714−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1716−mkTermsScriptAggregation :: Text -> TermsAggregation
1717−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1719−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1720−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1722−instance ToJSON Version where
1723− toJSON Version {..} = object ["number" .= number
1724− ,"build_hash" .= build_hash
1725− ,"build_timestamp" .= build_timestamp
1726− ,"build_snapshot" .= build_snapshot
1727− ,"lucene_version" .= lucene_version]
1729−instance FromJSON Version where
1730− parseJSON = withObject "Version" parse
1731− where parse o = Version
1733− <*> o .: "build_hash"
1734− <*> o .: "build_timestamp"
1735− <*> o .: "build_snapshot"
1736− <*> o .: "lucene_version"
1738−instance ToJSON TermOrder where
1739− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1741−instance ToJSON TermInclusion where
1742− toJSON (TermInclusion x) = toJSON x
1743− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1746−instance ToJSON CollectionMode where
1747− toJSON BreadthFirst = "breadth_first"
1748− toJSON DepthFirst = "depth_first"
1750−instance ToJSON ExecutionHint where
1751− toJSON Ordinals = "ordinals"
1752− toJSON GlobalOrdinals = "global_ordinals"
1753− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1754− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1757−instance ToJSON Interval where
1758− toJSON Year = "year"
1759− toJSON Quarter = "quarter"
1760− toJSON Month = "month"
1761− toJSON Week = "week"
1763− toJSON Hour = "hour"
1764− toJSON Minute = "minute"
1765− toJSON Second = "second"
1766− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1768−instance Show TimeInterval where
1775−instance Read TimeInterval where
1776− readPrec = f =<< TR.get
1778− f 'w' = return Weeks
1779− f 'd' = return Days
1780− f 'h' = return Hours
1781− f 'm' = return Minutes
1782− f 's' = return Seconds
1783− f _ = fail "TimeInterval expected one of w, d, h, m, s"
1785−instance ToJSON Aggregation where
1786− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1787− omitNulls ["terms" .= omitNulls [ toJSON' term,
1788− "include" .= include,
1789− "exclude" .= exclude,
1791− "min_doc_count" .= minDocCount,
1793− "shard_size" .= shardSize,
1794− "collect_mode" .= collectMode,
1795− "execution_hint" .= executionHint
1797− "aggs" .= termAggs ]
1799− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1801− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1802− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1803− "interval" .= interval,
1804− "format" .= format,
1805− "pre_zone" .= preZone,
1806− "post_zone" .= postZone,
1807− "pre_offset" .= preOffset,
1808− "post_offset" .= postOffset
1810− "aggs" .= dateHistoAggs ]
1811− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1812− where v = case a of
1813− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1814− (ScriptValueCount (Script s)) -> object ["script" .= s]
1815− toJSON (FilterAgg (FilterAggregation filt ags)) =
1816− omitNulls [ "filter" .= filt
1818− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1820− toJSON (MissingAgg (MissingAggregation{..})) =
1821− object ["missing" .= object ["field" .= maField]]
1823−instance ToJSON DateRangeAggregation where
1824− toJSON DateRangeAggregation {..} =
1825− omitNulls [ "field" .= draField
1826− , "format" .= draFormat
1827− , "ranges" .= toList draRanges
1830−instance ToJSON DateRangeAggRange where
1831− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1832− toJSON (DateRangeTo e) = object [ "to" .= e ]
1833− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1835−instance ToJSON DateMathExpr where
1836− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1837− where fmtA DMNow = "now"
1838− fmtA (DMDate date) = case toGregorian date of
1839− (y,m,d) -> showText y <> "-" <>
1840− showText m <> "-" <>
1842− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1843− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1844− fmtMod (RoundDownTo u) = "/" <> fmtU u
1850− fmtU DMMinute = "m"
1851− fmtU DMSecond = "s"
1854−type AggregationResults = M.Map Text Value
1856−class BucketAggregation a where
1857− key :: a -> BucketValue
1858− docCount :: a -> Int
1859− aggs :: a -> Maybe AggregationResults
1862−data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1864−data BucketValue = TextValue Text
1865− | ScientificValue Scientific
1866− | BoolValue Bool deriving (Read, Show)
1868−data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1870−data TermsResult = TermsResult { termKey :: BucketValue
1871− , termsDocCount :: Int
1872− , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1874−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1875− , dateKeyStr :: Maybe Text
1876− , dateDocCount :: Int
1877− , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1879−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1880− , dateRangeFrom :: Maybe UTCTime
1881− , dateRangeFromAsString :: Maybe Text
1882− , dateRangeTo :: Maybe UTCTime
1883− , dateRangeToAsString :: Maybe Text
1884− , dateRangeDocCount :: Int
1885− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1887−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1888−toTerms = toAggResult
1890−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1891−toDateHistogram = toAggResult
1893−toMissing :: Text -> AggregationResults -> Maybe MissingResult
1894−toMissing = toAggResult
1896−toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1897−toAggResult t a = M.lookup t a >>= deserialize
1898− where deserialize = parseMaybe parseJSON
1900−instance BucketAggregation TermsResult where
1902− docCount = termsDocCount
1905−instance BucketAggregation DateHistogramResult where
1906− key = TextValue . showText . dateKey
1907− docCount = dateDocCount
1908− aggs = dateHistogramAggs
1910−instance BucketAggregation DateRangeResult where
1911− key = TextValue . dateRangeKey
1912− docCount = dateRangeDocCount
1913− aggs = dateRangeAggs
1915−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1916− parseJSON (Object v) = Bucket <$>
1918− parseJSON _ = mempty
1920−instance FromJSON BucketValue where
1921− parseJSON (String t) = return $ TextValue t
1922− parseJSON (Number s) = return $ ScientificValue s
1923− parseJSON (Bool b) = return $ BoolValue b
1924− parseJSON _ = mempty
1926−instance FromJSON MissingResult where
1927− parseJSON = withObject "MissingResult" parse
1928− where parse v = MissingResult <$> v .: "doc_count"
1930−instance FromJSON TermsResult where
1931− parseJSON (Object v) = TermsResult <$>
1933− v .: "doc_count" <*>
1934− v .:? "aggregations"
1935− parseJSON _ = mempty
1937−instance FromJSON DateHistogramResult where
1938− parseJSON (Object v) = DateHistogramResult <$>
1940− v .:? "key_as_string" <*>
1941− v .: "doc_count" <*>
1942− v .:? "aggregations"
1943− parseJSON _ = mempty
1945−instance FromJSON DateRangeResult where
1946− parseJSON = withObject "DateRangeResult" parse
1947− where parse v = DateRangeResult <$>
1949− (fmap posixMS <$> v .:? "from") <*>
1950− v .:? "from_as_string" <*>
1951− (fmap posixMS <$> v .:? "to") <*>
1952− v .:? "to_as_string" <*>
1953− v .: "doc_count" <*>
1954− v .:? "aggregations"
1956−instance FromJSON POSIXMS where
1957− parseJSON = withScientific "POSIXMS" (return . parse)
1958− where parse n = let n' = truncate n :: Integer
1959− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1961−instance Monoid Filter where
1962− mempty = IdentityFilter
1963− mappend a b = AndFilter [a, b] defaultCache
1965−instance Seminearring Filter where
1966− a <||> b = OrFilter [a, b] defaultCache
1968−instance ToJSON Filter where
1969− toJSON (AndFilter filters cache) =
1971− object [ "filters" .= fmap toJSON filters
1972− , "_cache" .= cache]]
1974− toJSON (OrFilter filters cache) =
1976− object [ "filters" .= fmap toJSON filters
1977− , "_cache" .= cache]]
1979− toJSON (NotFilter notFilter cache) =
1981− object ["filter" .= notFilter
1982− , "_cache" .= cache]]
1984− toJSON (IdentityFilter) =
1985− object ["match_all" .= object []]
1987− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1988− object ["term" .= object base]
1989− where base = [termFilterField .= termFilterValue,
1992− toJSON (ExistsFilter (FieldName fieldName)) =
1993− object ["exists" .= object
1994− ["field" .= fieldName]]
1996− toJSON (BoolFilter boolMatch) =
1997− object ["bool" .= boolMatch]
1999− toJSON (GeoBoundingBoxFilter bbConstraint) =
2000− object ["geo_bounding_box" .= bbConstraint]
2002− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2003− distance distanceType optimizeBbox cache) =
2004− object ["geo_distance" .=
2005− object ["distance" .= distance
2006− , "distance_type" .= distanceType
2007− , "optimize_bbox" .= optimizeBbox
2008− , distanceGeoField .= geoDistLatLon
2009− , "_cache" .= cache]]
2011− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2012− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2013− object ["geo_distance_range" .=
2014− object ["from" .= geoDistRangeDistFrom
2015− , "to" .= drDistanceTo
2016− , gddrField .= drLatLon]]
2018− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2019− object ["geo_polygon" .=
2020− object [geoPolygonFilterField .=
2021− object ["points" .= fmap toJSON latLons]]]
2023− toJSON (IdsFilter (MappingName mappingName) values) =
2025− object ["type" .= mappingName
2026− , "values" .= fmap unpackId values]]
2028− toJSON (LimitFilter limit) =
2029− object ["limit" .= object ["value" .= limit]]
2031− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2032− object ["missing" .=
2033− object ["field" .= fieldName
2034− , "existence" .= existence
2035− , "null_value" .= nullValue]]
2037− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2038− object ["prefix" .=
2039− object [fieldName .= fieldValue
2040− , "_cache" .= cache]]
2042− toJSON (QueryFilter query False) =
2043− object ["query" .= toJSON query ]
2044− toJSON (QueryFilter query True) =
2045− object ["fquery" .=
2046− object [ "query" .= toJSON query
2047− , "_cache" .= True ]]
2049− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2051− object [ fieldName .= object (rangeValueToPair rangeValue)
2052− , "execution" .= rangeExecution
2053− , "_cache" .= cache]]
2055− toJSON (RegexpFilter (FieldName fieldName)
2056− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2057− object ["regexp" .=
2058− object [fieldName .=
2059− object ["value" .= regexText
2060− , "flags" .= flags]
2061− , "_name" .= cacheName
2062− , "_cache" .= cache
2063− , "_cache_key" .= cacheKey]]
2065−instance FromJSON Filter where
2066− parseJSON = withObject "Filter" parse
2067− where parse o = andFilter `taggedWith` "and"
2068− <|> orFilter `taggedWith` "or"
2069− <|> notFilter `taggedWith` "not"
2070− <|> identityFilter `taggedWith` "match_all"
2071− <|> boolFilter `taggedWith` "bool"
2072− <|> existsFilter `taggedWith` "exists"
2073− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2074− <|> geoDistanceFilter `taggedWith` "geo_distance"
2075− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2076− <|> geoPolygonFilter `taggedWith` "geo_polygon"
2077− <|> idsFilter `taggedWith` "ids"
2078− <|> limitFilter `taggedWith` "limit"
2079− <|> missingFilter `taggedWith` "missing"
2080− <|> prefixFilter `taggedWith` "prefix"
2081− <|> queryFilter `taggedWith` "query"
2082− <|> fqueryFilter `taggedWith` "fquery"
2083− <|> rangeFilter `taggedWith` "range"
2084− <|> regexpFilter `taggedWith` "regexp"
2085− <|> termFilter `taggedWith` "term"
2086− where taggedWith parser k = parser =<< o .: k
2087− andFilter o = AndFilter <$> o .: "filters"
2088− <*> o .:? "_cache" .!= defaultCache
2089− orFilter o = OrFilter <$> o .: "filters"
2090− <*> o .:? "_cache" .!= defaultCache
2091− notFilter o = NotFilter <$> o .: "filter"
2092− <*> o .: "_cache" .!= defaultCache
2093− identityFilter :: Object -> Parser Filter
2095− | HM.null m = pure IdentityFilter
2096− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2097− boolFilter = pure . BoolFilter
2098− existsFilter o = ExistsFilter <$> o .: "field"
2099− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2100− geoDistanceFilter o = do
2101− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2103− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2104− GeoDistanceFilter gp <$> o .: "distance"
2105− <*> o .: "distance_type"
2106− <*> o .: "optimize_bbox"
2107− <*> o .:? "_cache" .!= defaultCache
2108− _ -> fail "Could not find GeoDistanceFilter field name"
2109− geoDistanceRangeFilter o = do
2110− case HM.toList (deleteSeveral ["from", "to"] o) of
2112− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2113− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2114− return (GeoDistanceRangeFilter gp rng)
2115− _ -> fail "Could not find GeoDistanceRangeFilter field name"
2116− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2117− idsFilter o = IdsFilter <$> o .: "type"
2119− limitFilter o = LimitFilter <$> o .: "value"
2120− missingFilter o = MissingFilter <$> o .: "field"
2121− <*> o .: "existence"
2122− <*> o .: "null_value"
2123− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2124− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2125− _ -> fail "Could not parse PrefixFilter"
2127− queryFilter q = pure (QueryFilter q False)
2128− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2129− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2130− [(fn, v)] -> RangeFilter (FieldName fn)
2132− <*> o .: "execution"
2133− <*> o .:? "_cache" .!= defaultCache
2134− _ -> fail "Could not find field name for RangeFilter"
2135− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2136− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2140− <*> o .:? "_cache" .!= defaultCache
2141− <*> o .: "_cache_key"
2142− _ -> fail "Could not find field name for RegexpFilter"
2143− termFilter o = case HM.toList (HM.delete "_cache" o) of
2144− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2145− <$> o .:? "_cache" .!= defaultCache
2146− _ -> fail "Could not find term field for TermFilter"
2148−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2149−fieldTagged f o = case HM.toList o of
2150− [(k, Object o')] -> f (FieldName k) o'
2151− _ -> fail "Expected object with 1 field-named key"
2153−instance ToJSON GeoPoint where
2154− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2155− object [ geoPointField .= geoPointLatLon ]
2158−instance ToJSON Query where
2159− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2161− object [termQueryField .= object merged]]
2163− base = [ "value" .= termQueryValue ]
2164− boosted = maybe [] (return . ("boost" .=)) boost
2165− merged = mappend base boosted
2167− toJSON (TermsQuery fieldName terms) =
2168− object [ "terms" .= object conjoined ]
2169− where conjoined = [fieldName .= terms]
2171− toJSON (IdsQuery idsQueryMappingName docIds) =
2172− object [ "ids" .= object conjoined ]
2173− where conjoined = [ "type" .= idsQueryMappingName
2174− , "values" .= fmap toJSON docIds ]
2176− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2177− object [ "query_string" .= qQueryStringQuery ]
2179− toJSON (QueryMatchQuery matchQuery) =
2180− object [ "match" .= matchQuery ]
2182− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2183− toJSON multiMatchQuery
2185− toJSON (QueryBoolQuery boolQuery) =
2186− object [ "bool" .= boolQuery ]
2188− toJSON (QueryBoostingQuery boostingQuery) =
2189− object [ "boosting" .= boostingQuery ]
2191− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2192− object [ "common" .= commonTermsQuery ]
2194− toJSON (ConstantScoreFilter csFilter boost) =
2195− object ["constant_score" .= object ["filter" .= csFilter
2196− , "boost" .= boost]]
2198− toJSON (ConstantScoreQuery query boost) =
2199− object ["constant_score" .= object ["query" .= query
2200− , "boost" .= boost]]
2202− toJSON (QueryDisMaxQuery disMaxQuery) =
2203− object [ "dis_max" .= disMaxQuery ]
2205− toJSON (QueryFilteredQuery qFilteredQuery) =
2206− object [ "filtered" .= qFilteredQuery ]
2208− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2209− object [ "fuzzy_like_this" .= fuzzyQuery ]
2211− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2212− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2214− toJSON (QueryFuzzyQuery fuzzyQuery) =
2215− object [ "fuzzy" .= fuzzyQuery ]
2217− toJSON (QueryHasChildQuery childQuery) =
2218− object [ "has_child" .= childQuery ]
2220− toJSON (QueryHasParentQuery parentQuery) =
2221− object [ "has_parent" .= parentQuery ]
2223− toJSON (QueryIndicesQuery qIndicesQuery) =
2224− object [ "indices" .= qIndicesQuery ]
2226− toJSON (MatchAllQuery boost) =
2227− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2229− toJSON (QueryMoreLikeThisQuery query) =
2230− object [ "more_like_this" .= query ]
2232− toJSON (QueryMoreLikeThisFieldQuery query) =
2233− object [ "more_like_this_field" .= query ]
2235− toJSON (QueryNestedQuery query) =
2236− object [ "nested" .= query ]
2238− toJSON (QueryPrefixQuery query) =
2239− object [ "prefix" .= query ]
2241− toJSON (QueryRangeQuery query) =
2242− object [ "range" .= query ]
2244− toJSON (QueryRegexpQuery query) =
2245− object [ "regexp" .= query ]
2247− toJSON (QuerySimpleQueryStringQuery query) =
2248− object [ "simple_query_string" .= query ]
2250−instance FromJSON Query where
2251− parseJSON v = withObject "Query" parse v
2252− where parse o = termQuery `taggedWith` "term"
2253− <|> termsQuery `taggedWith` "terms"
2254− <|> idsQuery `taggedWith` "ids"
2255− <|> queryQueryStringQuery `taggedWith` "query_string"
2256− <|> queryMatchQuery `taggedWith` "match"
2257− <|> queryMultiMatchQuery
2258− <|> queryBoolQuery `taggedWith` "bool"
2259− <|> queryBoostingQuery `taggedWith` "boosting"
2260− <|> queryCommonTermsQuery `taggedWith` "common"
2261− <|> constantScoreFilter `taggedWith` "constant_score"
2262− <|> constantScoreQuery `taggedWith` "constant_score"
2263− <|> queryDisMaxQuery `taggedWith` "dis_max"
2264− <|> queryFilteredQuery `taggedWith` "filtered"
2265− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2266− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2267− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2268− <|> queryHasChildQuery `taggedWith` "has_child"
2269− <|> queryHasParentQuery `taggedWith` "has_parent"
2270− <|> queryIndicesQuery `taggedWith` "indices"
2271− <|> matchAllQuery `taggedWith` "match_all"
2272− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2273− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2274− <|> queryNestedQuery `taggedWith` "nested"
2275− <|> queryPrefixQuery `taggedWith` "prefix"
2276− <|> queryRangeQuery `taggedWith` "range"
2277− <|> queryRegexpQuery `taggedWith` "regexp"
2278− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2279− where taggedWith parser k = parser =<< o .: k
2280− termQuery = fieldTagged $ \(FieldName fn) o ->
2281− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2282− termsQuery o = case HM.toList o of
2283− [(fn, vs)] -> do vals <- parseJSON vs
2285− x:xs -> return (TermsQuery fn (x :| xs))
2286− _ -> fail "Expected non empty list of values"
2287− _ -> fail "Expected object with 1 field-named key"
2288− idsQuery o = IdsQuery <$> o .: "type"
2290− queryQueryStringQuery = pure . QueryQueryStringQuery
2291− queryMatchQuery = pure . QueryMatchQuery
2292− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2293− queryBoolQuery = pure . QueryBoolQuery
2294− queryBoostingQuery = pure . QueryBoostingQuery
2295− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2296− constantScoreFilter o = case HM.lookup "filter" o of
2297− Just x -> ConstantScoreFilter <$> parseJSON x
2299− _ -> fail "Does not appear to be a ConstantScoreFilter"
2300− constantScoreQuery o = case HM.lookup "query" o of
2301− Just x -> ConstantScoreQuery <$> parseJSON x
2303− _ -> fail "Does not appear to be a ConstantScoreQuery"
2304− queryDisMaxQuery = pure . QueryDisMaxQuery
2305− queryFilteredQuery = pure . QueryFilteredQuery
2306− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2307− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2308− queryFuzzyQuery = pure . QueryFuzzyQuery
2309− queryHasChildQuery = pure . QueryHasChildQuery
2310− queryHasParentQuery = pure . QueryHasParentQuery
2311− queryIndicesQuery = pure . QueryIndicesQuery
2312− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2313− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2314− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2315− queryNestedQuery = pure . QueryNestedQuery
2316− queryPrefixQuery = pure . QueryPrefixQuery
2317− queryRangeQuery = pure . QueryRangeQuery
2318− queryRegexpQuery = pure . QueryRegexpQuery
2319− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2322−omitNulls :: [(Text, Value)] -> Value
2323−omitNulls = object . filter notNull where
2324− notNull (_, Null) = False
2325− notNull (_, Array a) = (not . V.null) a
2329−instance ToJSON SimpleQueryStringQuery where
2330− toJSON SimpleQueryStringQuery {..} =
2331− omitNulls (base ++ maybeAdd)
2332− where base = [ "query" .= simpleQueryStringQuery ]
2333− maybeAdd = [ "fields" .= simpleQueryStringField
2334− , "default_operator" .= simpleQueryStringOperator
2335− , "analyzer" .= simpleQueryStringAnalyzer
2336− , "flags" .= simpleQueryStringFlags
2337− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2338− , "locale" .= simpleQueryStringLocale ]
2340−instance FromJSON SimpleQueryStringQuery where
2341− parseJSON = withObject "SimpleQueryStringQuery" parse
2342− where parse o = SimpleQueryStringQuery <$> o .: "query"
2344− <*> o .:? "default_operator"
2345− <*> o .:? "analyzer"
2346− <*> (parseFlags <$> o .:? "flags")
2347− <*> o .:? "lowercase_expanded_terms"
2349− parseFlags (Just (x:xs)) = Just (x :| xs)
2350− parseFlags _ = Nothing
2352−instance ToJSON FieldOrFields where
2353− toJSON (FofField fieldName) =
2355− toJSON (FofFields fieldNames) =
2358−instance FromJSON FieldOrFields where
2359− parseJSON v = FofField <$> parseJSON v
2360− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2362−instance ToJSON SimpleQueryFlag where
2363− toJSON SimpleQueryAll = "ALL"
2364− toJSON SimpleQueryNone = "NONE"
2365− toJSON SimpleQueryAnd = "AND"
2366− toJSON SimpleQueryOr = "OR"
2367− toJSON SimpleQueryPrefix = "PREFIX"
2368− toJSON SimpleQueryPhrase = "PHRASE"
2369− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2370− toJSON SimpleQueryEscape = "ESCAPE"
2371− toJSON SimpleQueryWhitespace = "WHITESPACE"
2372− toJSON SimpleQueryFuzzy = "FUZZY"
2373− toJSON SimpleQueryNear = "NEAR"
2374− toJSON SimpleQuerySlop = "SLOP"
2376−instance FromJSON SimpleQueryFlag where
2377− parseJSON = withText "SimpleQueryFlag" parse
2378− where parse "ALL" = pure SimpleQueryAll
2379− parse "NONE" = pure SimpleQueryNone
2380− parse "AND" = pure SimpleQueryAnd
2381− parse "OR" = pure SimpleQueryOr
2382− parse "PREFIX" = pure SimpleQueryPrefix
2383− parse "PHRASE" = pure SimpleQueryPhrase
2384− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2385− parse "ESCAPE" = pure SimpleQueryEscape
2386− parse "WHITESPACE" = pure SimpleQueryWhitespace
2387− parse "FUZZY" = pure SimpleQueryFuzzy
2388− parse "NEAR" = pure SimpleQueryNear
2389− parse "SLOP" = pure SimpleQuerySlop
2390− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2392−instance ToJSON RegexpQuery where
2393− toJSON (RegexpQuery (FieldName rqQueryField)
2394− (Regexp regexpQueryQuery) rqQueryFlags
2396− object [ rqQueryField .= omitNulls base ]
2397− where base = [ "value" .= regexpQueryQuery
2398− , "flags" .= rqQueryFlags
2399− , "boost" .= rqQueryBoost ]
2401−instance FromJSON RegexpQuery where
2402− parseJSON = withObject "RegexpQuery" parse
2403− where parse = fieldTagged $ \fn o ->
2409−instance ToJSON QueryStringQuery where
2410− toJSON (QueryStringQuery qsQueryString
2411− qsDefaultField qsOperator
2412− qsAnalyzer qsAllowWildcard
2413− qsLowercaseExpanded qsEnablePositionIncrements
2414− qsFuzzyMaxExpansions qsFuzziness
2415− qsFuzzyPrefixLength qsPhraseSlop
2416− qsBoost qsAnalyzeWildcard
2417− qsGeneratePhraseQueries qsMinimumShouldMatch
2418− qsLenient qsLocale) =
2421− base = [ "query" .= qsQueryString
2422− , "default_field" .= qsDefaultField
2423− , "default_operator" .= qsOperator
2424− , "analyzer" .= qsAnalyzer
2425− , "allow_leading_wildcard" .= qsAllowWildcard
2426− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2427− , "enable_position_increments" .= qsEnablePositionIncrements
2428− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2429− , "fuzziness" .= qsFuzziness
2430− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2431− , "phrase_slop" .= qsPhraseSlop
2432− , "boost" .= qsBoost
2433− , "analyze_wildcard" .= qsAnalyzeWildcard
2434− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2435− , "minimum_should_match" .= qsMinimumShouldMatch
2436− , "lenient" .= qsLenient
2437− , "locale" .= qsLocale ]
2439−instance FromJSON QueryStringQuery where
2440− parseJSON = withObject "QueryStringQuery" parse
2441− where parse o = QueryStringQuery
2443− <*> o .:? "default_field"
2444− <*> o .:? "default_operator"
2445− <*> o .:? "analyzer"
2446− <*> o .:? "allow_leading_wildcard"
2447− <*> o .:? "lowercase_expanded_terms"
2448− <*> o .:? "enable_position_increments"
2449− <*> o .:? "fuzzy_max_expansions"
2450− <*> o .:? "fuzziness"
2451− <*> o .:? "fuzzy_prefix_length"
2452− <*> o .:? "phrase_slop"
2454− <*> o .:? "analyze_wildcard"
2455− <*> o .:? "auto_generate_phrase_queries"
2456− <*> o .:? "minimum_should_match"
2457− <*> o .:? "lenient"
2460−instance ToJSON RangeQuery where
2461− toJSON (RangeQuery (FieldName fieldName) range boost) =
2462− object [ fieldName .= object conjoined ]
2463− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2465−instance FromJSON RangeQuery where
2466− parseJSON = withObject "RangeQuery" parse
2467− where parse = fieldTagged $ \fn o ->
2469− <$> parseJSON (Object o)
2472−instance FromJSON RangeValue where
2473− parseJSON = withObject "RangeValue" parse
2474− where parse o = parseDate o
2476− parseDate o = do lt <- o .:? "lt"
2480− case (lt, lte, gt, gte) of
2481− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2482− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2483− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2484− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2485− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2486− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2487− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2488− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2489− (Nothing, Nothing, Nothing, Nothing) -> mzero
2490− parseDouble o = do lt <- o .:? "lt"
2494− case (lt, lte, gt, gte) of
2495− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2496− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2497− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2498− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2499− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2500− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2501− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2502− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2503− (Nothing, Nothing, Nothing, Nothing) -> mzero
2505−instance ToJSON PrefixQuery where
2506− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2507− object [ fieldName .= omitNulls base ]
2508− where base = [ "value" .= queryValue
2509− , "boost" .= boost ]
2511−instance FromJSON PrefixQuery where
2512− parseJSON = withObject "PrefixQuery" parse
2513− where parse = fieldTagged $ \fn o ->
2518−instance ToJSON NestedQuery where
2519− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2520− object [ "path" .= nqPath
2521− , "score_mode" .= nqScoreType
2522− , "query" .= nqQuery ]
2524−instance FromJSON NestedQuery where
2525− parseJSON = withObject "NestedQuery" parse
2526− where parse o = NestedQuery
2528− <*> o .: "score_mode"
2531−instance ToJSON MoreLikeThisFieldQuery where
2532− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2533− percent mtf mqt stopwords mindf maxdf
2534− minwl maxwl boostTerms boost analyzer) =
2535− object [ fieldName .= omitNulls base ]
2536− where base = [ "like_text" .= text
2537− , "percent_terms_to_match" .= percent
2538− , "min_term_freq" .= mtf
2539− , "max_query_terms" .= mqt
2540− , "stop_words" .= stopwords
2541− , "min_doc_freq" .= mindf
2542− , "max_doc_freq" .= maxdf
2543− , "min_word_length" .= minwl
2544− , "max_word_length" .= maxwl
2545− , "boost_terms" .= boostTerms
2547− , "analyzer" .= analyzer ]
2549−instance FromJSON MoreLikeThisFieldQuery where
2550− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2551− where parse = fieldTagged $ \fn o ->
2552− MoreLikeThisFieldQuery
2553− <$> o .: "like_text"
2555− <*> o .:? "percent_terms_to_match"
2556− <*> o .:? "min_term_freq"
2557− <*> o .:? "max_query_terms"
2558− -- <*> (optionalNE =<< o .:? "stop_words")
2559− <*> o .:? "stop_words"
2560− <*> o .:? "min_doc_freq"
2561− <*> o .:? "max_doc_freq"
2562− <*> o .:? "min_word_length"
2563− <*> o .:? "max_word_length"
2564− <*> o .:? "boost_terms"
2566− <*> o .:? "analyzer"
2567− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2569−instance ToJSON MoreLikeThisQuery where
2570− toJSON (MoreLikeThisQuery text fields percent
2571− mtf mqt stopwords mindf maxdf
2572− minwl maxwl boostTerms boost analyzer) =
2574− where base = [ "like_text" .= text
2575− , "fields" .= fields
2576− , "percent_terms_to_match" .= percent
2577− , "min_term_freq" .= mtf
2578− , "max_query_terms" .= mqt
2579− , "stop_words" .= stopwords
2580− , "min_doc_freq" .= mindf
2581− , "max_doc_freq" .= maxdf
2582− , "min_word_length" .= minwl
2583− , "max_word_length" .= maxwl
2584− , "boost_terms" .= boostTerms
2586− , "analyzer" .= analyzer ]
2588−instance FromJSON MoreLikeThisQuery where
2589− parseJSON = withObject "MoreLikeThisQuery" parse
2590− where parse o = MoreLikeThisQuery
2591− <$> o .: "like_text"
2592− -- <*> (optionalNE =<< o .:? "fields")
2594− <*> o .:? "percent_terms_to_match"
2595− <*> o .:? "min_term_freq"
2596− <*> o .:? "max_query_terms"
2597− -- <*> (optionalNE =<< o .:? "stop_words")
2598− <*> o .:? "stop_words"
2599− <*> o .:? "min_doc_freq"
2600− <*> o .:? "max_doc_freq"
2601− <*> o .:? "min_word_length"
2602− <*> o .:? "max_word_length"
2603− <*> o .:? "boost_terms"
2605− <*> o .:? "analyzer"
2606− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2608−instance ToJSON IndicesQuery where
2609− toJSON (IndicesQuery indices query noMatch) =
2610− omitNulls [ "indices" .= indices
2611− , "no_match_query" .= noMatch
2612− , "query" .= query ]
2614−instance FromJSON IndicesQuery where
2615− parseJSON = withObject "IndicesQuery" parse
2616− where parse o = IndicesQuery
2617− <$> o .:? "indices" .!= []
2619− <*> o .:? "no_match_query"
2621−instance ToJSON HasParentQuery where
2622− toJSON (HasParentQuery queryType query scoreType) =
2623− omitNulls [ "parent_type" .= queryType
2624− , "score_type" .= scoreType
2625− , "query" .= query ]
2627−instance FromJSON HasParentQuery where
2628− parseJSON = withObject "HasParentQuery" parse
2629− where parse o = HasParentQuery
2630− <$> o .: "parent_type"
2632− <*> o .:? "score_type"
2634−instance ToJSON HasChildQuery where
2635− toJSON (HasChildQuery queryType query scoreType) =
2636− omitNulls [ "query" .= query
2637− , "score_type" .= scoreType
2638− , "type" .= queryType ]
2640−instance FromJSON HasChildQuery where
2641− parseJSON = withObject "HasChildQuery" parse
2642− where parse o = HasChildQuery
2645− <*> o .:? "score_type"
2647−instance ToJSON FuzzyQuery where
2648− toJSON (FuzzyQuery (FieldName fieldName) queryText
2649− prefixLength maxEx fuzziness boost) =
2650− object [ fieldName .= omitNulls base ]
2651− where base = [ "value" .= queryText
2652− , "fuzziness" .= fuzziness
2653− , "prefix_length" .= prefixLength
2655− , "max_expansions" .= maxEx ]
2657−instance FromJSON FuzzyQuery where
2658− parseJSON = withObject "FuzzyQuery" parse
2659− where parse = fieldTagged $ \fn o ->
2662− <*> o .: "prefix_length"
2663− <*> o .: "max_expansions"
2664− <*> o .: "fuzziness"
2667−instance ToJSON FuzzyLikeFieldQuery where
2668− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2669− fieldText maxTerms ignoreFreq fuzziness prefixLength
2671− object [ fieldName .=
2672− omitNulls [ "like_text" .= fieldText
2673− , "max_query_terms" .= maxTerms
2674− , "ignore_tf" .= ignoreFreq
2675− , "fuzziness" .= fuzziness
2676− , "prefix_length" .= prefixLength
2677− , "analyzer" .= analyzer
2678− , "boost" .= boost ]]
2680−instance FromJSON FuzzyLikeFieldQuery where
2681− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2682− where parse = fieldTagged $ \fn o ->
2683− FuzzyLikeFieldQuery fn
2684− <$> o .: "like_text"
2685− <*> o .: "max_query_terms"
2686− <*> o .: "ignore_tf"
2687− <*> o .: "fuzziness"
2688− <*> o .: "prefix_length"
2690− <*> o .:? "analyzer"
2692−instance ToJSON FuzzyLikeThisQuery where
2693− toJSON (FuzzyLikeThisQuery fields text maxTerms
2694− ignoreFreq fuzziness prefixLength boost analyzer) =
2696− where base = [ "fields" .= fields
2697− , "like_text" .= text
2698− , "max_query_terms" .= maxTerms
2699− , "ignore_tf" .= ignoreFreq
2700− , "fuzziness" .= fuzziness
2701− , "prefix_length" .= prefixLength
2702− , "analyzer" .= analyzer
2703− , "boost" .= boost ]
2705−instance FromJSON FuzzyLikeThisQuery where
2706− parseJSON = withObject "FuzzyLikeThisQuery" parse
2707− where parse o = FuzzyLikeThisQuery
2708− <$> o .:? "fields" .!= []
2709− <*> o .: "like_text"
2710− <*> o .: "max_query_terms"
2711− <*> o .: "ignore_tf"
2712− <*> o .: "fuzziness"
2713− <*> o .: "prefix_length"
2715− <*> o .:? "analyzer"
2717−instance ToJSON FilteredQuery where
2718− toJSON (FilteredQuery query fFilter) =
2719− object [ "query" .= query
2720− , "filter" .= fFilter ]
2722−instance FromJSON FilteredQuery where
2723− parseJSON = withObject "FilteredQuery" parse
2724− where parse o = FilteredQuery
2728−instance ToJSON DisMaxQuery where
2729− toJSON (DisMaxQuery queries tiebreaker boost) =
2731− where base = [ "queries" .= queries
2733− , "tie_breaker" .= tiebreaker ]
2735−instance FromJSON DisMaxQuery where
2736− parseJSON = withObject "DisMaxQuery" parse
2737− where parse o = DisMaxQuery
2738− <$> o .:? "queries" .!= []
2739− <*> o .: "tie_breaker"
2742−instance ToJSON CommonTermsQuery where
2743− toJSON (CommonTermsQuery (FieldName fieldName)
2744− (QueryString query) cf lfo hfo msm
2745− boost analyzer disableCoord) =
2746− object [fieldName .= omitNulls base ]
2747− where base = [ "query" .= query
2748− , "cutoff_frequency" .= cf
2749− , "low_freq_operator" .= lfo
2750− , "minimum_should_match" .= msm
2752− , "analyzer" .= analyzer
2753− , "disable_coord" .= disableCoord
2754− , "high_freq_operator" .= hfo ]
2756−instance FromJSON CommonTermsQuery where
2757− parseJSON = withObject "CommonTermsQuery" parse
2758− where parse = fieldTagged $ \fn o ->
2759− CommonTermsQuery fn
2761− <*> o .: "cutoff_frequency"
2762− <*> o .: "low_freq_operator"
2763− <*> o .: "high_freq_operator"
2764− <*> o .:? "minimum_should_match"
2766− <*> o .:? "analyzer"
2767− <*> o .:? "disable_coord"
2769−instance ToJSON CommonMinimumMatch where
2770− toJSON (CommonMinimumMatch mm) = toJSON mm
2771− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2772− object [ "low_freq" .= lowF
2773− , "high_freq" .= highF ]
2775−instance FromJSON CommonMinimumMatch where
2776− parseJSON v = parseMinimum v
2777− <|> parseMinimumHighLow v
2778− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2779− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2780− MinimumMatchHighLow
2781− <$> o .: "low_freq"
2782− <*> o .: "high_freq")
2785−instance ToJSON BoostingQuery where
2786− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2787− object [ "positive" .= bqPositiveQuery
2788− , "negative" .= bqNegativeQuery
2789− , "negative_boost" .= bqNegativeBoost ]
2791−instance FromJSON BoostingQuery where
2792− parseJSON = withObject "BoostingQuery" parse
2793− where parse o = BoostingQuery
2794− <$> o .: "positive"
2795− <*> o .: "negative"
2796− <*> o .: "negative_boost"
2798−instance ToJSON BoolQuery where
2799− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2801− where base = [ "must" .= mustM
2802− , "must_not" .= notM
2803− , "should" .= shouldM
2804− , "minimum_should_match" .= bqMin
2806− , "disable_coord" .= disableCoord ]
2808−instance FromJSON BoolQuery where
2809− parseJSON = withObject "BoolQuery" parse
2810− where parse o = BoolQuery
2811− <$> o .:? "must" .!= []
2812− <*> o .:? "must_not" .!= []
2813− <*> o .:? "should" .!= []
2814− <*> o .:? "minimum_should_match"
2816− <*> o .:? "disable_coord"
2818−instance ToJSON MatchQuery where
2819− toJSON (MatchQuery (FieldName fieldName)
2820− (QueryString mqQueryString) booleanOperator
2821− zeroTermsQuery cutoffFrequency matchQueryType
2822− analyzer maxExpansions lenient boost) =
2823− object [ fieldName .= omitNulls base ]
2824− where base = [ "query" .= mqQueryString
2825− , "operator" .= booleanOperator
2826− , "zero_terms_query" .= zeroTermsQuery
2827− , "cutoff_frequency" .= cutoffFrequency
2828− , "type" .= matchQueryType
2829− , "analyzer" .= analyzer
2830− , "max_expansions" .= maxExpansions
2831− , "lenient" .= lenient
2832− , "boost" .= boost ]
2834−instance FromJSON MatchQuery where
2835− parseJSON = withObject "MatchQuery" parse
2836− where parse = fieldTagged $ \fn o ->
2839− <*> o .: "operator"
2840− <*> o .: "zero_terms_query"
2841− <*> o .:? "cutoff_frequency"
2843− <*> o .:? "analyzer"
2844− <*> o .:? "max_expansions"
2845− <*> o .:? "lenient"
2848−instance ToJSON MultiMatchQuery where
2849− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2850− ztQ tb mmqt cf analyzer maxEx lenient) =
2851− object ["multi_match" .= omitNulls base]
2852− where base = [ "fields" .= fmap toJSON fields
2854− , "operator" .= boolOp
2855− , "zero_terms_query" .= ztQ
2856− , "tiebreaker" .= tb
2858− , "cutoff_frequency" .= cf
2859− , "analyzer" .= analyzer
2860− , "max_expansions" .= maxEx
2861− , "lenient" .= lenient ]
2863−instance FromJSON MultiMatchQuery where
2864− parseJSON = withObject "MultiMatchQuery" parse
2865− where parse raw = do o <- raw .: "multi_match"
2867− <$> o .:? "fields" .!= []
2869− <*> o .: "operator"
2870− <*> o .: "zero_terms_query"
2871− <*> o .:? "tiebreaker"
2873− <*> o .:? "cutoff_frequency"
2874− <*> o .:? "analyzer"
2875− <*> o .:? "max_expansions"
2876− <*> o .:? "lenient"
2878−instance ToJSON MultiMatchQueryType where
2879− toJSON MultiMatchBestFields = "best_fields"
2880− toJSON MultiMatchMostFields = "most_fields"
2881− toJSON MultiMatchCrossFields = "cross_fields"
2882− toJSON MultiMatchPhrase = "phrase"
2883− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2885−instance FromJSON MultiMatchQueryType where
2886− parseJSON = withText "MultiMatchPhrasePrefix" parse
2887− where parse "best_fields" = pure MultiMatchBestFields
2888− parse "most_fields" = pure MultiMatchMostFields
2889− parse "cross_fields" = pure MultiMatchCrossFields
2890− parse "phrase" = pure MultiMatchPhrase
2891− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2892− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2894−instance ToJSON BooleanOperator where
2895− toJSON And = String "and"
2896− toJSON Or = String "or"
2898−instance FromJSON BooleanOperator where
2899− parseJSON = withText "BooleanOperator" parse
2900− where parse "and" = pure And
2901− parse "or" = pure Or
2902− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2904−instance ToJSON ZeroTermsQuery where
2905− toJSON ZeroTermsNone = String "none"
2906− toJSON ZeroTermsAll = String "all"
2908−instance FromJSON ZeroTermsQuery where
2909− parseJSON = withText "ZeroTermsQuery" parse
2910− where parse "none" = pure ZeroTermsNone
2911− parse "all" = pure ZeroTermsAll
2912− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2914−instance ToJSON MatchQueryType where
2915− toJSON MatchPhrase = "phrase"
2916− toJSON MatchPhrasePrefix = "phrase_prefix"
2918−instance FromJSON MatchQueryType where
2919− parseJSON = withText "MatchQueryType" parse
2920− where parse "phrase" = pure MatchPhrase
2921− parse "phrase_prefix" = pure MatchPhrasePrefix
2922− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2924−instance FromJSON Status where
2925− parseJSON (Object v) = Status <$>
2931− parseJSON _ = empty
2934−instance ToJSON IndexSettings where
2935− toJSON (IndexSettings s r) = object ["settings" .=
2937− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2941−instance FromJSON IndexSettings where
2942− parseJSON = withObject "IndexSettings" parse
2943− where parse o = do s <- o .: "settings"
2945− IndexSettings <$> i .: "number_of_shards"
2946− <*> i .: "number_of_replicas"
2948−instance ToJSON UpdatableIndexSetting where
2949− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2950− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2951− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2952− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2953− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2954− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2955− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2956− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2957− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2958− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2959− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2960− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2961− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2962− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2963− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2964− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2965− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2966− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2967− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2968− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2969− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2970− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2971− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2972− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2973− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2974− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2975− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2976− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2978−instance FromJSON UpdatableIndexSetting where
2979− parseJSON = withObject "UpdatableIndexSetting" parse
2980− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2981− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2982− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2983− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2984− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2985− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2986− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2987− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2988− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2989− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2990− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2991− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2992− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2993− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2994− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2995− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2996− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2997− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2998− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2999− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
3000− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
3001− <|> compoundFormat `taggedAt` ["index", "compound_format"]
3002− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3003− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3004− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3005− <|> blocksRead `taggedAt` ["blocks", "read"]
3006− <|> blocksWrite `taggedAt` ["blocks", "write"]
3007− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3008− where taggedAt f ks = taggedAt' f (Object o) ks
3009− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3010− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3011− taggedAt' f v' ks) v
3012− numberOfReplicas = pure . NumberOfReplicas
3013− autoExpandReplicas = pure . AutoExpandReplicas
3014− refreshInterval = pure . RefreshInterval . ndtJSON
3015− indexConcurrency = pure . IndexConcurrency
3016− failOnMergeFailure = pure . FailOnMergeFailure
3017− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3018− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3019− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3020− translogDisableFlush = pure . TranslogDisableFlush
3021− cacheFilterMaxSize = pure . CacheFilterMaxSize
3022− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3023− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3024− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3025− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3026− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3027− routingAllocationEnable = pure . RoutingAllocationEnable
3028− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3029− recoveryInitialShards = pure . RecoveryInitialShards
3030− gcDeletes = pure . GCDeletes . ndtJSON
3031− ttlDisablePurge = pure . TTLDisablePurge
3032− translogFSType = pure . TranslogFSType
3033− compoundFormat = pure . IndexCompoundFormat
3034− compoundOnFlush = pure . IndexCompoundOnFlush
3035− warmerEnabled = pure . WarmerEnabled
3036− blocksReadOnly = pure . BlocksReadOnly
3037− blocksRead = pure . BlocksRead
3038− blocksWrite = pure . BlocksWrite
3039− blocksMetaData = pure . BlocksMetaData
3041−instance FromJSON IndexSettingsSummary where
3042− parseJSON = withObject "IndexSettingsSummary" parse
3043− where parse o = case HM.toList o of
3044− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3046− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3047− _ -> fail "Expected single-key object with index name"
3048− redundant (NumberOfReplicas _) = True
3049− redundant _ = False
3051−-- | For some reason in several settings APIs, all leaf values get returned
3052−-- as strings. This function attepmts to recover from this for all
3053−-- non-recursive JSON types. If nothing can be done, the value is left alone.
3054−unStringlyTypeJSON :: Value -> Value
3055−unStringlyTypeJSON (String "true") = Bool True
3056−unStringlyTypeJSON (String "false") = Bool False
3057−unStringlyTypeJSON (String "null") = Null
3058−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3061−unStringlyTypeJSON v = v
3064−parseSettings :: Object -> Parser [UpdatableIndexSetting]
3065−parseSettings o = do
3067− -- slice the index object into singleton hashmaps and try to parse each
3068− parses <- forM (HM.toList o') $ \(k, v) -> do
3069− -- blocks are now nested into the "index" key, which is not how they're serialized
3070− let atRoot = Object (HM.singleton k v)
3071− let atIndex = Object (HM.singleton "index" atRoot)
3072− optional (parseJSON atRoot <|> parseJSON atIndex)
3073− return (catMaybes parses)
3075−oPath :: ToJSON a => NonEmpty Text -> a -> Value
3076−oPath (k :| []) v = object [k .= v]
3077−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3079−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3080−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3081− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3083−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3084−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3085− where parse o = case HM.toList o of
3086− [] -> fail "Expected non-empty list of NodeAttrFilters"
3087− x:xs -> DT.mapM (uncurry parse') (x :| xs)
3088− parse' n = withText "Text" $ \t ->
3089− case T.splitOn "," t of
3090− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3091− [] -> fail "Expected non-empty list of filter values"
3093−instance ToJSON ReplicaBounds where
3094− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3095− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3096− toJSON ReplicasUnbounded = Bool False
3098−instance FromJSON ReplicaBounds where
3099− parseJSON v = withText "ReplicaBounds" parseText v
3100− <|> withBool "ReplicaBounds" parseBool v
3101− where parseText t = case T.splitOn "-" t of
3102− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3103− [a, b] -> ReplicasBounded <$> parseReadText a
3104− <*> parseReadText b
3105− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3106− parseBool False = pure ReplicasUnbounded
3107− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3109−instance ToJSON AllocationPolicy where
3110− toJSON AllocAll = String "all"
3111− toJSON AllocPrimaries = String "primaries"
3112− toJSON AllocNewPrimaries = String "new_primaries"
3113− toJSON AllocNone = String "none"
3115−instance FromJSON AllocationPolicy where
3116− parseJSON = withText "AllocationPolicy" parse
3117− where parse "all" = pure AllocAll
3118− parse "primaries" = pure AllocPrimaries
3119− parse "new_primaries" = pure AllocNewPrimaries
3120− parse "none" = pure AllocNone
3121− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3123−instance ToJSON InitialShardCount where
3124− toJSON QuorumShards = String "quorum"
3125− toJSON QuorumMinus1Shards = String "quorum-1"
3126− toJSON FullShards = String "full"
3127− toJSON FullMinus1Shards = String "full-1"
3128− toJSON (ExplicitShards x) = toJSON x
3130−instance FromJSON InitialShardCount where
3131− parseJSON v = withText "InitialShardCount" parseText v
3132− <|> ExplicitShards <$> parseJSON v
3133− where parseText "quorum" = pure QuorumShards
3134− parseText "quorum-1" = pure QuorumMinus1Shards
3135− parseText "full" = pure FullShards
3136− parseText "full-1" = pure FullMinus1Shards
3137− parseText _ = mzero
3139−instance ToJSON FSType where
3140− toJSON FSSimple = "simple"
3141− toJSON FSBuffered = "buffered"
3143−instance FromJSON FSType where
3144− parseJSON = withText "FSType" parse
3145− where parse "simple" = pure FSSimple
3146− parse "buffered" = pure FSBuffered
3147− parse t = fail ("Invalid FSType: " <> show t)
3149−instance ToJSON CompoundFormat where
3150− toJSON (CompoundFileFormat x) = Bool x
3151− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3153−instance FromJSON CompoundFormat where
3154− parseJSON v = CompoundFileFormat <$> parseJSON v
3155− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3157−instance ToJSON NominalDiffTimeJSON where
3158− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3160−instance FromJSON NominalDiffTimeJSON where
3161− parseJSON = withText "NominalDiffTime" parse
3162− where parse t = case T.takeEnd 1 t of
3163− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3164− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3166−instance ToJSON IndexTemplate where
3167− toJSON (IndexTemplate p s m) = merge
3168− (object [ "template" .= p
3169− , "mappings" .= foldl' merge (object []) m
3173− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3175− merge _ _ = undefined
3177−instance (FromJSON a) => FromJSON (EsResult a) where
3178− parseJSON jsonVal@(Object v) = do
3179− found <- v .:? "found" .!= False
3181− then parseJSON jsonVal
3182− else return Nothing
3183− EsResult <$> v .: "_index" <*>
3187− parseJSON _ = empty
3189−instance (FromJSON a) => FromJSON (EsResultFound a) where
3190− parseJSON (Object v) = EsResultFound <$>
3191− v .: "_version" <*>
3193− parseJSON _ = empty
3195−instance FromJSON EsError where
3196− parseJSON (Object v) = EsError <$>
3199− parseJSON _ = empty
3201−instance FromJSON IndexAliasesSummary where
3202− parseJSON = withObject "IndexAliasesSummary" parse
3203− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3204− go ixn = withObject "index aliases" $ \ia -> do
3205− aliases <- ia .:? "aliases" .!= mempty
3206− forM (HM.toList aliases) $ \(aName, v) -> do
3207− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3208− IndexAliasSummary indexAlias <$> parseJSON v
3211−instance ToJSON IndexAliasAction where
3212− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3213− where Object iaObj = toJSON ia
3214− Object optsObj = toJSON opts
3215− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3216− where Object iaObj = toJSON ia
3218−instance ToJSON IndexAlias where
3219− toJSON IndexAlias {..} = object ["index" .= srcIndex
3220− , "alias" .= indexAlias
3223−instance ToJSON IndexAliasCreate where
3224− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3225− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3226− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3228−instance ToJSON AliasRouting where
3229− toJSON (AllAliasRouting v) = object ["routing" .= v]
3230− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3231− where prs = [("search_routing" .=) <$> srch
3232− ,("index_routing" .=) <$> idx]
3234−instance FromJSON AliasRouting where
3235− parseJSON = withObject "AliasRouting" parse
3236− where parse o = parseAll o <|> parseGranular o
3237− parseAll o = AllAliasRouting <$> o .: "routing"
3238− parseGranular o = do
3239− sr <- o .:? "search_routing"
3240− ir <- o .:? "index_routing"
3241− if isNothing sr && isNothing ir
3242− then fail "Both search_routing and index_routing can't be blank"
3243− else return (GranularAliasRouting sr ir)
3245−instance FromJSON IndexAliasCreate where
3246− parseJSON v = withObject "IndexAliasCreate" parse v
3247− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3250−instance ToJSON SearchAliasRouting where
3251− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3253−instance FromJSON SearchAliasRouting where
3254− parseJSON = withText "SearchAliasRouting" parse
3255− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3257−instance ToJSON Search where
3258− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3259− omitNulls [ "query" .= query
3260− , "filter" .= sFilter
3262− , "aggregations" .= searchAggs
3263− , "highlight" .= highlight
3266− , "track_scores" .= sTrackSortScores
3267− , "fields" .= sFields
3268− , "_source" .= sSource]
3271−instance ToJSON Source where
3272− toJSON NoSource = toJSON False
3273− toJSON (SourcePatterns patterns) = toJSON patterns
3274− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3276−instance ToJSON PatternOrPatterns where
3277− toJSON (PopPattern pattern) = toJSON pattern
3278− toJSON (PopPatterns patterns) = toJSON patterns
3280−instance ToJSON Include where
3281− toJSON (Include patterns) = toJSON patterns
3283−instance ToJSON Exclude where
3284− toJSON (Exclude patterns) = toJSON patterns
3286−instance ToJSON Pattern where
3287− toJSON (Pattern pattern) = toJSON pattern
3290−instance ToJSON FieldHighlight where
3291− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3292− object [ fName .= fSettings ]
3293− toJSON (FieldHighlight (FieldName fName) Nothing) =
3294− object [ fName .= emptyObject ]
3296−instance ToJSON Highlights where
3297− toJSON (Highlights global fields) =
3298− omitNulls (("fields" .= fields)
3299− : highlightSettingsPairs global)
3301−instance ToJSON HighlightSettings where
3302− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3304−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3305−highlightSettingsPairs Nothing = []
3306−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3307−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3308−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3311−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3312−plainHighPairs Nothing = []
3313−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3314− [ "type" .= String "plain"]
3315− ++ commonHighlightPairs plCom
3316− ++ nonPostingsToPairs plNonPost
3318−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3319−postHighPairs Nothing = []
3320−postHighPairs (Just (PostingsHighlight pCom)) =
3321− ("type" .= String "postings")
3322− : commonHighlightPairs pCom
3324−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3325−fastVectorHighPairs Nothing = []
3326−fastVectorHighPairs (Just
3327− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3328− fvBoundMaxScan fvFragOff fvMatchedFields
3330− [ "type" .= String "fvh"
3331− , "boundary_chars" .= fvBoundChars
3332− , "boundary_max_scan" .= fvBoundMaxScan
3333− , "fragment_offset" .= fvFragOff
3334− , "matched_fields" .= fvMatchedFields
3335− , "phraseLimit" .= fvPhraseLim]
3336− ++ commonHighlightPairs fvCom
3337− ++ nonPostingsToPairs fvNonPostSettings
3339−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3340−deleteSeveral ks hm = foldr HM.delete hm ks
3342−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3343−commonHighlightPairs Nothing = []
3344−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3345− chNoMatchSize chHighlightQuery
3346− chRequireFieldMatch)) =
3347− [ "order" .= chScore
3348− , "force_source" .= chForceSource
3349− , "encoder" .= chEncoder
3350− , "no_match_size" .= chNoMatchSize
3351− , "highlight_query" .= chHighlightQuery
3352− , "require_fieldMatch" .= chRequireFieldMatch]
3353− ++ highlightTagToPairs chTag
3356−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3357−nonPostingsToPairs Nothing = []
3358−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3359− [ "fragment_size" .= npFragSize
3360− , "number_of_fragments" .= npNumOfFrags]
3362−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3363−parseNEJSON [] = fail "Expected non-empty list"
3364−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3367−instance ToJSON HighlightEncoder where
3368− toJSON DefaultEncoder = String "default"
3369− toJSON HTMLEncoder = String "html"
3371−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3372−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3373−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3374− , "post_tags" .= post]
3375−highlightTagToPairs Nothing = []
3377−instance ToJSON SortSpec where
3378− toJSON (DefaultSortSpec
3379− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3380− dsSortMode dsMissingSort dsNestedFilter)) =
3381− object [dsSortFieldName .= omitNulls base] where
3382− base = [ "order" .= dsSortOrder
3383− , "ignore_unmapped" .= dsIgnoreUnmapped
3384− , "mode" .= dsSortMode
3385− , "missing" .= dsMissingSort
3386− , "nested_filter" .= dsNestedFilter ]
3388− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3389− object [ "unit" .= units
3390− , field .= gdsLatLon
3391− , "order" .= gdsSortOrder ]
3394−instance ToJSON SortOrder where
3395− toJSON Ascending = String "asc"
3396− toJSON Descending = String "desc"
3399−instance ToJSON SortMode where
3400− toJSON SortMin = String "min"
3401− toJSON SortMax = String "max"
3402− toJSON SortSum = String "sum"
3403− toJSON SortAvg = String "avg"
3406−instance ToJSON Missing where
3407− toJSON LastMissing = String "_last"
3408− toJSON FirstMissing = String "_first"
3409− toJSON (CustomMissing txt) = String txt
3412−instance ToJSON ScoreType where
3413− toJSON ScoreTypeMax = "max"
3414− toJSON ScoreTypeAvg = "avg"
3415− toJSON ScoreTypeSum = "sum"
3416− toJSON ScoreTypeNone = "none"
3418−instance FromJSON ScoreType where
3419− parseJSON = withText "ScoreType" parse
3420− where parse "max" = pure ScoreTypeMax
3421− parse "avg" = pure ScoreTypeAvg
3422− parse "sum" = pure ScoreTypeSum
3423− parse "none" = pure ScoreTypeNone
3424− parse t = fail ("Unexpected ScoreType: " <> show t)
3426−instance ToJSON Distance where
3427− toJSON (Distance dCoefficient dUnit) =
3428− String boltedTogether where
3429− coefText = showText dCoefficient
3430− (String unitText) = toJSON dUnit
3431− boltedTogether = mappend coefText unitText
3433−instance FromJSON Distance where
3434− parseJSON = withText "Distance" parse
3435− where parse t = Distance <$> parseCoeff nT
3436− <*> parseJSON (String unitT)
3437− where (nT, unitT) = T.span validForNumber t
3438− -- may be a better way to do this
3439− validForNumber '-' = True
3440− validForNumber '.' = True
3441− validForNumber 'e' = True
3442− validForNumber c = isNumber c
3443− parseCoeff "" = fail "Empty string cannot be parsed as number"
3444− parseCoeff s = return (read (T.unpack s))
3446−instance ToJSON DistanceUnit where
3447− toJSON Miles = String "mi"
3448− toJSON Yards = String "yd"
3449− toJSON Feet = String "ft"
3450− toJSON Inches = String "in"
3451− toJSON Kilometers = String "km"
3452− toJSON Meters = String "m"
3453− toJSON Centimeters = String "cm"
3454− toJSON Millimeters = String "mm"
3455− toJSON NauticalMiles = String "nmi"
3458−instance FromJSON DistanceUnit where
3459− parseJSON = withText "DistanceUnit" parse
3460− where parse "mi" = pure Miles
3461− parse "yd" = pure Yards
3462− parse "ft" = pure Feet
3463− parse "in" = pure Inches
3464− parse "km" = pure Kilometers
3465− parse "m" = pure Meters
3466− parse "cm" = pure Centimeters
3467− parse "mm" = pure Millimeters
3468− parse "nmi" = pure NauticalMiles
3469− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3471−instance ToJSON DistanceType where
3472− toJSON Arc = String "arc"
3473− toJSON SloppyArc = String "sloppy_arc"
3474− toJSON Plane = String "plane"
3476−instance FromJSON DistanceType where
3477− parseJSON = withText "DistanceType" parse
3478− where parse "arc" = pure Arc
3479− parse "sloppy_arc" = pure SloppyArc
3480− parse "plane" = pure Plane
3481− parse t = fail ("Unrecognized DistanceType: " <> show t)
3484−instance ToJSON OptimizeBbox where
3485− toJSON NoOptimizeBbox = String "none"
3486− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3488−instance FromJSON OptimizeBbox where
3489− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3490− <|> parseOptimize v
3491− where parseNoOptimize "none" = pure NoOptimizeBbox
3492− parseNoOptimize _ = mzero
3493− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3495−instance ToJSON GeoBoundingBoxConstraint where
3496− toJSON (GeoBoundingBoxConstraint
3497− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3498− object [gbbcGeoBBField .= gbbcConstraintBox
3499− , "_cache" .= cache
3502−instance FromJSON GeoBoundingBoxConstraint where
3503− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3504− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3505− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3507− <*> o .:? "_cache" .!= defaultCache
3509− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3511−instance ToJSON GeoFilterType where
3512− toJSON GeoFilterMemory = String "memory"
3513− toJSON GeoFilterIndexed = String "indexed"
3515−instance FromJSON GeoFilterType where
3516− parseJSON = withText "GeoFilterType" parse
3517− where parse "memory" = pure GeoFilterMemory
3518− parse "indexed" = pure GeoFilterIndexed
3519− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3521−instance ToJSON GeoBoundingBox where
3522− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3523− object ["top_left" .= gbbTopLeft
3524− , "bottom_right" .= gbbBottomRight]
3526−instance FromJSON GeoBoundingBox where
3527− parseJSON = withObject "GeoBoundingBox" parse
3528− where parse o = GeoBoundingBox
3529− <$> o .: "top_left"
3530− <*> o .: "bottom_right"
3532−instance ToJSON LatLon where
3533− toJSON (LatLon lLat lLon) =
3534− object ["lat" .= lLat
3537−instance FromJSON LatLon where
3538− parseJSON = withObject "LatLon" parse
3539− where parse o = LatLon <$> o .: "lat"
3542−-- index for smaller ranges, fielddata for longer ranges
3543−instance ToJSON RangeExecution where
3544− toJSON RangeExecutionIndex = "index"
3545− toJSON RangeExecutionFielddata = "fielddata"
3548−instance FromJSON RangeExecution where
3549− parseJSON = withText "RangeExecution" parse
3550− where parse "index" = pure RangeExecutionIndex
3551− parse "fielddata" = pure RangeExecutionFielddata
3552− parse t = error ("Unrecognized RangeExecution " <> show t)
3554−instance ToJSON RegexpFlags where
3555− toJSON AllRegexpFlags = String "ALL"
3556− toJSON NoRegexpFlags = String "NONE"
3557− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3558− where flagStrs = map flagStr . nub $ h:fs
3559− flagStr AnyString = "ANYSTRING"
3560− flagStr Automaton = "AUTOMATON"
3561− flagStr Complement = "COMPLEMENT"
3562− flagStr Empty = "EMPTY"
3563− flagStr Intersection = "INTERSECTION"
3564− flagStr Interval = "INTERVAL"
3566−instance FromJSON RegexpFlags where
3567− parseJSON = withText "RegexpFlags" parse
3568− where parse "ALL" = pure AllRegexpFlags
3569− parse "NONE" = pure NoRegexpFlags
3570− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3572−instance FromJSON RegexpFlag where
3573− parseJSON = withText "RegexpFlag" parse
3574− where parse "ANYSTRING" = pure AnyString
3575− parse "AUTOMATON" = pure Automaton
3576− parse "COMPLEMENT" = pure Complement
3577− parse "EMPTY" = pure Empty
3578− parse "INTERSECTION" = pure Intersection
3579− parse "INTERVAL" = pure Interval
3580− parse f = fail ("Unknown RegexpFlag: " <> show f)
3582−instance ToJSON Term where
3583− toJSON (Term field value) = object ["term" .= object
3586−instance FromJSON Term where
3587− parseJSON = withObject "Term" parse
3588− where parse o = do termObj <- o .: "term"
3589− case HM.toList termObj of
3590− [(fn, v)] -> Term fn <$> parseJSON v
3591− _ -> fail "Expected object with 1 field-named key"
3593−instance ToJSON BoolMatch where
3594− toJSON (MustMatch term cache) = object ["must" .= term,
3596− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3598− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3601−instance FromJSON BoolMatch where
3602− parseJSON = withObject "BoolMatch" parse
3603− where parse o = mustMatch `taggedWith` "must"
3604− <|> mustNotMatch `taggedWith` "must_not"
3605− <|> shouldMatch `taggedWith` "should"
3606− where taggedWith parser k = parser =<< o .: k
3607− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3608− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3609− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3611instance (FromJSON a) => FromJSON (SearchResult a) where
529instance (FromJSON a) => FromJSON (SearchResult a) where
3612 parseJSON (Object v) = SearchResult <$>
530 parseJSON (Object v) = SearchResult <$>
@@ -3615,484 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3615 v .: "_shards" <*>
533 v .: "_shards" <*>
3616 v .: "hits" <*>
534 v .: "hits" <*>
3617 v .:? "aggregations" <*>
535 v .:? "aggregations" <*>
3618− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
3619 parseJSON _ = empty
538 parseJSON _ = empty
3621−instance (FromJSON a) => FromJSON (SearchHits a) where
540+newtype ScrollId =
3622− parseJSON (Object v) = SearchHits <$>
541+ ScrollId Text
3623− v .: "total" <*>
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
3624− v .: "max_score" <*>
3626− parseJSON _ = empty
3628−instance (FromJSON a) => FromJSON (Hit a) where
3629− parseJSON (Object v) = Hit <$>
3634− v .:? "_source" <*>
3636− parseJSON _ = empty
3638−instance FromJSON ShardResult where
3639− parseJSON (Object v) = ShardResult <$>
3641− v .: "successful" <*>
3643− parseJSON _ = empty
3646−instance FromJSON DocVersion where
3649− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3651−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3652−instance FromJSON ReplicaCount where
3653− parseJSON v = parseAsInt v
3654− <|> parseAsString v
3655− where parseAsInt = fmap ReplicaCount . parseJSON
3656− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3658−instance FromJSON ShardCount where
3659− parseJSON v = parseAsInt v
3660− <|> parseAsString v
3661− where parseAsInt = fmap ShardCount . parseJSON
3662− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3664−instance Bounded DocVersion where
3665− minBound = DocVersion 1
3666− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3668−instance Enum DocVersion where
3670− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3671− | otherwise = succError "DocVersion"
3673− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3674− | otherwise = predError "DocVersion"
3676− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3677− fromEnum = docVersionNumber
3678− enumFrom = boundedEnumFrom
3679− enumFromThen = boundedEnumFromThen
3681−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3682−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3684−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3685−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3688−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3689− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3692−-- | Either specifies an exact repo name or one with globs in it,
3693−-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3694−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3696− deriving (Eq, Generic, Show, Typeable)
3698−-- | The unique name of a snapshot repository.
3699−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3700− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3703−-- | A generic representation of a snapshot repo. This is what gets
3704−-- sent to and parsed from the server. For repo types enabled by
3705−-- plugins that aren't exported by this library, consider making a
3706−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3707−-- type, consider submitting a pull request to have it included in the
3709−data GenericSnapshotRepo = GenericSnapshotRepo {
3710− gSnapshotRepoName :: SnapshotRepoName
3711− , gSnapshotRepoType :: SnapshotRepoType
3712− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3713− } deriving (Eq, Generic, Show, Typeable)
3716−instance SnapshotRepo GenericSnapshotRepo where
3717− toGSnapshotRepo = id
3718− fromGSnapshotRepo = Right
3721−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3722− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3725−-- | Opaque representation of snapshot repo settings. Instances of
3726−-- 'SnapshotRepo' will produce this.
3727−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3728− deriving (Eq, Generic, Show, Typeable, ToJSON)
3731− -- Regardless of whether you send strongly typed json, my version of
3732− -- ES sends back stringly typed json in the settings, e.g. booleans
3733− -- as strings, so we'll try to convert them.
3734−instance FromJSON GenericSnapshotRepoSettings where
3735− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3737−-- | The result of running 'verifySnapshotRepo'.
3738−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3739− deriving (Eq, Generic, Show, Typeable)
3742−instance FromJSON SnapshotVerification where
3743− parseJSON = withObject "SnapshotVerification" parse
3747− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3748− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3749− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3752−-- | A node that has verified a snapshot
3753−data SnapshotNodeVerification = SnapshotNodeVerification {
3754− snvFullId :: FullNodeId
3755− , snvNodeName :: NodeName
3756− } deriving (Eq, Generic, Show, Typeable)
3759−-- | Unique, automatically-generated name assigned to nodes that are
3760−-- usually returned in node-oriented APIs.
3761−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3762− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3765−-- | A human-readable node name that is supplied by the user in the
3766−-- node config or automatically generated by ElasticSearch.
3767−newtype NodeName = NodeName { nodeName :: Text }
3768− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3771−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
3772− repoUpdateVerify :: Bool
3773− -- ^ After creation/update, synchronously check that nodes can
3774− -- write to this repo. Defaults to True. You may use False if you
3775− -- need a faster response and plan on verifying manually later
3776− -- with 'verifySnapshotRepo'.
3777− } deriving (Eq, Show, Generic, Typeable)
3780−-- | Reasonable defaults for repo creation/update
3782−-- * repoUpdateVerify True
3783−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
3784−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
3787−-- | A filesystem-based snapshot repo that ships with
3788−-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
3789−-- used with 'updateSnapshotRepo'
3790−data FsSnapshotRepo = FsSnapshotRepo {
3791− fsrName :: SnapshotRepoName
3792− , fsrLocation :: FilePath
3793− , fsrCompressMetadata :: Bool
3794− , fsrChunkSize :: Maybe Bytes
3795− -- ^ Size by which to split large files during snapshotting.
3796− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
3797− -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
3798− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
3799− -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
3800− } deriving (Eq, Generic, Show, Typeable)
3803−instance SnapshotRepo FsSnapshotRepo where
3804− toGSnapshotRepo FsSnapshotRepo {..} =
3805− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
3807− Object settings = object $ [ "location" .= fsrLocation
3808− , "compress" .= fsrCompressMetadata
3810− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
3811− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
3812− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
3814− fromGSnapshotRepo GenericSnapshotRepo {..}
3815− | gSnapshotRepoType == fsRepoType = do
3816− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
3818− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
3819− <*> o .:? "compress" .!= False
3820− <*> o .:? "chunk_size"
3821− <*> o .:? "max_restore_bytes_per_sec"
3822− <*> o .:? "max_snapshot_bytes_per_sec"
3823− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
3826−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
3827−parseRepo parser = case parseEither (const parser) () of
3828− Left e -> Left (OtherRepoConversionError (T.pack e))
3832−fsRepoType :: SnapshotRepoType
3833−fsRepoType = SnapshotRepoType "fs"
3835−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
3836−class SnapshotRepo r where
3837− toGSnapshotRepo :: r -> GenericSnapshotRepo
3838− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
3841−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
3842− -- ^ Expected type and actual type
3843− | OtherRepoConversionError Text
3844− deriving (Show, Eq, Generic, Typeable)
3847−instance Exception SnapshotRepoConversionError
3850−data SnapshotCreateSettings = SnapshotCreateSettings {
3851− snapWaitForCompletion :: Bool
3852− -- ^ Should the API call return immediately after initializing
3853− -- the snapshot or wait until completed? Note that if this is
3854− -- enabled it could wait a long time, so you should adjust your
3855− -- 'ManagerSettings' accordingly to set long timeouts or
3856− -- explicitly handle timeouts.
3857− , snapIndices :: Maybe IndexSelection
3858− -- ^ Nothing will snapshot all indices. Just [] is permissable and
3859− -- will essentially be a no-op snapshot.
3860− , snapIgnoreUnavailable :: Bool
3861− -- ^ If set to True, any matched indices that don't exist will be
3862− -- ignored. Otherwise it will be an error and fail.
3863− , snapIncludeGlobalState :: Bool
3864− , snapPartial :: Bool
3865− -- ^ If some indices failed to snapshot (e.g. if not all primary
3866− -- shards are available), should the process proceed?
3867− } deriving (Eq, Generic, Show, Typeable)
3870−-- | Reasonable defaults for snapshot creation
3872−-- * snapWaitForCompletion False
3873−-- * snapIndices Nothing
3874−-- * snapIgnoreUnavailable False
3875−-- * snapIncludeGlobalState True
3876−-- * snapPartial False
3877−defaultSnapshotCreateSettings :: SnapshotCreateSettings
3878−defaultSnapshotCreateSettings = SnapshotCreateSettings {
3879− snapWaitForCompletion = False
3880− , snapIndices = Nothing
3881− , snapIgnoreUnavailable = False
3882− , snapIncludeGlobalState = True
3883− , snapPartial = False
3887−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
3888− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
3891−-- | Either specifies an exact snapshot name or one with globs in it,
3892−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
3894−data SnapshotPattern = ExactSnap SnapshotName
3896− deriving (Eq, Generic, Show, Typeable)
3899−-- | General information about the state of a snapshot. Has some
3900−-- redundancies with 'SnapshotStatus'
3901−data SnapshotInfo = SnapshotInfo {
3902− snapInfoShards :: ShardResult
3903− , snapInfoFailures :: [SnapshotShardFailure]
3904− , snapInfoDuration :: NominalDiffTime
3905− , snapInfoEndTime :: UTCTime
3906− , snapInfoStartTime :: UTCTime
3907− , snapInfoState :: SnapshotState
3908− , snapInfoIndices :: [IndexName]
3909− , snapInfoName :: SnapshotName
3910− } deriving (Eq, Generic, Show, Typeable)
3913−instance FromJSON SnapshotInfo where
3914− parseJSON = withObject "SnapshotInfo" parse
3916− parse o = SnapshotInfo <$> o .: "shards"
3917− <*> o .: "failures"
3918− <*> (unMS <$> o .: "duration_in_millis")
3919− <*> (posixMS <$> o .: "end_time_in_millis")
3920− <*> (posixMS <$> o .: "start_time_in_millis")
3923− <*> o .: "snapshot"
3925−data SnapshotShardFailure = SnapshotShardFailure {
3926− snapShardFailureIndex :: IndexName
3927− , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
3928− , snapShardFailureReason :: Text
3929− , snapShardFailureShardId :: ShardId
3930− } deriving (Eq, Show, Generic, Typeable)
3933−instance FromJSON SnapshotShardFailure where
3934− parseJSON = withObject "SnapshotShardFailure" parse
3936− parse o = SnapshotShardFailure <$> o .: "index"
3937− <*> o .:? "node_id"
3939− <*> o .: "shard_id"
3942−newtype ShardId = ShardId { shardId :: Int }
3943− deriving (Eq, Show, Generic, Typeable, FromJSON)
3946−newtype MS = MS NominalDiffTime
3949−-- keeps the unexported constructor warnings at bay
3950−unMS :: MS -> NominalDiffTime
3954−instance FromJSON MS where
3955− parseJSON = withScientific "MS" (return . MS . parse)
3957− parse n = fromInteger ((truncate n) * 1000)
3960−data SnapshotState = SnapshotInit
3967− deriving (Show, Eq, Generic, Typeable)
3969−instance FromJSON SnapshotState where
3970− parseJSON = withText "SnapshotState" parse
3972− parse "INIT" = return SnapshotInit
3973− parse "STARTED" = return SnapshotStarted
3974− parse "SUCCESS" = return SnapshotSuccess
3975− parse "FAILED" = return SnapshotFailed
3976− parse "ABORTED" = return SnapshotAborted
3977− parse "MISSING" = return SnapshotMissing
3978− parse "WAITING" = return SnapshotWaiting
3979− parse t = fail ("Invalid snapshot state " <> T.unpack t)
3982−newtype SnapshotName = SnapshotName { snapshotName :: Text }
3983− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
3986−data SnapshotRestoreSettings = SnapshotRestoreSettings {
3987− snapRestoreWaitForCompletion :: Bool
3988− -- ^ Should the API call return immediately after initializing
3989− -- the restore or wait until completed? Note that if this is
3990− -- enabled, it could wait a long time, so you should adjust your
3991− -- 'ManagerSettings' accordingly to set long timeouts or
3992− -- explicitly handle timeouts.
3993− , snapRestoreIndices :: Maybe IndexSelection
3994− -- ^ Nothing will restore all indices in the snapshot. Just [] is
3995− -- permissable and will essentially be a no-op restore.
3996− , snapRestoreIgnoreUnavailable :: Bool
3997− -- ^ If set to True, any indices that do not exist will be ignored
3998− -- during snapshot rather than failing the restore.
3999− , snapRestoreIncludeGlobalState :: Bool
4000− -- ^ If set to false, will ignore any global state in the snapshot
4001− -- and will not restore it.
4002− , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4003− -- ^ A regex pattern for matching indices. Used with
4004− -- 'snapRestoreRenameReplacement', the restore can reference the
4005− -- matched index and create a new index name upon restore.
4006− , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4007− -- ^ Expression of how index renames should be constructed.
4008− , snapRestorePartial :: Bool
4009− -- ^ If some indices fail to restore, should the process proceed?
4010− , snapRestoreIncludeAliases :: Bool
4011− -- ^ Should the restore also restore the aliases captured in the
4013− , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4014− -- ^ Settings to apply during the restore process.
4015− , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4016− -- ^ This type could be more rich but it isn't clear which
4017− -- settings are allowed to be ignored during restore, so we're
4018− -- going with including this feature in a basic form rather than
4019− -- omitting it. One example here would be
4020− -- "index.refresh_interval". Any setting specified here will
4021− -- revert back to the server default during the restore process.
4022− } deriving (Eq, Generic, Show, Typeable)
4024−-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4025−newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4026− deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4029−-- | A single token in a index renaming scheme for a restore. These
4030−-- are concatenated into a string before being sent to
4031−-- ElasticSearch. Check out these Java
4032−-- <https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html docs> to find out more if you're into that sort of thing.
4033−data RestoreRenameToken = RRTLit Text
4034− -- ^ Just a literal string of characters
4036− -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4037− | RRSubGroup RRGroupRefNum
4038− -- ^ A specific reference to a group number
4039− deriving (Show, Eq, Generic, Typeable)
4042−-- | A group number for regex matching. Only values from 1-9 are
4043−-- supported. Construct with 'mkRRGroupRefNum'
4044−newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4045− deriving (Show, Eq, Generic, Typeable, Ord)
4047−instance Bounded RRGroupRefNum where
4048− minBound = RRGroupRefNum 1
4049− maxBound = RRGroupRefNum 9
4052−-- | Only allows valid group number references (1-9).
4053−mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4055− | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4056− Just $ RRGroupRefNum i
4057− | otherwise = Nothing
4060−-- | Reasonable defaults for snapshot restores
4062−-- * snapRestoreWaitForCompletion False
4063−-- * snapRestoreIndices Nothing
4064−-- * snapRestoreIgnoreUnavailable False
4065−-- * snapRestoreIncludeGlobalState True
4066−-- * snapRestoreRenamePattern Nothing
4067−-- * snapRestoreRenameReplacement Nothing
4068−-- * snapRestorePartial False
4069−-- * snapRestoreIncludeAliases True
4070−-- * snapRestoreIndexSettingsOverrides Nothing
4071−-- * snapRestoreIgnoreIndexSettings Nothing
4072−defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4073−defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4074− snapRestoreWaitForCompletion = False
4075− , snapRestoreIndices = Nothing
4076− , snapRestoreIgnoreUnavailable = False
4077− , snapRestoreIncludeGlobalState = True
4078− , snapRestoreRenamePattern = Nothing
4079− , snapRestoreRenameReplacement = Nothing
4080− , snapRestorePartial = False
4081− , snapRestoreIncludeAliases = True
4082− , snapRestoreIndexSettingsOverrides = Nothing
4083− , snapRestoreIgnoreIndexSettings = Nothing
4087−-- | Index settings that can be overridden. The docs only mention you
4088−-- can update number of replicas, but there may be more. You
4089−-- definitely cannot override shard count.
4090−data RestoreIndexSettings = RestoreIndexSettings {
4091− restoreOverrideReplicas :: Maybe ReplicaCount
4092− } deriving (Show, Eq, Generic, Typeable)
4095−instance ToJSON RestoreIndexSettings where
4096− toJSON RestoreIndexSettings {..} = object prs
4098− prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]