@@ -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,14 +285,81 @@ 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
258 , SnapshotSelection(..)
336 , SnapshotSelection(..)
259 , SnapshotPattern(..)
337 , SnapshotPattern(..)
260 , SnapshotInfo(..)
338 , SnapshotInfo(..)
339+ , SnapshotShardFailure(..)
261 , SnapshotName(..)
341 , SnapshotName(..)
262 , SnapshotState(..)
342 , SnapshotState(..)
343+ , SnapshotRestoreSettings(..)
344+ , defaultSnapshotRestoreSettings
345+ , RestoreRenamePattern(..)
346+ , RestoreRenameToken(..)
350+ , RestoreIndexSettings(..)
353+ , PhraseSuggester(..)
354+ , PhraseSuggesterHighlighter(..)
355+ , PhraseSuggesterCollate(..)
357+ , SuggestOptions(..)
358+ , SuggestResponse(..)
359+ , NamedSuggestionResponse(..)
360+ , DirectGenerators(..)
361+ , mkDirectGenerators
362+ , DirectGeneratorSuggestModeTypes (..)
264 , Aggregation(..)
364 , Aggregation(..)
265 , Aggregations
365 , Aggregations
@@ -271,6 +371,8 @@ module Database.Bloodhound.Types
271 , MissingAggregation(..)
371 , MissingAggregation(..)
272 , ValueCountAggregation(..)
372 , ValueCountAggregation(..)
273 , FilterAggregation(..)
373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
274 , DateHistogramAggregation(..)
376 , DateHistogramAggregation(..)
275 , DateRangeAggregation(..)
377 , DateRangeAggregation(..)
276 , DateRangeAggRange(..)
378 , DateRangeAggRange(..)
@@ -278,6 +380,9 @@ module Database.Bloodhound.Types
278 , DateMathAnchor(..)
380 , DateMathAnchor(..)
279 , DateMathModifier(..)
381 , DateMathModifier(..)
280 , DateMathUnit(..)
382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
282 , Highlights(..)
387 , Highlights(..)
283 , FieldHighlight(..)
388 , FieldHighlight(..)
@@ -295,697 +400,32 @@ module Database.Bloodhound.Types
295 , TermsResult(..)
400 , TermsResult(..)
296 , DateHistogramResult(..)
401 , DateHistogramResult(..)
297 , DateRangeResult(..)
402 , DateRangeResult(..)
299 , EsUsername(..)
405 , EsUsername(..)
300 , EsPassword(..)
406 , EsPassword(..)
303−import Control.Applicative as A
408+ , Analysis(..)
304−import Control.Monad.Catch
409+ , AnalyzerDefinition(..)
305−import Control.Monad.Except
410+ , TokenizerDefinition(..)
306−import Control.Monad.Reader
411+ , TokenFilterDefinition(..)
307−import Control.Monad.State
412+ , CharFilterDefinition(..)
308−import Control.Monad.Writer
413+ , Ngram(..)
309−import Data.Aeson
414+ , TokenChar(..)
310−import Data.Aeson.Types (Pair, Parser, emptyObject,
415+ , Shingle(..)
311− parseEither, parseMaybe)
416+ , Language(..)
312−import qualified Data.ByteString.Lazy.Char8 as L
417+ ) where
314−import Data.Hashable (Hashable)
419+import Bloodhound.Import
315−import qualified Data.HashMap.Strict as HM
420+
316−import Data.List (foldl', nub)
421+import Database.Bloodhound.Internal.Aggregation
317−import Data.List.NonEmpty (NonEmpty (..), toList)
422+import Database.Bloodhound.Internal.Analysis
318−import qualified Data.Map.Strict as M
423+import Database.Bloodhound.Internal.Client
319−import Data.Maybe
424+import Database.Bloodhound.Internal.Highlight
320−import Data.Scientific (Scientific)
425+import Database.Bloodhound.Internal.Newtypes
321−import Data.Text (Text)
426+import Database.Bloodhound.Internal.Query
322−import qualified Data.Text as T
427+import Database.Bloodhound.Internal.Sort
323−import Data.Time.Calendar
428+import Database.Bloodhound.Internal.Suggest
324−import Data.Time.Clock (NominalDiffTime, UTCTime)
325−import Data.Time.Clock.POSIX
326−import qualified Data.Traversable as DT
327−import Data.Typeable (Typeable)
328−import qualified Data.Vector as V
330−import GHC.Generics (Generic)
331−import Network.HTTP.Client
332−import qualified Network.HTTP.Types.Method as NHTM
333−import qualified Text.Read as TR
335−import Database.Bloodhound.Types.Class
336−import Database.Bloodhound.Types.Internal
339−-- >>> :set -XOverloadedStrings
340−-- >>> import Data.Aeson
341−-- >>> import Database.Bloodhound
342−-- >>> let testServer = (Server "http://localhost:9200")
343−-- >>> let testIndex = IndexName "twitter"
344−-- >>> let testMapping = MappingName "tweet"
345−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
347−-- defaultIndexSettings is exported by Database.Bloodhound as well
348−-- no trailing slashes in servers, library handles building the path.
350−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
351−-- will be a noop. You can use the exported fields to customize it further, e.g.:
353−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
354−mkBHEnv :: Server -> Manager -> BHEnv
355−mkBHEnv s m = BHEnv s m return
357−newtype BH m a = BH {
358− unBH :: ReaderT BHEnv m a
359− } deriving ( Functor
373−instance MonadTrans BH where
376−instance (MonadReader r m) => MonadReader r (BH m) where
378− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
381−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
382− getBHEnv = BH getBHEnv
384−runBH :: BHEnv -> BH m a -> m a
385−runBH e f = runReaderT (unBH f) e
387−{-| 'Version' is embedded in 'Status' -}
388−data Version = Version { number :: Text
389− , build_hash :: Text
390− , build_timestamp :: UTCTime
391− , build_snapshot :: Bool
392− , lucene_version :: Text } deriving (Eq, Read, Show, Generic, Typeable)
394−{-| 'Status' is a data type for describing the JSON body returned by
395− Elasticsearch when you query its status. This was deprecated in 1.2.0.
397− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
400−data Status = Status { ok :: Maybe Bool
403− , version :: Version
404− , tagline :: Text } deriving (Eq, Read, Show, Generic)
406−{-| 'IndexSettings' is used to configure the shards and replicas when you create
407− an Elasticsearch Index.
409− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
413− IndexSettings { indexShards :: ShardCount
414− , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
416−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
417−defaultIndexSettings :: IndexSettings
418−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
421−{-| 'IndexOptimizationSettings' is used to configure index optimization. See
422− <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
425−data IndexOptimizationSettings =
426− IndexOptimizationSettings { maxNumSegments :: Maybe Int
427− -- ^ 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.
428− , onlyExpungeDeletes :: Bool
429− -- ^ 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.
430− , flushAfterOptimize :: Bool
431− -- ^ Should a flush be performed after the optimize.
432− } deriving (Eq, Show, Generic, Typeable)
435−{-| 'defaultIndexOptimizationSettings' implements the default settings that
436− ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
437− 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
439−defaultIndexOptimizationSettings :: IndexOptimizationSettings
440−defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
442−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
444− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
446−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
447− -- ^ The number of replicas each shard has.
448− | AutoExpandReplicas ReplicaBounds
449− | BlocksReadOnly Bool
450− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
452− -- ^ Set to True to disable read operations against the index.
454− -- ^ Set to True to disable write operations against the index.
455− | BlocksMetaData Bool
456− -- ^ Set to True to disable metadata operations against the index.
457− | RefreshInterval NominalDiffTime
458− -- ^ The async refresh interval of a shard
459− | IndexConcurrency Int
460− | FailOnMergeFailure Bool
461− | TranslogFlushThresholdOps Int
462− -- ^ When to flush on operations.
463− | TranslogFlushThresholdSize Bytes
464− -- ^ When to flush based on translog (bytes) size.
465− | TranslogFlushThresholdPeriod NominalDiffTime
466− -- ^ When to flush based on a period of not flushing.
467− | TranslogDisableFlush Bool
468− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
469− | CacheFilterMaxSize (Maybe Bytes)
470− -- ^ The maximum size of filter cache (per segment in shard).
471− | CacheFilterExpire (Maybe NominalDiffTime)
472− -- ^ The expire after access time for filter cache.
473− | GatewaySnapshotInterval NominalDiffTime
474− -- ^ The gateway snapshot interval (only applies to shared gateways).
475− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
476− -- ^ A node matching any rule will be allowed to host shards from the index.
477− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
478− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
479− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
480− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
481− | RoutingAllocationEnable AllocationPolicy
482− -- ^ Enables shard allocation for a specific index.
483− | RoutingAllocationShardsPerNode ShardCount
484− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
485− | RecoveryInitialShards InitialShardCount
486− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
487− | GCDeletes NominalDiffTime
488− | TTLDisablePurge Bool
489− -- ^ Disables temporarily the purge of expired docs.
490− | TranslogFSType FSType
491− | IndexCompoundFormat CompoundFormat
492− | IndexCompoundOnFlush Bool
493− | WarmerEnabled Bool
494− deriving (Eq, Show, Generic, Typeable)
496−data AllocationPolicy = AllocAll
497− -- ^ Allows shard allocation for all shards.
499− -- ^ Allows shard allocation only for primary shards.
501− -- ^ Allows shard allocation only for primary shards for new indices.
503− -- ^ No shard allocation is allowed
504− deriving (Eq, Read, Show, Generic, Typeable)
506−data ReplicaBounds = ReplicasBounded Int Int
507− | ReplicasLowerBounded Int
509− deriving (Eq, Read, Show, Generic, Typeable)
511−-- | A measure of bytes used for various configurations. You may want
512−-- to use smart constructors like 'gigabytes' for larger values.
522−newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
524−gigabytes :: Int -> Bytes
525−gigabytes n = megabytes (1000 * n)
528−megabytes :: Int -> Bytes
529−megabytes n = kilobytes (1000 * n)
532−kilobytes :: Int -> Bytes
533−kilobytes n = Bytes (1000 * n)
536−data FSType = FSSimple
537− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
539−data InitialShardCount = QuorumShards
540− | QuorumMinus1Shards
543− | ExplicitShards Int
544− deriving (Eq, Read, Show, Generic, Typeable)
546−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
547− , nodeAttrFilterValues :: NonEmpty Text}
548− deriving (Eq, Read, Show, Generic, Ord)
550−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
552−data CompoundFormat = CompoundFileFormat Bool
553− | MergeSegmentVsTotalIndex Double
554− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
555− deriving (Eq, Read, Show, Generic, Typeable)
557−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
559−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
560− , sSummaryFixedSettings :: IndexSettings
561− , sSummaryUpdateable :: [UpdatableIndexSetting]}
562− deriving (Eq, Show, Generic, Typeable)
564−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
565−type Reply = Network.HTTP.Client.Response L.ByteString
566−type Method = NHTM.Method
568−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
570− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
572−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
574−data FieldType = GeoPointType
580− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
582−data FieldDefinition =
583− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
585−{-| An 'IndexTemplate' defines a template that will automatically be
586− applied to new indices created. The templates include both
587− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
588− controls if the template will be applied to the index created.
589− Specify mappings as follows: @[toJSON TweetMapping, ...]@
591− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
594− IndexTemplate { templatePattern :: TemplatePattern
595− , templateSettings :: Maybe IndexSettings
596− , templateMappings :: [Value]
600− MappingField { mappingFieldName :: FieldName
601− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
603−{-| Support for type reification of 'Mapping's is currently incomplete, for
604− now the mapping API verbiage expects a 'ToJSON'able blob.
606− Indexes have mappings, mappings are schemas for the documents contained in the
607− index. I'd recommend having only one mapping per index, always having a mapping,
608− and keeping different kinds of documents separated if possible.
610−data Mapping = Mapping { typeName :: TypeName
611− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
613−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
614− operation index, create, delete, and update. 'BulkIndex' behaves like an
615− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
617− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
620− BulkIndex IndexName MappingName DocId Value
621− | BulkCreate IndexName MappingName DocId Value
622− | BulkDelete IndexName MappingName DocId
623− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
625−{-| 'EsResult' describes the standard wrapper JSON document that you see in
626− successful Elasticsearch lookups or lookups that couldn't find the document.
628−data EsResult a = EsResult { _index :: Text
631− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
633−{-| 'EsResultFound' contains the document and its metadata inside of an
634− 'EsResult' when the document was successfully found.
636−data EsResultFound a = EsResultFound { _version :: DocVersion
637− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
639−{-| 'EsError' is the generic type that will be returned when there was a
640− problem. If you can't parse the expected response, its a good idea to
643−data EsError = EsError { errorStatus :: Int
644− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
646−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
647−returned by the ElasticSearch server. If you encounter this error, please
648−verify that your domain data types and FromJSON instances are working properly
649−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
650−sure that your mappings are correct, then this error may be an indication of an
651−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
652−and be sure to include the exception body.
654−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
655− deriving (Eq, Read, Show, Generic, Typeable)
657−instance Exception EsProtocolException
659−data IndexAlias = IndexAlias { srcIndex :: IndexName
660− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
662−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
664−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
665− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
667−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
668− , aliasCreateFilter :: Maybe Filter}
669− deriving (Read, Show, Eq, Generic, Typeable)
671−data AliasRouting = AllAliasRouting RoutingValue
672− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
673− deriving (Read, Show, Eq, Generic, Typeable)
675−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
677−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
679−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
681−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
683−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
684−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
685− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
687−{-| 'DocVersion' is an integer version number for a document between 1
688−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
690−newtype DocVersion = DocVersion {
691− docVersionNumber :: Int
692− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
694−-- | Smart constructor for in-range doc version
695−mkDocVersion :: Int -> Maybe DocVersion
697− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
699− | otherwise = Nothing
702−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
703−own version numbers instead of ones from ES.
705−newtype ExternalDocVersion = ExternalDocVersion DocVersion
706− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
708−{-| 'VersionControl' is specified when indexing documents as a
709−optimistic concurrency control.
711−data VersionControl = NoVersionControl
712− -- ^ Don't send a version. This is a pure overwrite.
713− | InternalVersion DocVersion
714− -- ^ Use the default ES versioning scheme. Only
715− -- index the document if the version is the same
716− -- as the one specified. Only applicable to
717− -- updates, as you should be getting Version from
719− | ExternalGT ExternalDocVersion
720− -- ^ Use your own version numbering. Only index
721− -- the document if the version is strictly higher
722− -- OR the document doesn't exist. The given
723− -- version will be used as the new version number
724− -- for the stored document. N.B. All updates must
725− -- increment this number, meaning there is some
726− -- global, external ordering of updates.
727− | ExternalGTE ExternalDocVersion
728− -- ^ Use your own version numbering. Only index
729− -- the document if the version is equal or higher
730− -- than the stored version. Will succeed if there
731− -- is no existing document. The given version will
732− -- be used as the new version number for the
733− -- stored document. Use with care, as this could
734− -- result in data loss.
735− | ForceVersion ExternalDocVersion
736− -- ^ The document will always be indexed and the
737− -- given version will be the new version. This is
738− -- typically used for correcting errors. Use with
739− -- care, as this could result in data loss.
740− deriving (Read, Show, Eq, Generic, Ord)
742−{-| 'DocumentParent' is used to specify a parent document.
744−newtype DocumentParent = DocumentParent DocId
745− deriving (Eq, Read, Show, Generic, Typeable)
747−{-| 'IndexDocumentSettings' are special settings supplied when indexing
748−a document. For the best backwards compatiblity when new fields are
749−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
751−data IndexDocumentSettings =
752− IndexDocumentSettings { idsVersionControl :: VersionControl
753− , idsParent :: Maybe DocumentParent
754− } deriving (Eq, Read, Show, Generic, Typeable)
756−{-| Reasonable default settings. Chooses no version control and no parent.
758−defaultIndexDocumentSettings :: IndexDocumentSettings
759−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
761−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
762− dependent with later sorts acting as tie-breakers for earlier sorts.
764−type Sort = [SortSpec]
766−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
767− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
768− 'DistanceUnit' to express "nearness" to a single geographical point as a
771−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
773−data SortSpec = DefaultSortSpec DefaultSort
774− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
776−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
777− 'mkSort' convenience function for when you want to specify only the most
780−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
783− DefaultSort { sortFieldName :: FieldName
784− , sortOrder :: SortOrder
786− , ignoreUnmapped :: Bool
787− , sortMode :: Maybe SortMode
788− , missingSort :: Maybe Missing
789− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
791−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
792− encoded into "asc" or "desc" when turned into JSON.
794−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
796−data SortOrder = Ascending
797− | Descending deriving (Eq, Read, Show, Generic, Typeable)
799−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
800− sorted last, first, or using a custom value as a substitute.
802−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
804−data Missing = LastMissing
806− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
808−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
810−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
812−data SortMode = SortMin
815− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
817−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
818− that you can concisely describe the usual kind of 'SortSpec's you want.
820−mkSort :: FieldName -> SortOrder -> DefaultSort
821−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
823−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
824− 'Query's cannot be cached.
826−type Cache = Bool -- caching on/off
827−defaultCache :: Cache
830−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
832−type PrefixValue = Text
834−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
835− JSON encoding baked in. Used all over the place.
837−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
839−{-| 'ShardCount' is part of 'IndexSettings'
841−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
843−{-| 'ReplicaCount' is part of 'IndexSettings'
845−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
847−{-| 'IndexName' is used to describe which index to query/create/delete
849−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
851−{-| 'IndexSelection' is used for APIs which take a single index, a list of
852− indexes, or the special @_all@ index.
854−data IndexSelection = IndexList (NonEmpty IndexName)
855− | AllIndexes deriving (Eq, Generic, Show, Typeable)
857−{-| 'TemplateName' is used to describe which template to query/create/delete
859−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
861−{-| 'TemplatePattern' represents a pattern which is matched against index names
863−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
865−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
866− the data in the indices.
868−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
870−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
871− Can be set by the user or created by ES itself. Often used in client
872− functions for poking at specific documents.
874−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
876−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
878−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
880−{-| 'FieldName' is used all over the place wherever a specific field within
881− a document needs to be specified, usually in 'Query's or 'Filter's.
883−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
886−{-| 'Script' is often used in place of 'FieldName' to specify more
887−complex ways of extracting a value from a document.
889−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
891−{-| 'CacheName' is used in 'RegexpFilter' for describing the
892− 'CacheKey' keyed caching behavior.
894−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
896−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
899− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
901− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
903− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
904−newtype CutoffFrequency =
905− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
907− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
908−newtype MaxExpansions =
909− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
911−{-| 'Lenient', if set to true, will cause format based failures to be
912− ignored. I don't know what the bloody default is, Elasticsearch
913− documentation didn't say what it was. Let me know if you figure it out.
916− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
918− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
920− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
922− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
924−{-| 'MinimumMatch' controls how many should clauses in the bool query should
925− match. Can be an absolute value (2) or a percentage (30%) or a
926− combination of both.
928−newtype MinimumMatch =
929− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
930−newtype DisableCoord =
931− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
932−newtype IgnoreTermFrequency =
933− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
934−newtype MinimumTermFrequency =
935− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
936−newtype MaxQueryTerms =
937− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
939− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
941−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
942−newtype PrefixLength =
943− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
945− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
946−newtype PercentMatch =
947− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
949− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
951− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
953−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
954− heavy, because all terms in the index need to be examined, just in case
955− they match. Leading wildcards can be disabled by setting
956− 'AllowLeadingWildcard' to false. -}
957−newtype AllowLeadingWildcard =
958− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
959−newtype LowercaseExpanded =
960− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
961−newtype EnablePositionIncrements =
962− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
964−{-| By default, wildcard terms in a query are not analyzed.
965− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
967−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
969−{-| 'GeneratePhraseQueries' defaults to false.
971−newtype GeneratePhraseQueries =
972− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
974−{-| 'Locale' is used for string conversions - defaults to ROOT.
976−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
977−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
978−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
980−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
981− phrase matches. Default is 0.
983−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
984−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
985−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
987−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
988−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
990{-| 'unpackId' is a silly convenience function that gets used once.
430{-| 'unpackId' is a silly convenience function that gets used once.
@@ -993,8 +433,6 @@ unpackId :: DocId -> Text
993unpackId (DocId docId) = docId
433unpackId (DocId docId) = docId
995type TrackSortScores = Bool
435type TrackSortScores = Bool
996−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
997−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
999data Search = Search { queryBody :: Maybe Query
437data Search = Search { queryBody :: Maybe Query
1000 , filterBody :: Maybe Filter
438 , filterBody :: Maybe Filter
@@ -1006,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
1006 , from :: From
444 , from :: From
1007 , size :: Size
445 , size :: Size
1008 , searchType :: SearchType
446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
1009 , fields :: Maybe [FieldName]
448 , fields :: Maybe [FieldName]
449+ , scriptFields :: Maybe ScriptFields
1010− , 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)
1012data SearchType = SearchTypeQueryThenFetch
480data SearchType = SearchTypeQueryThenFetch
1013 | SearchTypeDfsQueryThenFetch
481 | SearchTypeDfsQueryThenFetch
1016− | SearchTypeQueryAndFetch
1017− | SearchTypeDfsQueryAndFetch
1018− deriving (Eq, Read, Show, Generic, Typeable)
482+ deriving (Eq, Show)
1020data Source =
484data Source =
1021 NoSource
485 NoSource
1022 | SourcePatterns PatternOrPatterns
486 | SourcePatterns PatternOrPatterns
1023 | SourceIncludeExclude Include Exclude
487 | SourceIncludeExclude Include Exclude
1024− deriving (Read, Show, Eq, Generic, Typeable)
488+ deriving (Eq, Show)
1026−data PatternOrPatterns = PopPattern Pattern
1027− | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1029−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1030−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1032−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
1034−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1035− , highlightFields :: [FieldHighlight]
1036− } deriving (Read, Show, Eq, Generic, Typeable)
1038−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1039− deriving (Read, Show, Eq, Generic, Typeable)
1042−data HighlightSettings = Plain PlainHighlight
1043− | Postings PostingsHighlight
1044− | FastVector FastVectorHighlight
1045− deriving (Read, Show, Eq, Generic, Typeable)
1046−data PlainHighlight =
1047− PlainHighlight { plainCommon :: Maybe CommonHighlight
1048− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1050− -- This requires that index_options are set to 'offset' in the mapping.
1051−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1053−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1054−data FastVectorHighlight =
1055− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1056− , fvNonPostSettings :: Maybe NonPostings
1057− , boundaryChars :: Maybe Text
1058− , boundaryMaxScan :: Maybe Int
1059− , fragmentOffset :: Maybe Int
1060− , matchedFields :: [Text]
1061− , phraseLimit :: Maybe Int
1062− } deriving (Read, Show, Eq, Generic, Typeable)
1064−data CommonHighlight =
1065− CommonHighlight { order :: Maybe Text
1066− , forceSource :: Maybe Bool
1067− , tag :: Maybe HighlightTag
1068− , encoder :: Maybe HighlightEncoder
1069− , noMatchSize :: Maybe Int
1070− , highlightQuery :: Maybe Query
1071− , requireFieldMatch :: Maybe Bool
1072− } deriving (Read, Show, Eq, Generic, Typeable)
1074−-- Settings that are only applicable to FastVector and Plain highlighters.
1076− NonPostings { fragmentSize :: Maybe Int
1077− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1079−data HighlightEncoder = DefaultEncoder
1081− deriving (Read, Show, Eq, Generic, Typeable)
1083−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1084−data HighlightTag = TagSchema Text
1085− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1086− deriving (Read, Show, Eq, Generic, Typeable)
1090− TermQuery Term (Maybe Boost)
1091− | TermsQuery Text (NonEmpty Text)
1092− | QueryMatchQuery MatchQuery
1093− | QueryMultiMatchQuery MultiMatchQuery
1094− | QueryBoolQuery BoolQuery
1095− | QueryBoostingQuery BoostingQuery
1096− | QueryCommonTermsQuery CommonTermsQuery
1097− | ConstantScoreFilter Filter Boost
1098− | ConstantScoreQuery Query Boost
1099− | QueryDisMaxQuery DisMaxQuery
1100− | QueryFilteredQuery FilteredQuery
1101− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1102− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1103− | QueryFuzzyQuery FuzzyQuery
1104− | QueryHasChildQuery HasChildQuery
1105− | QueryHasParentQuery HasParentQuery
1106− | IdsQuery MappingName [DocId]
1107− | QueryIndicesQuery IndicesQuery
1108− | MatchAllQuery (Maybe Boost)
1109− | QueryMoreLikeThisQuery MoreLikeThisQuery
1110− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1111− | QueryNestedQuery NestedQuery
1112− | QueryPrefixQuery PrefixQuery
1113− | QueryQueryStringQuery QueryStringQuery
1114− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1115− | QueryRangeQuery RangeQuery
1116− | QueryRegexpQuery RegexpQuery
1117− deriving (Eq, Read, Show, Generic, Typeable)
1120− RegexpQuery { regexpQueryField :: FieldName
1121− , regexpQuery :: Regexp
1122− , regexpQueryFlags :: RegexpFlags
1123− , regexpQueryBoost :: Maybe Boost
1124− } deriving (Eq, Read, Show, Generic, Typeable)
1127− RangeQuery { rangeQueryField :: FieldName
1128− , rangeQueryRange :: RangeValue
1129− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1131−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1132−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1134−data SimpleQueryStringQuery =
1135− SimpleQueryStringQuery
1136− { simpleQueryStringQuery :: QueryString
1137− , simpleQueryStringField :: Maybe FieldOrFields
1138− , simpleQueryStringOperator :: Maybe BooleanOperator
1139− , simpleQueryStringAnalyzer :: Maybe Analyzer
1140− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1141− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1142− , simpleQueryStringLocale :: Maybe Locale
1143− } deriving (Eq, Read, Show, Generic, Typeable)
1145−data SimpleQueryFlag =
1150− | SimpleQueryPrefix
1151− | SimpleQueryPhrase
1152− | SimpleQueryPrecedence
1153− | SimpleQueryEscape
1154− | SimpleQueryWhitespace
1157− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1159−-- use_dis_max and tie_breaker when fields are plural?
1160−data QueryStringQuery =
1162− { queryStringQuery :: QueryString
1163− , queryStringDefaultField :: Maybe FieldName
1164− , queryStringOperator :: Maybe BooleanOperator
1165− , queryStringAnalyzer :: Maybe Analyzer
1166− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1167− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1168− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1169− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1170− , queryStringFuzziness :: Maybe Fuzziness
1171− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1172− , queryStringPhraseSlop :: Maybe PhraseSlop
1173− , queryStringBoost :: Maybe Boost
1174− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1175− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1176− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1177− , queryStringLenient :: Maybe Lenient
1178− , queryStringLocale :: Maybe Locale
1179− } deriving (Eq, Read, Show, Generic, Typeable)
1181−mkQueryStringQuery :: QueryString -> QueryStringQuery
1182−mkQueryStringQuery qs =
1183− QueryStringQuery qs Nothing Nothing
1184− Nothing Nothing Nothing Nothing
1185− Nothing Nothing Nothing Nothing
1186− Nothing Nothing Nothing Nothing
1189−data FieldOrFields = FofField FieldName
1190− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1194− { prefixQueryField :: FieldName
1195− , prefixQueryPrefixValue :: Text
1196− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1198−data NestedQuery =
490+instance ToJSON Source where
1199− NestedQuery
491+ toJSON NoSource = toJSON False
1200− { nestedQueryPath :: QueryPath
492+ toJSON (SourcePatterns patterns) = toJSON patterns
1201− , nestedQueryScoreType :: ScoreType
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1202− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1204−data MoreLikeThisFieldQuery =
1205− MoreLikeThisFieldQuery
1206− { moreLikeThisFieldText :: Text
1207− , moreLikeThisFieldFields :: FieldName
1208− -- default 0.3 (30%)
1209− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1210− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1211− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1212− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1213− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1214− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1215− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1216− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1217− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1218− , moreLikeThisFieldBoost :: Maybe Boost
1219− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1220− } deriving (Eq, Read, Show, Generic, Typeable)
1222−data MoreLikeThisQuery =
1224− { moreLikeThisText :: Text
1225− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1226− -- default 0.3 (30%)
1227− , moreLikeThisPercentMatch :: Maybe PercentMatch
1228− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1229− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1230− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1231− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1232− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1233− , moreLikeThisMinWordLength :: Maybe MinWordLength
1234− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1235− , moreLikeThisBoostTerms :: Maybe BoostTerms
1236− , moreLikeThisBoost :: Maybe Boost
1237− , moreLikeThisAnalyzer :: Maybe Analyzer
1238− } deriving (Eq, Read, Show, Generic, Typeable)
1242− { indicesQueryIndices :: [IndexName]
1243− , indicesQuery :: Query
1245− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1247−data HasParentQuery =
1249− { hasParentQueryType :: TypeName
1250− , hasParentQuery :: Query
1251− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1253−data HasChildQuery =
1255− { hasChildQueryType :: TypeName
1256− , hasChildQuery :: Query
1257− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1263− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1266− FuzzyQuery { fuzzyQueryField :: FieldName
1267− , fuzzyQueryValue :: Text
1268− , fuzzyQueryPrefixLength :: PrefixLength
1269− , fuzzyQueryMaxExpansions :: MaxExpansions
1270− , fuzzyQueryFuzziness :: Fuzziness
1271− , fuzzyQueryBoost :: Maybe Boost
1272− } deriving (Eq, Read, Show, Generic, Typeable)
1274−data FuzzyLikeFieldQuery =
1275− FuzzyLikeFieldQuery
1276− { fuzzyLikeField :: FieldName
1277− -- anaphora is good for the soul.
1278− , fuzzyLikeFieldText :: Text
1279− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1280− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1281− , fuzzyLikeFieldFuzziness :: Fuzziness
1282− , fuzzyLikeFieldPrefixLength :: PrefixLength
1283− , fuzzyLikeFieldBoost :: Boost
1284− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1285− } deriving (Eq, Read, Show, Generic, Typeable)
1287−data FuzzyLikeThisQuery =
1289− { fuzzyLikeFields :: [FieldName]
1290− , fuzzyLikeText :: Text
1291− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1292− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1293− , fuzzyLikeFuzziness :: Fuzziness
1294− , fuzzyLikePrefixLength :: PrefixLength
1295− , fuzzyLikeBoost :: Boost
1296− , fuzzyLikeAnalyzer :: Maybe Analyzer
1297− } deriving (Eq, Read, Show, Generic, Typeable)
1299−data FilteredQuery =
1301− { filteredQuery :: Query
1302− , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1305− DisMaxQuery { disMaxQueries :: [Query]
1307− , disMaxTiebreaker :: Tiebreaker
1308− , disMaxBoost :: Maybe Boost
1309− } deriving (Eq, Read, Show, Generic, Typeable)
1312− MatchQuery { matchQueryField :: FieldName
1313− , matchQueryQueryString :: QueryString
1314− , matchQueryOperator :: BooleanOperator
1315− , matchQueryZeroTerms :: ZeroTermsQuery
1316− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1317− , matchQueryMatchType :: Maybe MatchQueryType
1318− , matchQueryAnalyzer :: Maybe Analyzer
1319− , matchQueryMaxExpansions :: Maybe MaxExpansions
1320− , matchQueryLenient :: Maybe Lenient
1321− , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1323−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1324− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1326−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1327−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1329−data MatchQueryType =
1331− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1333−data MultiMatchQuery =
1334− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1335− , multiMatchQueryString :: QueryString
1336− , multiMatchQueryOperator :: BooleanOperator
1337− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1338− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1339− , multiMatchQueryType :: Maybe MultiMatchQueryType
1340− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1341− , multiMatchQueryAnalyzer :: Maybe Analyzer
1342− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1343− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1345−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1346− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1347− make a 'MultiMatchQuery'.
1350−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1351−mkMultiMatchQuery matchFields query =
1352− MultiMatchQuery matchFields query
1353− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1355−data MultiMatchQueryType =
1356− MultiMatchBestFields
1357− | MultiMatchMostFields
1358− | MultiMatchCrossFields
1360− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1363− BoolQuery { boolQueryMustMatch :: [Query]
1364− , boolQueryMustNotMatch :: [Query]
1365− , boolQueryShouldMatch :: [Query]
1366− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1367− , boolQueryBoost :: Maybe Boost
1368− , boolQueryDisableCoord :: Maybe DisableCoord
1369− } deriving (Eq, Read, Show, Generic, Typeable)
1371−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1372−mkBoolQuery must mustNot should =
1373− BoolQuery must mustNot should Nothing Nothing Nothing
1375−data BoostingQuery =
1376− BoostingQuery { positiveQuery :: Query
1377− , negativeQuery :: Query
1378− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1380−data CommonTermsQuery =
1381− CommonTermsQuery { commonField :: FieldName
1382− , commonQuery :: QueryString
1383− , commonCutoffFrequency :: CutoffFrequency
1384− , commonLowFreqOperator :: BooleanOperator
1385− , commonHighFreqOperator :: BooleanOperator
1386− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1387− , commonBoost :: Maybe Boost
1388− , commonAnalyzer :: Maybe Analyzer
1389− , commonDisableCoord :: Maybe DisableCoord
1390− } deriving (Eq, Read, Show, Generic, Typeable)
1392−data CommonMinimumMatch =
1393− CommonMinimumMatchHighLow MinimumMatchHighLow
1394− | CommonMinimumMatch MinimumMatch
1395− deriving (Eq, Read, Show, Generic, Typeable)
1397−data MinimumMatchHighLow =
1398− MinimumMatchHighLow { lowFreq :: MinimumMatch
1399− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1401−data Filter = AndFilter [Filter] Cache
1402− | OrFilter [Filter] Cache
1403− | NotFilter Filter Cache
1405− | BoolFilter BoolMatch
1406− | ExistsFilter FieldName -- always cached
1407− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1408− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1409− | GeoDistanceRangeFilter GeoPoint DistanceRange
1410− | GeoPolygonFilter FieldName [LatLon]
1411− | IdsFilter MappingName [DocId]
1413− | MissingFilter FieldName Existence NullValue
1414− | PrefixFilter FieldName PrefixValue Cache
1415− | QueryFilter Query Cache
1416− | RangeFilter FieldName RangeValue RangeExecution Cache
1417− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1418− | TermFilter Term Cache
1419− deriving (Eq, Read, Show, Generic, Typeable)
1421−data ZeroTermsQuery = ZeroTermsNone
1422− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1424−data RangeExecution = RangeExecutionIndex
1425− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1427−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1429−data RegexpFlags = AllRegexpFlags
1431− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1433−data RegexpFlag = AnyString
1438− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1440−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1441−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1442−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1443−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1445−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1446−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1447−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1448−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1450−data RangeValue = RangeDateLte LessThanEqD
1451− | RangeDateLt LessThanD
1452− | RangeDateGte GreaterThanEqD
1453− | RangeDateGt GreaterThanD
1454− | RangeDateGtLt GreaterThanD LessThanD
1455− | RangeDateGteLte GreaterThanEqD LessThanEqD
1456− | RangeDateGteLt GreaterThanEqD LessThanD
1457− | RangeDateGtLte GreaterThanD LessThanEqD
1458− | RangeDoubleLte LessThanEq
1459− | RangeDoubleLt LessThan
1460− | RangeDoubleGte GreaterThanEq
1461− | RangeDoubleGt GreaterThan
1462− | RangeDoubleGtLt GreaterThan LessThan
1463− | RangeDoubleGteLte GreaterThanEq LessThanEq
1464− | RangeDoubleGteLt GreaterThanEq LessThan
1465− | RangeDoubleGtLte GreaterThan LessThanEq
1466− deriving (Eq, Read, Show, Generic, Typeable)
1468−rangeValueToPair :: RangeValue -> [Pair]
1469−rangeValueToPair rv = case rv of
1470− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1471− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1472− RangeDateLt (LessThanD t) -> ["lt" .= t]
1473− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1474− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1475− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1476− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1477− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1478− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1479− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1480− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1481− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1482− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1483− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1484− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1485− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1487−data Term = Term { termField :: Text
1488− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1490−data BoolMatch = MustMatch Term Cache
1491− | MustNotMatch Term Cache
1492− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1494−-- "memory" or "indexed"
1495−data GeoFilterType = GeoFilterMemory
1496− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1498−data LatLon = LatLon { lat :: Double
1499− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1501−data GeoBoundingBox =
1502− GeoBoundingBox { topLeft :: LatLon
1503− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1505−data GeoBoundingBoxConstraint =
495+data PatternOrPatterns = PopPattern Pattern
1506− GeoBoundingBoxConstraint { geoBBField :: FieldName
1507− , constraintBox :: GeoBoundingBox
1508− , bbConstraintcache :: Cache
1509− , geoType :: GeoFilterType
1510− } deriving (Eq, Read, Show, Generic, Typeable)
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1512−data GeoPoint =
498+instance ToJSON PatternOrPatterns where
1513− GeoPoint { geoField :: FieldName
499+ toJSON (PopPattern pattern) = toJSON pattern
1514− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
500+ toJSON (PopPatterns patterns) = toJSON patterns
1516−data DistanceUnit = Miles
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
1524− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1526−data DistanceType = Arc
505+instance ToJSON Include where
1527− | SloppyArc -- doesn't exist <1.0
506+ toJSON (Include patterns) = toJSON patterns
1528− | Plane deriving (Eq, Read, Show, Generic, Typeable)
1530−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
508+instance ToJSON Exclude where
1531− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
509+ toJSON (Exclude patterns) = toJSON patterns
1533−data Distance =
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1534− Distance { coefficient :: Double
1535− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1537−data DistanceRange =
513+instance ToJSON Pattern where
1538− DistanceRange { distanceFrom :: Distance
514+ toJSON (Pattern pattern) = toJSON pattern
1539− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
1541data SearchResult a =
516data SearchResult a =
1542 SearchResult { took :: Int
517 SearchResult { took :: Int
@@ -1544,2058 +519,12 @@ data SearchResult a =
1544 , shards :: ShardResult
519 , shards :: ShardResult
1545 , searchHits :: SearchHits a
520 , searchHits :: SearchHits a
1546 , aggregations :: Maybe AggregationResults
521 , aggregations :: Maybe AggregationResults
1547− , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
522+ , scrollId :: Maybe ScrollId
1548−
523+ -- ^ Only one Suggestion request / response per
1549−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
524+ -- Search is supported.
1550−
525+ , suggest :: Maybe NamedSuggestionResponse
1551−type Score = Maybe Double
526+ }
1552−
527+ deriving (Eq, Show)
1554− SearchHits { hitsTotal :: Int
1555− , maxScore :: Score
1556− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1559−instance Monoid (SearchHits a) where
1560− mempty = SearchHits 0 Nothing mempty
1561− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1562− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1566− Hit { hitIndex :: IndexName
1567− , hitType :: MappingName
1568− , hitDocId :: DocId
1569− , hitScore :: Score
1570− , hitSource :: Maybe a
1571− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1574− ShardResult { shardTotal :: Int
1575− , shardsSuccessful :: Int
1576− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1578−type HitHighlight = M.Map Text [Text]
1580−showText :: Show a => a -> Text
1581−showText = T.pack . show
1583−readMay :: Read a => String -> Maybe a
1584−readMay s = case reads s of
1585− (a, ""):_ -> Just a
1588−parseReadText :: Read a => Text -> Parser a
1589−parseReadText = maybe mzero return . readMay . T.unpack
1591−type Aggregations = M.Map Text Aggregation
1593−emptyAggregations :: Aggregations
1594−emptyAggregations = M.empty
1596−mkAggregations :: Text -> Aggregation -> Aggregations
1597−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1599−data TermOrder = TermOrder{ termSortField :: Text
1600− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1602−data TermInclusion = TermInclusion Text
1603− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1605−data CollectionMode = BreadthFirst
1606− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1608−data ExecutionHint = Ordinals
1610− | GlobalOrdinalsHash
1611− | GlobalOrdinalsLowCardinality
1612− | Map deriving (Eq, Read, Show, Generic, Typeable)
1614−data TimeInterval = Weeks
1618− | Seconds deriving Eq
1620−data Interval = Year
1628− | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1630−data Aggregation = TermsAgg TermsAggregation
1631− | DateHistogramAgg DateHistogramAggregation
1632− | ValueCountAgg ValueCountAggregation
1633− | FilterAgg FilterAggregation
1634− | DateRangeAgg DateRangeAggregation
1635− | MissingAgg MissingAggregation deriving (Eq, Read, Show, Generic, Typeable)
1637−data MissingAggregation = MissingAggregation
1639− } deriving (Eq, Read, Show, Generic, Typeable)
1641−data TermsAggregation = TermsAggregation { term :: Either Text Text
1642− , termInclude :: Maybe TermInclusion
1643− , termExclude :: Maybe TermInclusion
1644− , termOrder :: Maybe TermOrder
1645− , termMinDocCount :: Maybe Int
1646− , termSize :: Maybe Int
1647− , termShardSize :: Maybe Int
1648− , termCollectMode :: Maybe CollectionMode
1649− , termExecutionHint :: Maybe ExecutionHint
1650− , termAggs :: Maybe Aggregations
1651− } deriving (Eq, Read, Show, Generic, Typeable)
1653−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1654− , dateInterval :: Interval
1655− , dateFormat :: Maybe Text
1656− -- pre and post deprecated in 1.5
1657− , datePreZone :: Maybe Text
1658− , datePostZone :: Maybe Text
1659− , datePreOffset :: Maybe Text
1660− , datePostOffset :: Maybe Text
1661− , dateAggs :: Maybe Aggregations
1662− } deriving (Eq, Read, Show, Generic, Typeable)
1665−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1666− , draFormat :: Maybe Text
1667− , draRanges :: NonEmpty DateRangeAggRange
1668− } deriving (Eq, Read, Show, Generic, Typeable)
1670−data DateRangeAggRange = DateRangeFrom DateMathExpr
1671− | DateRangeTo DateMathExpr
1672− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1674−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1675−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1678−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1679−data DateMathAnchor = DMNow
1680− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1682−data DateMathModifier = AddTime Int DateMathUnit
1683− | SubtractTime Int DateMathUnit
1684− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1686−data DateMathUnit = DMYear
1692− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1694−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1695−data ValueCountAggregation = FieldValueCount FieldName
1696− | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1698−-- | 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.
1699−data FilterAggregation = FilterAggregation { faFilter :: Filter
1700− , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1702−mkTermsAggregation :: Text -> TermsAggregation
1703−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1705−mkTermsScriptAggregation :: Text -> TermsAggregation
1706−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1708−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1709−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1711−instance ToJSON Version where
1712− toJSON Version {..} = object ["number" .= number
1713− ,"build_hash" .= build_hash
1714− ,"build_timestamp" .= build_timestamp
1715− ,"build_snapshot" .= build_snapshot
1716− ,"lucene_version" .= lucene_version]
1718−instance FromJSON Version where
1719− parseJSON = withObject "Version" parse
1720− where parse o = Version
1722− <*> o .: "build_hash"
1723− <*> o .: "build_timestamp"
1724− <*> o .: "build_snapshot"
1725− <*> o .: "lucene_version"
1727−instance ToJSON TermOrder where
1728− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1730−instance ToJSON TermInclusion where
1731− toJSON (TermInclusion x) = toJSON x
1732− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1735−instance ToJSON CollectionMode where
1736− toJSON BreadthFirst = "breadth_first"
1737− toJSON DepthFirst = "depth_first"
1739−instance ToJSON ExecutionHint where
1740− toJSON Ordinals = "ordinals"
1741− toJSON GlobalOrdinals = "global_ordinals"
1742− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1743− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1746−instance ToJSON Interval where
1747− toJSON Year = "year"
1748− toJSON Quarter = "quarter"
1749− toJSON Month = "month"
1750− toJSON Week = "week"
1752− toJSON Hour = "hour"
1753− toJSON Minute = "minute"
1754− toJSON Second = "second"
1755− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1757−instance Show TimeInterval where
1764−instance Read TimeInterval where
1765− readPrec = f =<< TR.get
1767− f 'w' = return Weeks
1768− f 'd' = return Days
1769− f 'h' = return Hours
1770− f 'm' = return Minutes
1771− f 's' = return Seconds
1772− f _ = fail "TimeInterval expected one of w, d, h, m, s"
1774−instance ToJSON Aggregation where
1775− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1776− omitNulls ["terms" .= omitNulls [ toJSON' term,
1777− "include" .= include,
1778− "exclude" .= exclude,
1780− "min_doc_count" .= minDocCount,
1782− "shard_size" .= shardSize,
1783− "collect_mode" .= collectMode,
1784− "execution_hint" .= executionHint
1786− "aggs" .= termAggs ]
1788− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1790− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1791− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1792− "interval" .= interval,
1793− "format" .= format,
1794− "pre_zone" .= preZone,
1795− "post_zone" .= postZone,
1796− "pre_offset" .= preOffset,
1797− "post_offset" .= postOffset
1799− "aggs" .= dateHistoAggs ]
1800− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1801− where v = case a of
1802− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1803− (ScriptValueCount (Script s)) -> object ["script" .= s]
1804− toJSON (FilterAgg (FilterAggregation filt ags)) =
1805− omitNulls [ "filter" .= filt
1807− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1809− toJSON (MissingAgg (MissingAggregation{..})) =
1810− object ["missing" .= object ["field" .= maField]]
1812−instance ToJSON DateRangeAggregation where
1813− toJSON DateRangeAggregation {..} =
1814− omitNulls [ "field" .= draField
1815− , "format" .= draFormat
1816− , "ranges" .= toList draRanges
1819−instance ToJSON DateRangeAggRange where
1820− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1821− toJSON (DateRangeTo e) = object [ "to" .= e ]
1822− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1824−instance ToJSON DateMathExpr where
1825− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1826− where fmtA DMNow = "now"
1827− fmtA (DMDate date) = case toGregorian date of
1828− (y,m,d) -> showText y <> "-" <>
1829− showText m <> "-" <>
1831− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1832− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1833− fmtMod (RoundDownTo u) = "/" <> fmtU u
1839− fmtU DMMinute = "m"
1840− fmtU DMSecond = "s"
1843−type AggregationResults = M.Map Text Value
1845−class BucketAggregation a where
1846− key :: a -> BucketValue
1847− docCount :: a -> Int
1848− aggs :: a -> Maybe AggregationResults
1851−data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1853−data BucketValue = TextValue Text
1854− | ScientificValue Scientific
1855− | BoolValue Bool deriving (Read, Show)
1857−data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1859−data TermsResult = TermsResult { termKey :: BucketValue
1860− , termsDocCount :: Int
1861− , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1863−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1864− , dateKeyStr :: Maybe Text
1865− , dateDocCount :: Int
1866− , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1868−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1869− , dateRangeFrom :: Maybe UTCTime
1870− , dateRangeFromAsString :: Maybe Text
1871− , dateRangeTo :: Maybe UTCTime
1872− , dateRangeToAsString :: Maybe Text
1873− , dateRangeDocCount :: Int
1874− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1876−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1877−toTerms = toAggResult
1879−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1880−toDateHistogram = toAggResult
1882−toMissing :: Text -> AggregationResults -> Maybe MissingResult
1883−toMissing = toAggResult
1885−toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1886−toAggResult t a = M.lookup t a >>= deserialize
1887− where deserialize = parseMaybe parseJSON
1889−instance BucketAggregation TermsResult where
1891− docCount = termsDocCount
1894−instance BucketAggregation DateHistogramResult where
1895− key = TextValue . showText . dateKey
1896− docCount = dateDocCount
1897− aggs = dateHistogramAggs
1899−instance BucketAggregation DateRangeResult where
1900− key = TextValue . dateRangeKey
1901− docCount = dateRangeDocCount
1902− aggs = dateRangeAggs
1904−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1905− parseJSON (Object v) = Bucket <$>
1907− parseJSON _ = mempty
1909−instance FromJSON BucketValue where
1910− parseJSON (String t) = return $ TextValue t
1911− parseJSON (Number s) = return $ ScientificValue s
1912− parseJSON (Bool b) = return $ BoolValue b
1913− parseJSON _ = mempty
1915−instance FromJSON MissingResult where
1916− parseJSON = withObject "MissingResult" parse
1917− where parse v = MissingResult <$> v .: "doc_count"
1919−instance FromJSON TermsResult where
1920− parseJSON (Object v) = TermsResult <$>
1922− v .: "doc_count" <*>
1923− v .:? "aggregations"
1924− parseJSON _ = mempty
1926−instance FromJSON DateHistogramResult where
1927− parseJSON (Object v) = DateHistogramResult <$>
1929− v .:? "key_as_string" <*>
1930− v .: "doc_count" <*>
1931− v .:? "aggregations"
1932− parseJSON _ = mempty
1934−instance FromJSON DateRangeResult where
1935− parseJSON = withObject "DateRangeResult" parse
1936− where parse v = DateRangeResult <$>
1938− (fmap posixMS <$> v .:? "from") <*>
1939− v .:? "from_as_string" <*>
1940− (fmap posixMS <$> v .:? "to") <*>
1941− v .:? "to_as_string" <*>
1942− v .: "doc_count" <*>
1943− v .:? "aggregations"
1945−instance FromJSON POSIXMS where
1946− parseJSON = withScientific "POSIXMS" (return . parse)
1947− where parse n = let n' = truncate n :: Integer
1948− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1950−instance Monoid Filter where
1951− mempty = IdentityFilter
1952− mappend a b = AndFilter [a, b] defaultCache
1954−instance Seminearring Filter where
1955− a <||> b = OrFilter [a, b] defaultCache
1957−instance ToJSON Filter where
1958− toJSON (AndFilter filters cache) =
1960− object [ "filters" .= fmap toJSON filters
1961− , "_cache" .= cache]]
1963− toJSON (OrFilter filters cache) =
1965− object [ "filters" .= fmap toJSON filters
1966− , "_cache" .= cache]]
1968− toJSON (NotFilter notFilter cache) =
1970− object ["filter" .= notFilter
1971− , "_cache" .= cache]]
1973− toJSON (IdentityFilter) =
1974− object ["match_all" .= object []]
1976− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1977− object ["term" .= object base]
1978− where base = [termFilterField .= termFilterValue,
1981− toJSON (ExistsFilter (FieldName fieldName)) =
1982− object ["exists" .= object
1983− ["field" .= fieldName]]
1985− toJSON (BoolFilter boolMatch) =
1986− object ["bool" .= boolMatch]
1988− toJSON (GeoBoundingBoxFilter bbConstraint) =
1989− object ["geo_bounding_box" .= bbConstraint]
1991− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1992− distance distanceType optimizeBbox cache) =
1993− object ["geo_distance" .=
1994− object ["distance" .= distance
1995− , "distance_type" .= distanceType
1996− , "optimize_bbox" .= optimizeBbox
1997− , distanceGeoField .= geoDistLatLon
1998− , "_cache" .= cache]]
2000− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2001− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2002− object ["geo_distance_range" .=
2003− object ["from" .= geoDistRangeDistFrom
2004− , "to" .= drDistanceTo
2005− , gddrField .= drLatLon]]
2007− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2008− object ["geo_polygon" .=
2009− object [geoPolygonFilterField .=
2010− object ["points" .= fmap toJSON latLons]]]
2012− toJSON (IdsFilter (MappingName mappingName) values) =
2014− object ["type" .= mappingName
2015− , "values" .= fmap unpackId values]]
2017− toJSON (LimitFilter limit) =
2018− object ["limit" .= object ["value" .= limit]]
2020− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2021− object ["missing" .=
2022− object ["field" .= fieldName
2023− , "existence" .= existence
2024− , "null_value" .= nullValue]]
2026− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2027− object ["prefix" .=
2028− object [fieldName .= fieldValue
2029− , "_cache" .= cache]]
2031− toJSON (QueryFilter query False) =
2032− object ["query" .= toJSON query ]
2033− toJSON (QueryFilter query True) =
2034− object ["fquery" .=
2035− object [ "query" .= toJSON query
2036− , "_cache" .= True ]]
2038− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2040− object [ fieldName .= object (rangeValueToPair rangeValue)
2041− , "execution" .= rangeExecution
2042− , "_cache" .= cache]]
2044− toJSON (RegexpFilter (FieldName fieldName)
2045− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2046− object ["regexp" .=
2047− object [fieldName .=
2048− object ["value" .= regexText
2049− , "flags" .= flags]
2050− , "_name" .= cacheName
2051− , "_cache" .= cache
2052− , "_cache_key" .= cacheKey]]
2054−instance FromJSON Filter where
2055− parseJSON = withObject "Filter" parse
2056− where parse o = andFilter `taggedWith` "and"
2057− <|> orFilter `taggedWith` "or"
2058− <|> notFilter `taggedWith` "not"
2059− <|> identityFilter `taggedWith` "match_all"
2060− <|> boolFilter `taggedWith` "bool"
2061− <|> existsFilter `taggedWith` "exists"
2062− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2063− <|> geoDistanceFilter `taggedWith` "geo_distance"
2064− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2065− <|> geoPolygonFilter `taggedWith` "geo_polygon"
2066− <|> idsFilter `taggedWith` "ids"
2067− <|> limitFilter `taggedWith` "limit"
2068− <|> missingFilter `taggedWith` "missing"
2069− <|> prefixFilter `taggedWith` "prefix"
2070− <|> queryFilter `taggedWith` "query"
2071− <|> fqueryFilter `taggedWith` "fquery"
2072− <|> rangeFilter `taggedWith` "range"
2073− <|> regexpFilter `taggedWith` "regexp"
2074− <|> termFilter `taggedWith` "term"
2075− where taggedWith parser k = parser =<< o .: k
2076− andFilter o = AndFilter <$> o .: "filters"
2077− <*> o .:? "_cache" .!= defaultCache
2078− orFilter o = OrFilter <$> o .: "filters"
2079− <*> o .:? "_cache" .!= defaultCache
2080− notFilter o = NotFilter <$> o .: "filter"
2081− <*> o .: "_cache" .!= defaultCache
2082− identityFilter :: Object -> Parser Filter
2084− | HM.null m = pure IdentityFilter
2085− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2086− boolFilter = pure . BoolFilter
2087− existsFilter o = ExistsFilter <$> o .: "field"
2088− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2089− geoDistanceFilter o = do
2090− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2092− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2093− GeoDistanceFilter gp <$> o .: "distance"
2094− <*> o .: "distance_type"
2095− <*> o .: "optimize_bbox"
2096− <*> o .:? "_cache" .!= defaultCache
2097− _ -> fail "Could not find GeoDistanceFilter field name"
2098− geoDistanceRangeFilter o = do
2099− case HM.toList (deleteSeveral ["from", "to"] o) of
2101− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2102− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2103− return (GeoDistanceRangeFilter gp rng)
2104− _ -> fail "Could not find GeoDistanceRangeFilter field name"
2105− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2106− idsFilter o = IdsFilter <$> o .: "type"
2108− limitFilter o = LimitFilter <$> o .: "value"
2109− missingFilter o = MissingFilter <$> o .: "field"
2110− <*> o .: "existence"
2111− <*> o .: "null_value"
2112− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2113− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2114− _ -> fail "Could not parse PrefixFilter"
2116− queryFilter q = pure (QueryFilter q False)
2117− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2118− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2119− [(fn, v)] -> RangeFilter (FieldName fn)
2121− <*> o .: "execution"
2122− <*> o .:? "_cache" .!= defaultCache
2123− _ -> fail "Could not find field name for RangeFilter"
2124− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2125− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2129− <*> o .:? "_cache" .!= defaultCache
2130− <*> o .: "_cache_key"
2131− _ -> fail "Could not find field name for RegexpFilter"
2132− termFilter o = case HM.toList (HM.delete "_cache" o) of
2133− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2134− <$> o .:? "_cache" .!= defaultCache
2135− _ -> fail "Could not find term field for TermFilter"
2137−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2138−fieldTagged f o = case HM.toList o of
2139− [(k, Object o')] -> f (FieldName k) o'
2140− _ -> fail "Expected object with 1 field-named key"
2142−instance ToJSON GeoPoint where
2143− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2144− object [ geoPointField .= geoPointLatLon ]
2147−instance ToJSON Query where
2148− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2150− object [termQueryField .= object merged]]
2152− base = [ "value" .= termQueryValue ]
2153− boosted = maybe [] (return . ("boost" .=)) boost
2154− merged = mappend base boosted
2156− toJSON (TermsQuery fieldName terms) =
2157− object [ "terms" .= object conjoined ]
2158− where conjoined = [fieldName .= terms]
2160− toJSON (IdsQuery idsQueryMappingName docIds) =
2161− object [ "ids" .= object conjoined ]
2162− where conjoined = [ "type" .= idsQueryMappingName
2163− , "values" .= fmap toJSON docIds ]
2165− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2166− object [ "query_string" .= qQueryStringQuery ]
2168− toJSON (QueryMatchQuery matchQuery) =
2169− object [ "match" .= matchQuery ]
2171− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2172− toJSON multiMatchQuery
2174− toJSON (QueryBoolQuery boolQuery) =
2175− object [ "bool" .= boolQuery ]
2177− toJSON (QueryBoostingQuery boostingQuery) =
2178− object [ "boosting" .= boostingQuery ]
2180− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2181− object [ "common" .= commonTermsQuery ]
2183− toJSON (ConstantScoreFilter csFilter boost) =
2184− object ["constant_score" .= object ["filter" .= csFilter
2185− , "boost" .= boost]]
2187− toJSON (ConstantScoreQuery query boost) =
2188− object ["constant_score" .= object ["query" .= query
2189− , "boost" .= boost]]
2191− toJSON (QueryDisMaxQuery disMaxQuery) =
2192− object [ "dis_max" .= disMaxQuery ]
2194− toJSON (QueryFilteredQuery qFilteredQuery) =
2195− object [ "filtered" .= qFilteredQuery ]
2197− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2198− object [ "fuzzy_like_this" .= fuzzyQuery ]
2200− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2201− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2203− toJSON (QueryFuzzyQuery fuzzyQuery) =
2204− object [ "fuzzy" .= fuzzyQuery ]
2206− toJSON (QueryHasChildQuery childQuery) =
2207− object [ "has_child" .= childQuery ]
2209− toJSON (QueryHasParentQuery parentQuery) =
2210− object [ "has_parent" .= parentQuery ]
2212− toJSON (QueryIndicesQuery qIndicesQuery) =
2213− object [ "indices" .= qIndicesQuery ]
2215− toJSON (MatchAllQuery boost) =
2216− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2218− toJSON (QueryMoreLikeThisQuery query) =
2219− object [ "more_like_this" .= query ]
2221− toJSON (QueryMoreLikeThisFieldQuery query) =
2222− object [ "more_like_this_field" .= query ]
2224− toJSON (QueryNestedQuery query) =
2225− object [ "nested" .= query ]
2227− toJSON (QueryPrefixQuery query) =
2228− object [ "prefix" .= query ]
2230− toJSON (QueryRangeQuery query) =
2231− object [ "range" .= query ]
2233− toJSON (QueryRegexpQuery query) =
2234− object [ "regexp" .= query ]
2236− toJSON (QuerySimpleQueryStringQuery query) =
2237− object [ "simple_query_string" .= query ]
2239−instance FromJSON Query where
2240− parseJSON v = withObject "Query" parse v
2241− where parse o = termQuery `taggedWith` "term"
2242− <|> termsQuery `taggedWith` "terms"
2243− <|> idsQuery `taggedWith` "ids"
2244− <|> queryQueryStringQuery `taggedWith` "query_string"
2245− <|> queryMatchQuery `taggedWith` "match"
2246− <|> queryMultiMatchQuery
2247− <|> queryBoolQuery `taggedWith` "bool"
2248− <|> queryBoostingQuery `taggedWith` "boosting"
2249− <|> queryCommonTermsQuery `taggedWith` "common"
2250− <|> constantScoreFilter `taggedWith` "constant_score"
2251− <|> constantScoreQuery `taggedWith` "constant_score"
2252− <|> queryDisMaxQuery `taggedWith` "dis_max"
2253− <|> queryFilteredQuery `taggedWith` "filtered"
2254− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2255− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2256− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2257− <|> queryHasChildQuery `taggedWith` "has_child"
2258− <|> queryHasParentQuery `taggedWith` "has_parent"
2259− <|> queryIndicesQuery `taggedWith` "indices"
2260− <|> matchAllQuery `taggedWith` "match_all"
2261− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2262− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2263− <|> queryNestedQuery `taggedWith` "nested"
2264− <|> queryPrefixQuery `taggedWith` "prefix"
2265− <|> queryRangeQuery `taggedWith` "range"
2266− <|> queryRegexpQuery `taggedWith` "regexp"
2267− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2268− where taggedWith parser k = parser =<< o .: k
2269− termQuery = fieldTagged $ \(FieldName fn) o ->
2270− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2271− termsQuery o = case HM.toList o of
2272− [(fn, vs)] -> do vals <- parseJSON vs
2274− x:xs -> return (TermsQuery fn (x :| xs))
2275− _ -> fail "Expected non empty list of values"
2276− _ -> fail "Expected object with 1 field-named key"
2277− idsQuery o = IdsQuery <$> o .: "type"
2279− queryQueryStringQuery = pure . QueryQueryStringQuery
2280− queryMatchQuery = pure . QueryMatchQuery
2281− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2282− queryBoolQuery = pure . QueryBoolQuery
2283− queryBoostingQuery = pure . QueryBoostingQuery
2284− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2285− constantScoreFilter o = case HM.lookup "filter" o of
2286− Just x -> ConstantScoreFilter <$> parseJSON x
2288− _ -> fail "Does not appear to be a ConstantScoreFilter"
2289− constantScoreQuery o = case HM.lookup "query" o of
2290− Just x -> ConstantScoreQuery <$> parseJSON x
2292− _ -> fail "Does not appear to be a ConstantScoreQuery"
2293− queryDisMaxQuery = pure . QueryDisMaxQuery
2294− queryFilteredQuery = pure . QueryFilteredQuery
2295− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2296− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2297− queryFuzzyQuery = pure . QueryFuzzyQuery
2298− queryHasChildQuery = pure . QueryHasChildQuery
2299− queryHasParentQuery = pure . QueryHasParentQuery
2300− queryIndicesQuery = pure . QueryIndicesQuery
2301− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2302− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2303− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2304− queryNestedQuery = pure . QueryNestedQuery
2305− queryPrefixQuery = pure . QueryPrefixQuery
2306− queryRangeQuery = pure . QueryRangeQuery
2307− queryRegexpQuery = pure . QueryRegexpQuery
2308− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2311−omitNulls :: [(Text, Value)] -> Value
2312−omitNulls = object . filter notNull where
2313− notNull (_, Null) = False
2314− notNull (_, Array a) = (not . V.null) a
2318−instance ToJSON SimpleQueryStringQuery where
2319− toJSON SimpleQueryStringQuery {..} =
2320− omitNulls (base ++ maybeAdd)
2321− where base = [ "query" .= simpleQueryStringQuery ]
2322− maybeAdd = [ "fields" .= simpleQueryStringField
2323− , "default_operator" .= simpleQueryStringOperator
2324− , "analyzer" .= simpleQueryStringAnalyzer
2325− , "flags" .= simpleQueryStringFlags
2326− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2327− , "locale" .= simpleQueryStringLocale ]
2329−instance FromJSON SimpleQueryStringQuery where
2330− parseJSON = withObject "SimpleQueryStringQuery" parse
2331− where parse o = SimpleQueryStringQuery <$> o .: "query"
2333− <*> o .:? "default_operator"
2334− <*> o .:? "analyzer"
2335− <*> (parseFlags <$> o .:? "flags")
2336− <*> o .:? "lowercase_expanded_terms"
2338− parseFlags (Just (x:xs)) = Just (x :| xs)
2339− parseFlags _ = Nothing
2341−instance ToJSON FieldOrFields where
2342− toJSON (FofField fieldName) =
2344− toJSON (FofFields fieldNames) =
2347−instance FromJSON FieldOrFields where
2348− parseJSON v = FofField <$> parseJSON v
2349− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2351−instance ToJSON SimpleQueryFlag where
2352− toJSON SimpleQueryAll = "ALL"
2353− toJSON SimpleQueryNone = "NONE"
2354− toJSON SimpleQueryAnd = "AND"
2355− toJSON SimpleQueryOr = "OR"
2356− toJSON SimpleQueryPrefix = "PREFIX"
2357− toJSON SimpleQueryPhrase = "PHRASE"
2358− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2359− toJSON SimpleQueryEscape = "ESCAPE"
2360− toJSON SimpleQueryWhitespace = "WHITESPACE"
2361− toJSON SimpleQueryFuzzy = "FUZZY"
2362− toJSON SimpleQueryNear = "NEAR"
2363− toJSON SimpleQuerySlop = "SLOP"
2365−instance FromJSON SimpleQueryFlag where
2366− parseJSON = withText "SimpleQueryFlag" parse
2367− where parse "ALL" = pure SimpleQueryAll
2368− parse "NONE" = pure SimpleQueryNone
2369− parse "AND" = pure SimpleQueryAnd
2370− parse "OR" = pure SimpleQueryOr
2371− parse "PREFIX" = pure SimpleQueryPrefix
2372− parse "PHRASE" = pure SimpleQueryPhrase
2373− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2374− parse "ESCAPE" = pure SimpleQueryEscape
2375− parse "WHITESPACE" = pure SimpleQueryWhitespace
2376− parse "FUZZY" = pure SimpleQueryFuzzy
2377− parse "NEAR" = pure SimpleQueryNear
2378− parse "SLOP" = pure SimpleQuerySlop
2379− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2381−instance ToJSON RegexpQuery where
2382− toJSON (RegexpQuery (FieldName rqQueryField)
2383− (Regexp regexpQueryQuery) rqQueryFlags
2385− object [ rqQueryField .= omitNulls base ]
2386− where base = [ "value" .= regexpQueryQuery
2387− , "flags" .= rqQueryFlags
2388− , "boost" .= rqQueryBoost ]
2390−instance FromJSON RegexpQuery where
2391− parseJSON = withObject "RegexpQuery" parse
2392− where parse = fieldTagged $ \fn o ->
2398−instance ToJSON QueryStringQuery where
2399− toJSON (QueryStringQuery qsQueryString
2400− qsDefaultField qsOperator
2401− qsAnalyzer qsAllowWildcard
2402− qsLowercaseExpanded qsEnablePositionIncrements
2403− qsFuzzyMaxExpansions qsFuzziness
2404− qsFuzzyPrefixLength qsPhraseSlop
2405− qsBoost qsAnalyzeWildcard
2406− qsGeneratePhraseQueries qsMinimumShouldMatch
2407− qsLenient qsLocale) =
2410− base = [ "query" .= qsQueryString
2411− , "default_field" .= qsDefaultField
2412− , "default_operator" .= qsOperator
2413− , "analyzer" .= qsAnalyzer
2414− , "allow_leading_wildcard" .= qsAllowWildcard
2415− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2416− , "enable_position_increments" .= qsEnablePositionIncrements
2417− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2418− , "fuzziness" .= qsFuzziness
2419− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2420− , "phrase_slop" .= qsPhraseSlop
2421− , "boost" .= qsBoost
2422− , "analyze_wildcard" .= qsAnalyzeWildcard
2423− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2424− , "minimum_should_match" .= qsMinimumShouldMatch
2425− , "lenient" .= qsLenient
2426− , "locale" .= qsLocale ]
2428−instance FromJSON QueryStringQuery where
2429− parseJSON = withObject "QueryStringQuery" parse
2430− where parse o = QueryStringQuery
2432− <*> o .:? "default_field"
2433− <*> o .:? "default_operator"
2434− <*> o .:? "analyzer"
2435− <*> o .:? "allow_leading_wildcard"
2436− <*> o .:? "lowercase_expanded_terms"
2437− <*> o .:? "enable_position_increments"
2438− <*> o .:? "fuzzy_max_expansions"
2439− <*> o .:? "fuzziness"
2440− <*> o .:? "fuzzy_prefix_length"
2441− <*> o .:? "phrase_slop"
2443− <*> o .:? "analyze_wildcard"
2444− <*> o .:? "auto_generate_phrase_queries"
2445− <*> o .:? "minimum_should_match"
2446− <*> o .:? "lenient"
2449−instance ToJSON RangeQuery where
2450− toJSON (RangeQuery (FieldName fieldName) range boost) =
2451− object [ fieldName .= object conjoined ]
2452− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2454−instance FromJSON RangeQuery where
2455− parseJSON = withObject "RangeQuery" parse
2456− where parse = fieldTagged $ \fn o ->
2458− <$> parseJSON (Object o)
2461−instance FromJSON RangeValue where
2462− parseJSON = withObject "RangeValue" parse
2463− where parse o = parseDate o
2465− parseDate o = do lt <- o .:? "lt"
2469− case (lt, lte, gt, gte) of
2470− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2471− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2472− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2473− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2474− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2475− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2476− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2477− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2478− (Nothing, Nothing, Nothing, Nothing) -> mzero
2479− parseDouble o = do lt <- o .:? "lt"
2483− case (lt, lte, gt, gte) of
2484− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2485− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2486− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2487− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2488− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2489− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2490− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2491− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2492− (Nothing, Nothing, Nothing, Nothing) -> mzero
2494−instance ToJSON PrefixQuery where
2495− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2496− object [ fieldName .= omitNulls base ]
2497− where base = [ "value" .= queryValue
2498− , "boost" .= boost ]
2500−instance FromJSON PrefixQuery where
2501− parseJSON = withObject "PrefixQuery" parse
2502− where parse = fieldTagged $ \fn o ->
2507−instance ToJSON NestedQuery where
2508− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2509− object [ "path" .= nqPath
2510− , "score_mode" .= nqScoreType
2511− , "query" .= nqQuery ]
2513−instance FromJSON NestedQuery where
2514− parseJSON = withObject "NestedQuery" parse
2515− where parse o = NestedQuery
2517− <*> o .: "score_mode"
2520−instance ToJSON MoreLikeThisFieldQuery where
2521− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2522− percent mtf mqt stopwords mindf maxdf
2523− minwl maxwl boostTerms boost analyzer) =
2524− object [ fieldName .= omitNulls base ]
2525− where base = [ "like_text" .= text
2526− , "percent_terms_to_match" .= percent
2527− , "min_term_freq" .= mtf
2528− , "max_query_terms" .= mqt
2529− , "stop_words" .= stopwords
2530− , "min_doc_freq" .= mindf
2531− , "max_doc_freq" .= maxdf
2532− , "min_word_length" .= minwl
2533− , "max_word_length" .= maxwl
2534− , "boost_terms" .= boostTerms
2536− , "analyzer" .= analyzer ]
2538−instance FromJSON MoreLikeThisFieldQuery where
2539− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2540− where parse = fieldTagged $ \fn o ->
2541− MoreLikeThisFieldQuery
2542− <$> o .: "like_text"
2544− <*> o .:? "percent_terms_to_match"
2545− <*> o .:? "min_term_freq"
2546− <*> o .:? "max_query_terms"
2547− -- <*> (optionalNE =<< o .:? "stop_words")
2548− <*> o .:? "stop_words"
2549− <*> o .:? "min_doc_freq"
2550− <*> o .:? "max_doc_freq"
2551− <*> o .:? "min_word_length"
2552− <*> o .:? "max_word_length"
2553− <*> o .:? "boost_terms"
2555− <*> o .:? "analyzer"
2556− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2558−instance ToJSON MoreLikeThisQuery where
2559− toJSON (MoreLikeThisQuery text fields percent
2560− mtf mqt stopwords mindf maxdf
2561− minwl maxwl boostTerms boost analyzer) =
2563− where base = [ "like_text" .= text
2564− , "fields" .= fields
2565− , "percent_terms_to_match" .= percent
2566− , "min_term_freq" .= mtf
2567− , "max_query_terms" .= mqt
2568− , "stop_words" .= stopwords
2569− , "min_doc_freq" .= mindf
2570− , "max_doc_freq" .= maxdf
2571− , "min_word_length" .= minwl
2572− , "max_word_length" .= maxwl
2573− , "boost_terms" .= boostTerms
2575− , "analyzer" .= analyzer ]
2577−instance FromJSON MoreLikeThisQuery where
2578− parseJSON = withObject "MoreLikeThisQuery" parse
2579− where parse o = MoreLikeThisQuery
2580− <$> o .: "like_text"
2581− -- <*> (optionalNE =<< o .:? "fields")
2583− <*> o .:? "percent_terms_to_match"
2584− <*> o .:? "min_term_freq"
2585− <*> o .:? "max_query_terms"
2586− -- <*> (optionalNE =<< o .:? "stop_words")
2587− <*> o .:? "stop_words"
2588− <*> o .:? "min_doc_freq"
2589− <*> o .:? "max_doc_freq"
2590− <*> o .:? "min_word_length"
2591− <*> o .:? "max_word_length"
2592− <*> o .:? "boost_terms"
2594− <*> o .:? "analyzer"
2595− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2597−instance ToJSON IndicesQuery where
2598− toJSON (IndicesQuery indices query noMatch) =
2599− omitNulls [ "indices" .= indices
2600− , "no_match_query" .= noMatch
2601− , "query" .= query ]
2603−instance FromJSON IndicesQuery where
2604− parseJSON = withObject "IndicesQuery" parse
2605− where parse o = IndicesQuery
2606− <$> o .:? "indices" .!= []
2608− <*> o .:? "no_match_query"
2610−instance ToJSON HasParentQuery where
2611− toJSON (HasParentQuery queryType query scoreType) =
2612− omitNulls [ "parent_type" .= queryType
2613− , "score_type" .= scoreType
2614− , "query" .= query ]
2616−instance FromJSON HasParentQuery where
2617− parseJSON = withObject "HasParentQuery" parse
2618− where parse o = HasParentQuery
2619− <$> o .: "parent_type"
2621− <*> o .:? "score_type"
2623−instance ToJSON HasChildQuery where
2624− toJSON (HasChildQuery queryType query scoreType) =
2625− omitNulls [ "query" .= query
2626− , "score_type" .= scoreType
2627− , "type" .= queryType ]
2629−instance FromJSON HasChildQuery where
2630− parseJSON = withObject "HasChildQuery" parse
2631− where parse o = HasChildQuery
2634− <*> o .:? "score_type"
2636−instance ToJSON FuzzyQuery where
2637− toJSON (FuzzyQuery (FieldName fieldName) queryText
2638− prefixLength maxEx fuzziness boost) =
2639− object [ fieldName .= omitNulls base ]
2640− where base = [ "value" .= queryText
2641− , "fuzziness" .= fuzziness
2642− , "prefix_length" .= prefixLength
2644− , "max_expansions" .= maxEx ]
2646−instance FromJSON FuzzyQuery where
2647− parseJSON = withObject "FuzzyQuery" parse
2648− where parse = fieldTagged $ \fn o ->
2651− <*> o .: "prefix_length"
2652− <*> o .: "max_expansions"
2653− <*> o .: "fuzziness"
2656−instance ToJSON FuzzyLikeFieldQuery where
2657− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2658− fieldText maxTerms ignoreFreq fuzziness prefixLength
2660− object [ fieldName .=
2661− omitNulls [ "like_text" .= fieldText
2662− , "max_query_terms" .= maxTerms
2663− , "ignore_tf" .= ignoreFreq
2664− , "fuzziness" .= fuzziness
2665− , "prefix_length" .= prefixLength
2666− , "analyzer" .= analyzer
2667− , "boost" .= boost ]]
2669−instance FromJSON FuzzyLikeFieldQuery where
2670− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2671− where parse = fieldTagged $ \fn o ->
2672− FuzzyLikeFieldQuery fn
2673− <$> o .: "like_text"
2674− <*> o .: "max_query_terms"
2675− <*> o .: "ignore_tf"
2676− <*> o .: "fuzziness"
2677− <*> o .: "prefix_length"
2679− <*> o .:? "analyzer"
2681−instance ToJSON FuzzyLikeThisQuery where
2682− toJSON (FuzzyLikeThisQuery fields text maxTerms
2683− ignoreFreq fuzziness prefixLength boost analyzer) =
2685− where base = [ "fields" .= fields
2686− , "like_text" .= text
2687− , "max_query_terms" .= maxTerms
2688− , "ignore_tf" .= ignoreFreq
2689− , "fuzziness" .= fuzziness
2690− , "prefix_length" .= prefixLength
2691− , "analyzer" .= analyzer
2692− , "boost" .= boost ]
2694−instance FromJSON FuzzyLikeThisQuery where
2695− parseJSON = withObject "FuzzyLikeThisQuery" parse
2696− where parse o = FuzzyLikeThisQuery
2697− <$> o .:? "fields" .!= []
2698− <*> o .: "like_text"
2699− <*> o .: "max_query_terms"
2700− <*> o .: "ignore_tf"
2701− <*> o .: "fuzziness"
2702− <*> o .: "prefix_length"
2704− <*> o .:? "analyzer"
2706−instance ToJSON FilteredQuery where
2707− toJSON (FilteredQuery query fFilter) =
2708− object [ "query" .= query
2709− , "filter" .= fFilter ]
2711−instance FromJSON FilteredQuery where
2712− parseJSON = withObject "FilteredQuery" parse
2713− where parse o = FilteredQuery
2717−instance ToJSON DisMaxQuery where
2718− toJSON (DisMaxQuery queries tiebreaker boost) =
2720− where base = [ "queries" .= queries
2722− , "tie_breaker" .= tiebreaker ]
2724−instance FromJSON DisMaxQuery where
2725− parseJSON = withObject "DisMaxQuery" parse
2726− where parse o = DisMaxQuery
2727− <$> o .:? "queries" .!= []
2728− <*> o .: "tie_breaker"
2731−instance ToJSON CommonTermsQuery where
2732− toJSON (CommonTermsQuery (FieldName fieldName)
2733− (QueryString query) cf lfo hfo msm
2734− boost analyzer disableCoord) =
2735− object [fieldName .= omitNulls base ]
2736− where base = [ "query" .= query
2737− , "cutoff_frequency" .= cf
2738− , "low_freq_operator" .= lfo
2739− , "minimum_should_match" .= msm
2741− , "analyzer" .= analyzer
2742− , "disable_coord" .= disableCoord
2743− , "high_freq_operator" .= hfo ]
2745−instance FromJSON CommonTermsQuery where
2746− parseJSON = withObject "CommonTermsQuery" parse
2747− where parse = fieldTagged $ \fn o ->
2748− CommonTermsQuery fn
2750− <*> o .: "cutoff_frequency"
2751− <*> o .: "low_freq_operator"
2752− <*> o .: "high_freq_operator"
2753− <*> o .:? "minimum_should_match"
2755− <*> o .:? "analyzer"
2756− <*> o .:? "disable_coord"
2758−instance ToJSON CommonMinimumMatch where
2759− toJSON (CommonMinimumMatch mm) = toJSON mm
2760− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2761− object [ "low_freq" .= lowF
2762− , "high_freq" .= highF ]
2764−instance FromJSON CommonMinimumMatch where
2765− parseJSON v = parseMinimum v
2766− <|> parseMinimumHighLow v
2767− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2768− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2769− MinimumMatchHighLow
2770− <$> o .: "low_freq"
2771− <*> o .: "high_freq")
2774−instance ToJSON BoostingQuery where
2775− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2776− object [ "positive" .= bqPositiveQuery
2777− , "negative" .= bqNegativeQuery
2778− , "negative_boost" .= bqNegativeBoost ]
2780−instance FromJSON BoostingQuery where
2781− parseJSON = withObject "BoostingQuery" parse
2782− where parse o = BoostingQuery
2783− <$> o .: "positive"
2784− <*> o .: "negative"
2785− <*> o .: "negative_boost"
2787−instance ToJSON BoolQuery where
2788− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2790− where base = [ "must" .= mustM
2791− , "must_not" .= notM
2792− , "should" .= shouldM
2793− , "minimum_should_match" .= bqMin
2795− , "disable_coord" .= disableCoord ]
2797−instance FromJSON BoolQuery where
2798− parseJSON = withObject "BoolQuery" parse
2799− where parse o = BoolQuery
2800− <$> o .:? "must" .!= []
2801− <*> o .:? "must_not" .!= []
2802− <*> o .:? "should" .!= []
2803− <*> o .:? "minimum_should_match"
2805− <*> o .:? "disable_coord"
2807−instance ToJSON MatchQuery where
2808− toJSON (MatchQuery (FieldName fieldName)
2809− (QueryString mqQueryString) booleanOperator
2810− zeroTermsQuery cutoffFrequency matchQueryType
2811− analyzer maxExpansions lenient boost) =
2812− object [ fieldName .= omitNulls base ]
2813− where base = [ "query" .= mqQueryString
2814− , "operator" .= booleanOperator
2815− , "zero_terms_query" .= zeroTermsQuery
2816− , "cutoff_frequency" .= cutoffFrequency
2817− , "type" .= matchQueryType
2818− , "analyzer" .= analyzer
2819− , "max_expansions" .= maxExpansions
2820− , "lenient" .= lenient
2821− , "boost" .= boost ]
2823−instance FromJSON MatchQuery where
2824− parseJSON = withObject "MatchQuery" parse
2825− where parse = fieldTagged $ \fn o ->
2828− <*> o .: "operator"
2829− <*> o .: "zero_terms_query"
2830− <*> o .:? "cutoff_frequency"
2832− <*> o .:? "analyzer"
2833− <*> o .:? "max_expansions"
2834− <*> o .:? "lenient"
2837−instance ToJSON MultiMatchQuery where
2838− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2839− ztQ tb mmqt cf analyzer maxEx lenient) =
2840− object ["multi_match" .= omitNulls base]
2841− where base = [ "fields" .= fmap toJSON fields
2843− , "operator" .= boolOp
2844− , "zero_terms_query" .= ztQ
2845− , "tiebreaker" .= tb
2847− , "cutoff_frequency" .= cf
2848− , "analyzer" .= analyzer
2849− , "max_expansions" .= maxEx
2850− , "lenient" .= lenient ]
2852−instance FromJSON MultiMatchQuery where
2853− parseJSON = withObject "MultiMatchQuery" parse
2854− where parse raw = do o <- raw .: "multi_match"
2856− <$> o .:? "fields" .!= []
2858− <*> o .: "operator"
2859− <*> o .: "zero_terms_query"
2860− <*> o .:? "tiebreaker"
2862− <*> o .:? "cutoff_frequency"
2863− <*> o .:? "analyzer"
2864− <*> o .:? "max_expansions"
2865− <*> o .:? "lenient"
2867−instance ToJSON MultiMatchQueryType where
2868− toJSON MultiMatchBestFields = "best_fields"
2869− toJSON MultiMatchMostFields = "most_fields"
2870− toJSON MultiMatchCrossFields = "cross_fields"
2871− toJSON MultiMatchPhrase = "phrase"
2872− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2874−instance FromJSON MultiMatchQueryType where
2875− parseJSON = withText "MultiMatchPhrasePrefix" parse
2876− where parse "best_fields" = pure MultiMatchBestFields
2877− parse "most_fields" = pure MultiMatchMostFields
2878− parse "cross_fields" = pure MultiMatchCrossFields
2879− parse "phrase" = pure MultiMatchPhrase
2880− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2881− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2883−instance ToJSON BooleanOperator where
2884− toJSON And = String "and"
2885− toJSON Or = String "or"
2887−instance FromJSON BooleanOperator where
2888− parseJSON = withText "BooleanOperator" parse
2889− where parse "and" = pure And
2890− parse "or" = pure Or
2891− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2893−instance ToJSON ZeroTermsQuery where
2894− toJSON ZeroTermsNone = String "none"
2895− toJSON ZeroTermsAll = String "all"
2897−instance FromJSON ZeroTermsQuery where
2898− parseJSON = withText "ZeroTermsQuery" parse
2899− where parse "none" = pure ZeroTermsNone
2900− parse "all" = pure ZeroTermsAll
2901− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2903−instance ToJSON MatchQueryType where
2904− toJSON MatchPhrase = "phrase"
2905− toJSON MatchPhrasePrefix = "phrase_prefix"
2907−instance FromJSON MatchQueryType where
2908− parseJSON = withText "MatchQueryType" parse
2909− where parse "phrase" = pure MatchPhrase
2910− parse "phrase_prefix" = pure MatchPhrasePrefix
2911− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2913−instance FromJSON Status where
2914− parseJSON (Object v) = Status <$>
2920− parseJSON _ = empty
2923−instance ToJSON IndexSettings where
2924− toJSON (IndexSettings s r) = object ["settings" .=
2926− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2930−instance FromJSON IndexSettings where
2931− parseJSON = withObject "IndexSettings" parse
2932− where parse o = do s <- o .: "settings"
2934− IndexSettings <$> i .: "number_of_shards"
2935− <*> i .: "number_of_replicas"
2937−instance ToJSON UpdatableIndexSetting where
2938− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2939− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2940− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2941− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2942− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2943− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2944− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2945− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2946− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2947− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2948− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2949− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2950− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2951− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2952− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2953− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2954− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2955− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2956− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2957− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2958− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2959− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2960− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2961− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2962− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2963− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2964− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2965− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2967−instance FromJSON UpdatableIndexSetting where
2968− parseJSON = withObject "UpdatableIndexSetting" parse
2969− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2970− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2971− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2972− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2973− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2974− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2975− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2976− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2977− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2978− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2979− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2980− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2981− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2982− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2983− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2984− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2985− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2986− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2987− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2988− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2989− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2990− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2991− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2992− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2993− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2994− <|> blocksRead `taggedAt` ["blocks", "read"]
2995− <|> blocksWrite `taggedAt` ["blocks", "write"]
2996− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2997− where taggedAt f ks = taggedAt' f (Object o) ks
2998− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
2999− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3000− taggedAt' f v' ks) v
3001− numberOfReplicas = pure . NumberOfReplicas
3002− autoExpandReplicas = pure . AutoExpandReplicas
3003− refreshInterval = pure . RefreshInterval . ndtJSON
3004− indexConcurrency = pure . IndexConcurrency
3005− failOnMergeFailure = pure . FailOnMergeFailure
3006− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3007− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3008− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3009− translogDisableFlush = pure . TranslogDisableFlush
3010− cacheFilterMaxSize = pure . CacheFilterMaxSize
3011− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3012− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3013− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3014− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3015− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3016− routingAllocationEnable = pure . RoutingAllocationEnable
3017− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3018− recoveryInitialShards = pure . RecoveryInitialShards
3019− gcDeletes = pure . GCDeletes . ndtJSON
3020− ttlDisablePurge = pure . TTLDisablePurge
3021− translogFSType = pure . TranslogFSType
3022− compoundFormat = pure . IndexCompoundFormat
3023− compoundOnFlush = pure . IndexCompoundOnFlush
3024− warmerEnabled = pure . WarmerEnabled
3025− blocksReadOnly = pure . BlocksReadOnly
3026− blocksRead = pure . BlocksRead
3027− blocksWrite = pure . BlocksWrite
3028− blocksMetaData = pure . BlocksMetaData
3030−instance FromJSON IndexSettingsSummary where
3031− parseJSON = withObject "IndexSettingsSummary" parse
3032− where parse o = case HM.toList o of
3033− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3035− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3036− _ -> fail "Expected single-key object with index name"
3037− redundant (NumberOfReplicas _) = True
3038− redundant _ = False
3040−-- | For some reason in several settings APIs, all leaf values get returned
3041−-- as strings. This function attepmts to recover from this for all
3042−-- non-recursive JSON types. If nothing can be done, the value is left alone.
3043−unStringlyTypeJSON :: Value -> Value
3044−unStringlyTypeJSON (String "true") = Bool True
3045−unStringlyTypeJSON (String "false") = Bool False
3046−unStringlyTypeJSON (String "null") = Null
3047−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3050−unStringlyTypeJSON v = v
3053−parseSettings :: Object -> Parser [UpdatableIndexSetting]
3054−parseSettings o = do
3056− -- slice the index object into singleton hashmaps and try to parse each
3057− parses <- forM (HM.toList o') $ \(k, v) -> do
3058− -- blocks are now nested into the "index" key, which is not how they're serialized
3059− let atRoot = Object (HM.singleton k v)
3060− let atIndex = Object (HM.singleton "index" atRoot)
3061− optional (parseJSON atRoot <|> parseJSON atIndex)
3062− return (catMaybes parses)
3064−oPath :: ToJSON a => NonEmpty Text -> a -> Value
3065−oPath (k :| []) v = object [k .= v]
3066−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3068−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3069−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3070− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3072−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3073−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3074− where parse o = case HM.toList o of
3075− [] -> fail "Expected non-empty list of NodeAttrFilters"
3076− x:xs -> DT.mapM (uncurry parse') (x :| xs)
3077− parse' n = withText "Text" $ \t ->
3078− case T.splitOn "," t of
3079− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3080− [] -> fail "Expected non-empty list of filter values"
3082−instance ToJSON ReplicaBounds where
3083− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3084− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3085− toJSON ReplicasUnbounded = Bool False
3087−instance FromJSON ReplicaBounds where
3088− parseJSON v = withText "ReplicaBounds" parseText v
3089− <|> withBool "ReplicaBounds" parseBool v
3090− where parseText t = case T.splitOn "-" t of
3091− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3092− [a, b] -> ReplicasBounded <$> parseReadText a
3093− <*> parseReadText b
3094− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3095− parseBool False = pure ReplicasUnbounded
3096− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3098−instance ToJSON AllocationPolicy where
3099− toJSON AllocAll = String "all"
3100− toJSON AllocPrimaries = String "primaries"
3101− toJSON AllocNewPrimaries = String "new_primaries"
3102− toJSON AllocNone = String "none"
3104−instance FromJSON AllocationPolicy where
3105− parseJSON = withText "AllocationPolicy" parse
3106− where parse "all" = pure AllocAll
3107− parse "primaries" = pure AllocPrimaries
3108− parse "new_primaries" = pure AllocNewPrimaries
3109− parse "none" = pure AllocNone
3110− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3112−instance ToJSON InitialShardCount where
3113− toJSON QuorumShards = String "quorum"
3114− toJSON QuorumMinus1Shards = String "quorum-1"
3115− toJSON FullShards = String "full"
3116− toJSON FullMinus1Shards = String "full-1"
3117− toJSON (ExplicitShards x) = toJSON x
3119−instance FromJSON InitialShardCount where
3120− parseJSON v = withText "InitialShardCount" parseText v
3121− <|> ExplicitShards <$> parseJSON v
3122− where parseText "quorum" = pure QuorumShards
3123− parseText "quorum-1" = pure QuorumMinus1Shards
3124− parseText "full" = pure FullShards
3125− parseText "full-1" = pure FullMinus1Shards
3126− parseText _ = mzero
3128−instance ToJSON FSType where
3129− toJSON FSSimple = "simple"
3130− toJSON FSBuffered = "buffered"
3132−instance FromJSON FSType where
3133− parseJSON = withText "FSType" parse
3134− where parse "simple" = pure FSSimple
3135− parse "buffered" = pure FSBuffered
3136− parse t = fail ("Invalid FSType: " <> show t)
3138−instance ToJSON CompoundFormat where
3139− toJSON (CompoundFileFormat x) = Bool x
3140− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3142−instance FromJSON CompoundFormat where
3143− parseJSON v = CompoundFileFormat <$> parseJSON v
3144− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3146−instance ToJSON NominalDiffTimeJSON where
3147− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3149−instance FromJSON NominalDiffTimeJSON where
3150− parseJSON = withText "NominalDiffTime" parse
3151− where parse t = case T.takeEnd 1 t of
3152− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3153− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3155−instance ToJSON IndexTemplate where
3156− toJSON (IndexTemplate p s m) = merge
3157− (object [ "template" .= p
3158− , "mappings" .= foldl' merge (object []) m
3162− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3164− merge _ _ = undefined
3166−instance (FromJSON a) => FromJSON (EsResult a) where
3167− parseJSON jsonVal@(Object v) = do
3168− found <- v .:? "found" .!= False
3170− then parseJSON jsonVal
3171− else return Nothing
3172− EsResult <$> v .: "_index" <*>
3176− parseJSON _ = empty
3178−instance (FromJSON a) => FromJSON (EsResultFound a) where
3179− parseJSON (Object v) = EsResultFound <$>
3180− v .: "_version" <*>
3182− parseJSON _ = empty
3184−instance FromJSON EsError where
3185− parseJSON (Object v) = EsError <$>
3188− parseJSON _ = empty
3190−instance FromJSON IndexAliasesSummary where
3191− parseJSON = withObject "IndexAliasesSummary" parse
3192− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3193− go ixn = withObject "index aliases" $ \ia -> do
3194− aliases <- ia .:? "aliases" .!= mempty
3195− forM (HM.toList aliases) $ \(aName, v) -> do
3196− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3197− IndexAliasSummary indexAlias <$> parseJSON v
3200−instance ToJSON IndexAliasAction where
3201− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3202− where Object iaObj = toJSON ia
3203− Object optsObj = toJSON opts
3204− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3205− where Object iaObj = toJSON ia
3207−instance ToJSON IndexAlias where
3208− toJSON IndexAlias {..} = object ["index" .= srcIndex
3209− , "alias" .= indexAlias
3212−instance ToJSON IndexAliasCreate where
3213− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3214− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3215− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3217−instance ToJSON AliasRouting where
3218− toJSON (AllAliasRouting v) = object ["routing" .= v]
3219− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3220− where prs = [("search_routing" .=) <$> srch
3221− ,("index_routing" .=) <$> idx]
3223−instance FromJSON AliasRouting where
3224− parseJSON = withObject "AliasRouting" parse
3225− where parse o = parseAll o <|> parseGranular o
3226− parseAll o = AllAliasRouting <$> o .: "routing"
3227− parseGranular o = do
3228− sr <- o .:? "search_routing"
3229− ir <- o .:? "index_routing"
3230− if isNothing sr && isNothing ir
3231− then fail "Both search_routing and index_routing can't be blank"
3232− else return (GranularAliasRouting sr ir)
3234−instance FromJSON IndexAliasCreate where
3235− parseJSON v = withObject "IndexAliasCreate" parse v
3236− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3239−instance ToJSON SearchAliasRouting where
3240− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3242−instance FromJSON SearchAliasRouting where
3243− parseJSON = withText "SearchAliasRouting" parse
3244− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3246−instance ToJSON Search where
3247− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3248− omitNulls [ "query" .= query
3249− , "filter" .= sFilter
3251− , "aggregations" .= searchAggs
3252− , "highlight" .= highlight
3255− , "track_scores" .= sTrackSortScores
3256− , "fields" .= sFields
3257− , "_source" .= sSource]
3260−instance ToJSON Source where
3261− toJSON NoSource = toJSON False
3262− toJSON (SourcePatterns patterns) = toJSON patterns
3263− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3265−instance ToJSON PatternOrPatterns where
3266− toJSON (PopPattern pattern) = toJSON pattern
3267− toJSON (PopPatterns patterns) = toJSON patterns
3269−instance ToJSON Include where
3270− toJSON (Include patterns) = toJSON patterns
3272−instance ToJSON Exclude where
3273− toJSON (Exclude patterns) = toJSON patterns
3275−instance ToJSON Pattern where
3276− toJSON (Pattern pattern) = toJSON pattern
3279−instance ToJSON FieldHighlight where
3280− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3281− object [ fName .= fSettings ]
3282− toJSON (FieldHighlight (FieldName fName) Nothing) =
3283− object [ fName .= emptyObject ]
3285−instance ToJSON Highlights where
3286− toJSON (Highlights global fields) =
3287− omitNulls (("fields" .= fields)
3288− : highlightSettingsPairs global)
3290−instance ToJSON HighlightSettings where
3291− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3293−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3294−highlightSettingsPairs Nothing = []
3295−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3296−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3297−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3300−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3301−plainHighPairs Nothing = []
3302−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3303− [ "type" .= String "plain"]
3304− ++ commonHighlightPairs plCom
3305− ++ nonPostingsToPairs plNonPost
3307−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3308−postHighPairs Nothing = []
3309−postHighPairs (Just (PostingsHighlight pCom)) =
3310− ("type" .= String "postings")
3311− : commonHighlightPairs pCom
3313−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3314−fastVectorHighPairs Nothing = []
3315−fastVectorHighPairs (Just
3316− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3317− fvBoundMaxScan fvFragOff fvMatchedFields
3319− [ "type" .= String "fvh"
3320− , "boundary_chars" .= fvBoundChars
3321− , "boundary_max_scan" .= fvBoundMaxScan
3322− , "fragment_offset" .= fvFragOff
3323− , "matched_fields" .= fvMatchedFields
3324− , "phraseLimit" .= fvPhraseLim]
3325− ++ commonHighlightPairs fvCom
3326− ++ nonPostingsToPairs fvNonPostSettings
3328−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3329−deleteSeveral ks hm = foldr HM.delete hm ks
3331−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3332−commonHighlightPairs Nothing = []
3333−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3334− chNoMatchSize chHighlightQuery
3335− chRequireFieldMatch)) =
3336− [ "order" .= chScore
3337− , "force_source" .= chForceSource
3338− , "encoder" .= chEncoder
3339− , "no_match_size" .= chNoMatchSize
3340− , "highlight_query" .= chHighlightQuery
3341− , "require_fieldMatch" .= chRequireFieldMatch]
3342− ++ highlightTagToPairs chTag
3345−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3346−nonPostingsToPairs Nothing = []
3347−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3348− [ "fragment_size" .= npFragSize
3349− , "number_of_fragments" .= npNumOfFrags]
3351−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3352−parseNEJSON [] = fail "Expected non-empty list"
3353−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3356−instance ToJSON HighlightEncoder where
3357− toJSON DefaultEncoder = String "default"
3358− toJSON HTMLEncoder = String "html"
3360−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3361−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3362−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3363− , "post_tags" .= post]
3364−highlightTagToPairs Nothing = []
3366−instance ToJSON SortSpec where
3367− toJSON (DefaultSortSpec
3368− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3369− dsSortMode dsMissingSort dsNestedFilter)) =
3370− object [dsSortFieldName .= omitNulls base] where
3371− base = [ "order" .= dsSortOrder
3372− , "ignore_unmapped" .= dsIgnoreUnmapped
3373− , "mode" .= dsSortMode
3374− , "missing" .= dsMissingSort
3375− , "nested_filter" .= dsNestedFilter ]
3377− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3378− object [ "unit" .= units
3379− , field .= gdsLatLon
3380− , "order" .= gdsSortOrder ]
3383−instance ToJSON SortOrder where
3384− toJSON Ascending = String "asc"
3385− toJSON Descending = String "desc"
3388−instance ToJSON SortMode where
3389− toJSON SortMin = String "min"
3390− toJSON SortMax = String "max"
3391− toJSON SortSum = String "sum"
3392− toJSON SortAvg = String "avg"
3395−instance ToJSON Missing where
3396− toJSON LastMissing = String "_last"
3397− toJSON FirstMissing = String "_first"
3398− toJSON (CustomMissing txt) = String txt
3401−instance ToJSON ScoreType where
3402− toJSON ScoreTypeMax = "max"
3403− toJSON ScoreTypeAvg = "avg"
3404− toJSON ScoreTypeSum = "sum"
3405− toJSON ScoreTypeNone = "none"
3407−instance FromJSON ScoreType where
3408− parseJSON = withText "ScoreType" parse
3409− where parse "max" = pure ScoreTypeMax
3410− parse "avg" = pure ScoreTypeAvg
3411− parse "sum" = pure ScoreTypeSum
3412− parse "none" = pure ScoreTypeNone
3413− parse t = fail ("Unexpected ScoreType: " <> show t)
3415−instance ToJSON Distance where
3416− toJSON (Distance dCoefficient dUnit) =
3417− String boltedTogether where
3418− coefText = showText dCoefficient
3419− (String unitText) = toJSON dUnit
3420− boltedTogether = mappend coefText unitText
3422−instance FromJSON Distance where
3423− parseJSON = withText "Distance" parse
3424− where parse t = Distance <$> parseCoeff nT
3425− <*> parseJSON (String unitT)
3426− where (nT, unitT) = T.span validForNumber t
3427− -- may be a better way to do this
3428− validForNumber '-' = True
3429− validForNumber '.' = True
3430− validForNumber 'e' = True
3431− validForNumber c = isNumber c
3432− parseCoeff "" = fail "Empty string cannot be parsed as number"
3433− parseCoeff s = return (read (T.unpack s))
3435−instance ToJSON DistanceUnit where
3436− toJSON Miles = String "mi"
3437− toJSON Yards = String "yd"
3438− toJSON Feet = String "ft"
3439− toJSON Inches = String "in"
3440− toJSON Kilometers = String "km"
3441− toJSON Meters = String "m"
3442− toJSON Centimeters = String "cm"
3443− toJSON Millimeters = String "mm"
3444− toJSON NauticalMiles = String "nmi"
3447−instance FromJSON DistanceUnit where
3448− parseJSON = withText "DistanceUnit" parse
3449− where parse "mi" = pure Miles
3450− parse "yd" = pure Yards
3451− parse "ft" = pure Feet
3452− parse "in" = pure Inches
3453− parse "km" = pure Kilometers
3454− parse "m" = pure Meters
3455− parse "cm" = pure Centimeters
3456− parse "mm" = pure Millimeters
3457− parse "nmi" = pure NauticalMiles
3458− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3460−instance ToJSON DistanceType where
3461− toJSON Arc = String "arc"
3462− toJSON SloppyArc = String "sloppy_arc"
3463− toJSON Plane = String "plane"
3465−instance FromJSON DistanceType where
3466− parseJSON = withText "DistanceType" parse
3467− where parse "arc" = pure Arc
3468− parse "sloppy_arc" = pure SloppyArc
3469− parse "plane" = pure Plane
3470− parse t = fail ("Unrecognized DistanceType: " <> show t)
3473−instance ToJSON OptimizeBbox where
3474− toJSON NoOptimizeBbox = String "none"
3475− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3477−instance FromJSON OptimizeBbox where
3478− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3479− <|> parseOptimize v
3480− where parseNoOptimize "none" = pure NoOptimizeBbox
3481− parseNoOptimize _ = mzero
3482− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3484−instance ToJSON GeoBoundingBoxConstraint where
3485− toJSON (GeoBoundingBoxConstraint
3486− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3487− object [gbbcGeoBBField .= gbbcConstraintBox
3488− , "_cache" .= cache
3491−instance FromJSON GeoBoundingBoxConstraint where
3492− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3493− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3494− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3496− <*> o .:? "_cache" .!= defaultCache
3498− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3500−instance ToJSON GeoFilterType where
3501− toJSON GeoFilterMemory = String "memory"
3502− toJSON GeoFilterIndexed = String "indexed"
3504−instance FromJSON GeoFilterType where
3505− parseJSON = withText "GeoFilterType" parse
3506− where parse "memory" = pure GeoFilterMemory
3507− parse "indexed" = pure GeoFilterIndexed
3508− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3510−instance ToJSON GeoBoundingBox where
3511− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3512− object ["top_left" .= gbbTopLeft
3513− , "bottom_right" .= gbbBottomRight]
3515−instance FromJSON GeoBoundingBox where
3516− parseJSON = withObject "GeoBoundingBox" parse
3517− where parse o = GeoBoundingBox
3518− <$> o .: "top_left"
3519− <*> o .: "bottom_right"
3521−instance ToJSON LatLon where
3522− toJSON (LatLon lLat lLon) =
3523− object ["lat" .= lLat
3526−instance FromJSON LatLon where
3527− parseJSON = withObject "LatLon" parse
3528− where parse o = LatLon <$> o .: "lat"
3531−-- index for smaller ranges, fielddata for longer ranges
3532−instance ToJSON RangeExecution where
3533− toJSON RangeExecutionIndex = "index"
3534− toJSON RangeExecutionFielddata = "fielddata"
3537−instance FromJSON RangeExecution where
3538− parseJSON = withText "RangeExecution" parse
3539− where parse "index" = pure RangeExecutionIndex
3540− parse "fielddata" = pure RangeExecutionFielddata
3541− parse t = error ("Unrecognized RangeExecution " <> show t)
3543−instance ToJSON RegexpFlags where
3544− toJSON AllRegexpFlags = String "ALL"
3545− toJSON NoRegexpFlags = String "NONE"
3546− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3547− where flagStrs = map flagStr . nub $ h:fs
3548− flagStr AnyString = "ANYSTRING"
3549− flagStr Automaton = "AUTOMATON"
3550− flagStr Complement = "COMPLEMENT"
3551− flagStr Empty = "EMPTY"
3552− flagStr Intersection = "INTERSECTION"
3553− flagStr Interval = "INTERVAL"
3555−instance FromJSON RegexpFlags where
3556− parseJSON = withText "RegexpFlags" parse
3557− where parse "ALL" = pure AllRegexpFlags
3558− parse "NONE" = pure NoRegexpFlags
3559− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3561−instance FromJSON RegexpFlag where
3562− parseJSON = withText "RegexpFlag" parse
3563− where parse "ANYSTRING" = pure AnyString
3564− parse "AUTOMATON" = pure Automaton
3565− parse "COMPLEMENT" = pure Complement
3566− parse "EMPTY" = pure Empty
3567− parse "INTERSECTION" = pure Intersection
3568− parse "INTERVAL" = pure Interval
3569− parse f = fail ("Unknown RegexpFlag: " <> show f)
3571−instance ToJSON Term where
3572− toJSON (Term field value) = object ["term" .= object
3575−instance FromJSON Term where
3576− parseJSON = withObject "Term" parse
3577− where parse o = do termObj <- o .: "term"
3578− case HM.toList termObj of
3579− [(fn, v)] -> Term fn <$> parseJSON v
3580− _ -> fail "Expected object with 1 field-named key"
3582−instance ToJSON BoolMatch where
3583− toJSON (MustMatch term cache) = object ["must" .= term,
3585− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3587− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3590−instance FromJSON BoolMatch where
3591− parseJSON = withObject "BoolMatch" parse
3592− where parse o = mustMatch `taggedWith` "must"
3593− <|> mustNotMatch `taggedWith` "must_not"
3594− <|> shouldMatch `taggedWith` "should"
3595− where taggedWith parser k = parser =<< o .: k
3596− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3597− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3598− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3600instance (FromJSON a) => FromJSON (SearchResult a) where
529instance (FromJSON a) => FromJSON (SearchResult a) where
3601 parseJSON (Object v) = SearchResult <$>
530 parseJSON (Object v) = SearchResult <$>
@@ -3604,337 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3604 v .: "_shards" <*>
533 v .: "_shards" <*>
3605 v .: "hits" <*>
534 v .: "hits" <*>
3606 v .:? "aggregations" <*>
535 v .:? "aggregations" <*>
3607− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
3608− parseJSON _ = empty
537+ v .:? "suggest"
3610−instance (FromJSON a) => FromJSON (SearchHits a) where
3611− parseJSON (Object v) = SearchHits <$>
3613− v .: "max_score" <*>
3615 parseJSON _ = empty
538 parseJSON _ = empty
3617−instance (FromJSON a) => FromJSON (Hit a) where
540+newtype ScrollId =
3618− parseJSON (Object v) = Hit <$>
541+ ScrollId Text
3619− v .: "_index" <*>
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
3623− v .:? "_source" <*>
3625− parseJSON _ = empty
3627−instance FromJSON ShardResult where
3628− parseJSON (Object v) = ShardResult <$>
3630− v .: "successful" <*>
3632− parseJSON _ = empty
3635−instance FromJSON DocVersion where
3638− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3640−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3641−instance FromJSON ReplicaCount where
3642− parseJSON v = parseAsInt v
3643− <|> parseAsString v
3644− where parseAsInt = fmap ReplicaCount . parseJSON
3645− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3647−instance FromJSON ShardCount where
3648− parseJSON v = parseAsInt v
3649− <|> parseAsString v
3650− where parseAsInt = fmap ShardCount . parseJSON
3651− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3653−instance Bounded DocVersion where
3654− minBound = DocVersion 1
3655− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3657−instance Enum DocVersion where
3659− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3660− | otherwise = succError "DocVersion"
3662− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3663− | otherwise = predError "DocVersion"
3665− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3666− fromEnum = docVersionNumber
3667− enumFrom = boundedEnumFrom
3668− enumFromThen = boundedEnumFromThen
3670−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3671−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3673−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3674−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3677−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3678− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3681−-- | Either specifies an exact repo name or one with globs in it,
3682−-- e.g. @RepoPattern "foo*"@ __NOTE__:@ Patterns are not supported on ES < 1.7
3683−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3685− deriving (Eq, Generic, Show, Typeable)
3687−-- | The unique name of a snapshot repository.
3688−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3689− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3692−-- | A generic representation of a snapshot repo. This is what gets
3693−-- sent to and parsed from the server. For repo types enabled by
3694−-- plugins that aren't exported by this library, consider making a
3695−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3696−-- type, consider submitting a pull request to have it included in the
3698−data GenericSnapshotRepo = GenericSnapshotRepo {
3699− gSnapshotRepoName :: SnapshotRepoName
3700− , gSnapshotRepoType :: SnapshotRepoType
3701− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3702− } deriving (Eq, Generic, Show, Typeable)
3705−instance SnapshotRepo GenericSnapshotRepo where
3706− toGSnapshotRepo = id
3707− fromGSnapshotRepo = Right
3710−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3711− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3714−-- | Opaque representation of snapshot repo settings. Instances of
3715−-- 'SnapshotRepo' will produce this.
3716−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3717− deriving (Eq, Generic, Show, Typeable, ToJSON)
3720− -- Regardless of whether you send strongly typed json, my version of
3721− -- ES sends back stringly typed json in the settings, e.g. booleans
3722− -- as strings, so we'll try to convert them.
3723−instance FromJSON GenericSnapshotRepoSettings where
3724− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3726−-- | The result of running 'verifySnapshotRepo'.
3727−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3728− deriving (Eq, Generic, Show, Typeable)
3731−instance FromJSON SnapshotVerification where
3732− parseJSON = withObject "SnapshotVerification" parse
3736− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3737− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3738− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3741−data SnapshotNodeVerification = SnapshotNodeVerification {
3742− snvFullId :: FullNodeId
3743− , snvNodeName :: NodeName
3744− } deriving (Eq, Generic, Show, Typeable)
3747−-- | Unique, automatically-generated name assigned to nodes that are
3748−-- usually returned in node-oriented APIs.
3749−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3750− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3753−newtype NodeName = NodeName { nodeName :: Text }
3754− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3757−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
3758− repoUpdateVerify :: Bool
3759− -- ^ After creation/update, synchronously check that nodes can
3760− -- write to this repo. Defaults to True. You may use False if you
3761− -- need a faster response and plan on verifying manually later
3762− -- with 'verifySnapshotRepo'.
3763− } deriving (Eq, Show, Generic, Typeable)
3766−-- | Reasonable defaults for repo creation/update
3768−-- * repoUpdateVerify True
3769−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
3770−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
3773−-- | A filesystem-based snapshot repo that ships with elasticsearch.
3774−data FsSnapshotRepo = FsSnapshotRepo {
3775− fsrName :: SnapshotRepoName
3776− , fsrLocation :: FilePath
3777− , fsrCompressMetadata :: Bool
3778− , fsrChunkSize :: Maybe Bytes
3779− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
3780− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
3781− } deriving (Eq, Generic, Show, Typeable)
3784−instance SnapshotRepo FsSnapshotRepo where
3785− toGSnapshotRepo FsSnapshotRepo {..} =
3786− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
3788− Object settings = object $ [ "location" .= fsrLocation
3789− , "compress" .= fsrCompressMetadata
3791− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
3792− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
3793− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
3795− fromGSnapshotRepo GenericSnapshotRepo {..}
3796− | gSnapshotRepoType == fsRepoType = do
3797− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
3799− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
3800− <*> o .:? "compress" .!= False
3801− <*> o .:? "chunk_size"
3802− <*> o .:? "max_restore_bytes_per_sec"
3803− <*> o .:? "max_snapshot_bytes_per_sec"
3804− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
3807−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
3808−parseRepo parser = case parseEither (const parser) () of
3809− Left e -> Left (OtherRepoConversionError (T.pack e))
3813−fsRepoType :: SnapshotRepoType
3814−fsRepoType = SnapshotRepoType "fs"
3816−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
3817−class SnapshotRepo r where
3818− toGSnapshotRepo :: r -> GenericSnapshotRepo
3819− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
3822−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType
3826− | OtherRepoConversionError Text
3827− deriving (Show, Eq, Generic, Typeable)
3830−instance Exception SnapshotRepoConversionError
3833−data SnapshotCreateSettings = SnapshotCreateSettings {
3834− snapWaitForCompletion :: Bool
3835− -- ^ Should the API call return immediately after initializing
3836− -- the snapshot or wait until completed. Note that if this is
3837− -- enabled it could wait a long time, so you should adjust your
3838− -- 'ManagerSettings' accordingly to set long timeouts or
3839− -- explicitly handle timeouts.
3840− , snapIndices :: Maybe (NonEmpty IndexName)
3841− -- ^ Nothing will snapshot all indices. Just [] is permissable and
3842− -- will essentially be a no-op snapshot.
3843− , snapIgnoreUnavailable :: Bool
3844− -- ^ If set to True, any matched indices that don't exist will be
3845− -- ignored. Otherwise it will be an error and fail.
3846− , snapIncludeGlobalState :: Bool
3847− , snapPartial :: Bool
3848− -- ^ If some indices failed to snapshot (e.g. if not all primary
3849− -- shards are available), should the process proceed?
3853−-- | Reasonable defaults for snapshot creation
3855−-- * snapWaitForCompletion False
3856−-- * snapIndices Nothing
3857−-- * snapIgnoreUnavailable False
3858−-- * snapIncludeGlobalState True
3859−-- * snapPartial False
3860−defaultSnapshotCreateSettings :: SnapshotCreateSettings
3861−defaultSnapshotCreateSettings =
3862− SnapshotCreateSettings False Nothing False True False
3865−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
3866− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
3869−-- | Either specifies an exact snapshot name or one with globs in it,
3870−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
3872−data SnapshotPattern = ExactSnap SnapshotName
3874− deriving (Eq, Generic, Show, Typeable)
3877−-- | General information about the state of a snapshot. Has some
3878−-- redundancies with 'SnapshotStatus'
3879−data SnapshotInfo = SnapshotInfo {
3880− snapInfoShards :: ShardResult
3881− --TODO: what does failures produce? list of what?
3882− , snapInfoDuration :: NominalDiffTime
3883− , snapInfoEndTime :: UTCTime
3884− , snapInfoStartTime :: UTCTime
3885− , snapInfoState :: SnapshotState
3886− , snapInfoIndices :: [IndexName]
3887− , snapInfoName :: SnapshotName
3888− } deriving (Eq, Generic, Show, Typeable)
3891−instance FromJSON SnapshotInfo where
3892− parseJSON = withObject "SnapshotInfo" parse
3894− parse o = SnapshotInfo <$> o .: "shards"
3895− <*> (unMS <$> o .: "duration_in_millis")
3896− <*> (posixMS <$> o .: "end_time_in_millis")
3897− <*> (posixMS <$> o .: "start_time_in_millis")
3900− <*> o .: "snapshot"
3903−newtype MS = MS NominalDiffTime
3906−-- keeps the unexported constructor warnings at bay
3907−unMS :: MS -> NominalDiffTime
3911−instance FromJSON MS where
3912− parseJSON = withScientific "MS" (return . MS . parse)
3914− parse n = fromInteger ((truncate n) * 1000)
3917−data SnapshotState = SnapshotInit
3924− deriving (Show, Eq, Generic, Typeable)
3926−instance FromJSON SnapshotState where
3927− parseJSON = withText "SnapshotState" parse
3929− parse "INIT" = return SnapshotInit
3930− parse "STARTED" = return SnapshotStarted
3931− parse "SUCCESS" = return SnapshotSuccess
3932− parse "FAILED" = return SnapshotFailed
3933− parse "ABORTED" = return SnapshotAborted
3934− parse "MISSING" = return SnapshotMissing
3935− parse "WAITING" = return SnapshotWaiting
3936− parse t = fail ("Invalid snapshot state " <> T.unpack t)
3939−newtype SnapshotName = SnapshotName { snapshotName :: Text }
3940− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)