@@ -1,10 +1,7 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveGeneric #-}
31{-# LANGUAGE FlexibleContexts #-}
42{-# LANGUAGE FlexibleInstances #-}
53{-# LANGUAGE GeneralizedNewtypeDeriving #-}
64{-# LANGUAGE MultiParamTypeClasses #-}
7−-- {-# LANGUAGE NoMonomorphismRestriction #-}
85{-# LANGUAGE NamedFieldPuns #-}
96{-# LANGUAGE OverloadedStrings #-}
107{-# LANGUAGE RecordWildCards #-}
@@ -13,11 +10,11 @@
1310-------------------------------------------------------------------------------
1411-- |
1512-- Module : Database.Bloodhound.Types
16−-- Copyright : (C) 2014, 2015, 2016 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
1714-- License : BSD-style (see the file LICENSE)
1815-- Maintainer : Chris Allen <cma@bitemyapp.com
1916-- Stability : provisional
20−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
2118--
2219-- Data types for describing actions and data structures performed to interact
2320-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -45,11 +42,15 @@ module Database.Bloodhound.Types
4542 , mkTermsAggregation
4643 , mkTermsScriptAggregation
4744 , mkDateHistogram
45+ , mkCardinalityAggregation
4846 , mkDocVersion
47+ , mkStatsAggregation
48+ , mkExtendedStatsAggregation
4949 , docVersionNumber
5050 , toMissing
5151 , toTerms
5252 , toDateHistogram
53+ , toTopHits
5354 , omitNulls
5455 , BH(..)
5556 , runBH
@@ -60,6 +61,9 @@ module Database.Bloodhound.Types
6061 , mkBHEnv
6162 , MonadBH(..)
6263 , Version(..)
64+ , VersionNumber(..)
65+ , MaybeNA(..)
66+ , BuildHash(..)
6367 , Status(..)
6468 , Existence(..)
6569 , NullValue(..)
@@ -67,6 +71,7 @@ module Database.Bloodhound.Types
6771 , UpdatableIndexSetting(..)
6872 , IndexSettingsSummary(..)
6973 , AllocationPolicy(..)
74+ , Compression(..)
7075 , ReplicaBounds(..)
7176 , Bytes(..)
7277 , gigabytes
@@ -115,8 +120,8 @@ module Database.Bloodhound.Types
115120 , Pattern(..)
116121 , ShardResult(..)
117122 , Hit(..)
123+ , HitFields(..)
118124 , Filter(..)
119− , Seminearring(..)
120125 , BoolMatch(..)
121126 , Term(..)
122127 , GeoPoint(..)
@@ -143,11 +148,22 @@ module Database.Bloodhound.Types
143148 , RegexpFlags(..)
144149 , RegexpFlag(..)
145150 , FieldName(..)
151+ , ScriptFields(..)
152+ , ScriptFieldName
153+ , ScriptFieldValue
146154 , Script(..)
155+ , ScriptLanguage(..)
156+ , ScriptInline(..)
157+ , ScriptId(..)
158+ , ScriptParams(..)
159+ , ScriptParamName
160+ , ScriptParamValue
147161 , IndexName(..)
148162 , IndexSelection(..)
149− , IndexOptimizationSettings(..)
150− , defaultIndexOptimizationSettings
163+ , NodeSelection(..)
164+ , NodeSelector(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
151167 , TemplateName(..)
152168 , TemplatePattern(..)
153169 , MappingName(..)
@@ -171,8 +187,19 @@ module Database.Bloodhound.Types
171187 , BoolQuery(..)
172188 , BoostingQuery(..)
173189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
191+ , BoostMode(..)
192+ , ScoreMode(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
196+ , Weight(..)
197+ , Seed(..)
198+ , FieldValueFactor(..)
199+ , Factor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
174202 , DisMaxQuery(..)
175− , FilteredQuery(..)
176203 , FuzzyLikeThisQuery(..)
177204 , FuzzyLikeFieldQuery(..)
178205 , FuzzyQuery(..)
@@ -188,10 +215,16 @@ module Database.Bloodhound.Types
188215 , RangeQuery(..)
189216 , RegexpQuery(..)
190217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
220+ , WildcardQuery(..)
191221 , BooleanOperator(..)
192222 , ZeroTermsQuery(..)
193223 , CutoffFrequency(..)
194224 , Analyzer(..)
225+ , Tokenizer(..)
226+ , TokenFilter(..)
227+ , CharFilter(..)
195228 , MaxExpansions(..)
196229 , Lenient(..)
197230 , MatchQueryType(..)
@@ -252,12 +285,59 @@ module Database.Bloodhound.Types
252285 , SnapshotNodeVerification(..)
253286 , FullNodeId(..)
254287 , NodeName(..)
288+ , ClusterName(..)
289+ , NodesInfo(..)
290+ , NodesStats(..)
291+ , NodeStats(..)
292+ , NodeBreakersStats(..)
293+ , NodeBreakerStats(..)
294+ , NodeHTTPStats(..)
295+ , NodeTransportStats(..)
296+ , NodeFSStats(..)
297+ , NodeDataPathStats(..)
298+ , NodeFSTotalStats(..)
299+ , NodeNetworkStats(..)
300+ , NodeThreadPoolsStats(..)
301+ , NodeThreadPoolStats(..)
302+ , NodeJVMStats(..)
303+ , JVMBufferPoolStats(..)
304+ , JVMGCStats(..)
305+ , JVMPoolStats(..)
306+ , NodeProcessStats(..)
307+ , NodeOSStats(..)
308+ , LoadAvgs(..)
309+ , NodeIndicesStats(..)
310+ , EsAddress(..)
311+ , PluginName(..)
312+ , NodeInfo(..)
313+ , NodePluginInfo(..)
314+ , NodeHTTPInfo(..)
315+ , NodeTransportInfo(..)
316+ , BoundTransportAddress(..)
317+ , NodeNetworkInfo(..)
318+ , MacAddress(..)
319+ , NetworkInterfaceName(..)
320+ , NodeNetworkInterface(..)
321+ , NodeThreadPoolsInfo(..)
322+ , NodeThreadPoolInfo(..)
323+ , ThreadPoolSize(..)
324+ , ThreadPoolType(..)
325+ , NodeJVMInfo(..)
326+ , JVMMemoryPool(..)
327+ , JVMGCCollector(..)
328+ , JVMMemoryInfo(..)
329+ , PID(..)
330+ , NodeOSInfo(..)
331+ , CPUInfo(..)
332+ , NodeProcessInfo(..)
255333 , FsSnapshotRepo(..)
256334 , SnapshotCreateSettings(..)
257335 , defaultSnapshotCreateSettings
258336 , SnapshotSelection(..)
259337 , SnapshotPattern(..)
260338 , SnapshotInfo(..)
339+ , SnapshotShardFailure(..)
340+ , ShardId(..)
261341 , SnapshotName(..)
262342 , SnapshotState(..)
263343 , SnapshotRestoreSettings(..)
@@ -268,6 +348,18 @@ module Database.Bloodhound.Types
268348 , rrGroupRefNum
269349 , mkRRGroupRefNum
270350 , RestoreIndexSettings(..)
351+ , Suggest(..)
352+ , SuggestType(..)
353+ , PhraseSuggester(..)
354+ , PhraseSuggesterHighlighter(..)
355+ , PhraseSuggesterCollate(..)
356+ , mkPhraseSuggester
357+ , SuggestOptions(..)
358+ , SuggestResponse(..)
359+ , NamedSuggestionResponse(..)
360+ , DirectGenerators(..)
361+ , mkDirectGenerators
362+ , DirectGeneratorSuggestModeTypes (..)
271363
272364 , Aggregation(..)
273365 , Aggregations
@@ -279,6 +371,8 @@ module Database.Bloodhound.Types
279371 , MissingAggregation(..)
280372 , ValueCountAggregation(..)
281373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
282376 , DateHistogramAggregation(..)
283377 , DateRangeAggregation(..)
284378 , DateRangeAggRange(..)
@@ -286,6 +380,9 @@ module Database.Bloodhound.Types
286380 , DateMathAnchor(..)
287381 , DateMathModifier(..)
288382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
385+ , SearchAfterKey
289386
290387 , Highlights(..)
291388 , FieldHighlight(..)
@@ -303,697 +400,32 @@ module Database.Bloodhound.Types
303400 , TermsResult(..)
304401 , DateHistogramResult(..)
305402 , DateRangeResult(..)
403+ , TopHitResult(..)
306404
307405 , EsUsername(..)
308406 , EsPassword(..)
309− ) where
310407
311−import Control.Applicative as A
312−import Control.Monad.Catch
313−import Control.Monad.Except
314−import Control.Monad.Reader
315−import Control.Monad.State
316−import Control.Monad.Writer
317−import Data.Aeson
318−import Data.Aeson.Types (Pair, Parser, emptyObject,
319− parseEither, parseMaybe)
320−import qualified Data.ByteString.Lazy.Char8 as L
321−import Data.Char
322−import Data.Hashable (Hashable)
323−import qualified Data.HashMap.Strict as HM
324−import Data.List (foldl', nub)
325−import Data.List.NonEmpty (NonEmpty (..), toList)
326−import qualified Data.Map.Strict as M
327−import Data.Maybe
328−import Data.Scientific (Scientific)
329−import Data.Text (Text)
330−import qualified Data.Text as T
331−import Data.Time.Calendar
332−import Data.Time.Clock (NominalDiffTime, UTCTime)
333−import Data.Time.Clock.POSIX
334−import qualified Data.Traversable as DT
335−import Data.Typeable (Typeable)
336−import qualified Data.Vector as V
337−import GHC.Enum
338−import GHC.Generics (Generic)
339−import Network.HTTP.Client
340−import qualified Network.HTTP.Types.Method as NHTM
341−import qualified Text.Read as TR
342−
343−import Database.Bloodhound.Types.Class
344−import Database.Bloodhound.Types.Internal
345−
346−-- $setup
347−-- >>> :set -XOverloadedStrings
348−-- >>> import Data.Aeson
349−-- >>> import Database.Bloodhound
350−-- >>> let testServer = (Server "http://localhost:9200")
351−-- >>> let testIndex = IndexName "twitter"
352−-- >>> let testMapping = MappingName "tweet"
353−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
354−
355−-- defaultIndexSettings is exported by Database.Bloodhound as well
356−-- no trailing slashes in servers, library handles building the path.
357−
358−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
359−-- will be a noop. You can use the exported fields to customize it further, e.g.:
360−--
361−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
362−mkBHEnv :: Server -> Manager -> BHEnv
363−mkBHEnv s m = BHEnv s m return
364−
365−newtype BH m a = BH {
366− unBH :: ReaderT BHEnv m a
367− } deriving ( Functor
368− , A.Applicative
369− , Monad
370− , MonadIO
371− , MonadState s
372− , MonadWriter w
373− , MonadError e
374− , Alternative
375− , MonadPlus
376− , MonadFix
377− , MonadThrow
378− , MonadCatch
379− , MonadMask)
380−
381−instance MonadTrans BH where
382− lift = BH . lift
383−
384−instance (MonadReader r m) => MonadReader r (BH m) where
385− ask = lift ask
386− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
387− local f (m r)
388−
389−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
390− getBHEnv = BH getBHEnv
391−
392−runBH :: BHEnv -> BH m a -> m a
393−runBH e f = runReaderT (unBH f) e
394−
395−{-| 'Version' is embedded in 'Status' -}
396−data Version = Version { number :: Text
397− , build_hash :: Text
398− , build_timestamp :: UTCTime
399− , build_snapshot :: Bool
400− , lucene_version :: Text } deriving (Eq, Read, Show, Generic, Typeable)
401−
402−{-| 'Status' is a data type for describing the JSON body returned by
403− Elasticsearch when you query its status. This was deprecated in 1.2.0.
404−
405− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
406−-}
407−
408−data Status = Status { ok :: Maybe Bool
409− , status :: Int
410− , name :: Text
411− , version :: Version
412− , tagline :: Text } deriving (Eq, Read, Show, Generic)
413−
414−{-| 'IndexSettings' is used to configure the shards and replicas when you create
415− an Elasticsearch Index.
416−
417− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
418−-}
419−
420−data IndexSettings =
421− IndexSettings { indexShards :: ShardCount
422− , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
423−
424−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
425−defaultIndexSettings :: IndexSettings
426−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
427−
428−
429−{-| 'IndexOptimizationSettings' is used to configure index optimization. See
430− <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
431− for more info.
432−-}
433−data IndexOptimizationSettings =
434− IndexOptimizationSettings { maxNumSegments :: Maybe Int
435− -- ^ 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.
436− , onlyExpungeDeletes :: Bool
437− -- ^ 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.
438− , flushAfterOptimize :: Bool
439− -- ^ Should a flush be performed after the optimize.
440− } deriving (Eq, Show, Generic, Typeable)
441−
442−
443−{-| 'defaultIndexOptimizationSettings' implements the default settings that
444− ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
445− 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
446−-}
447−defaultIndexOptimizationSettings :: IndexOptimizationSettings
448−defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
449−
450−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
451−
452− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
453−-}
454−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
455− -- ^ The number of replicas each shard has.
456− | AutoExpandReplicas ReplicaBounds
457− | BlocksReadOnly Bool
458− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
459− | BlocksRead Bool
460− -- ^ Set to True to disable read operations against the index.
461− | BlocksWrite Bool
462− -- ^ Set to True to disable write operations against the index.
463− | BlocksMetaData Bool
464− -- ^ Set to True to disable metadata operations against the index.
465− | RefreshInterval NominalDiffTime
466− -- ^ The async refresh interval of a shard
467− | IndexConcurrency Int
468− | FailOnMergeFailure Bool
469− | TranslogFlushThresholdOps Int
470− -- ^ When to flush on operations.
471− | TranslogFlushThresholdSize Bytes
472− -- ^ When to flush based on translog (bytes) size.
473− | TranslogFlushThresholdPeriod NominalDiffTime
474− -- ^ When to flush based on a period of not flushing.
475− | TranslogDisableFlush Bool
476− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
477− | CacheFilterMaxSize (Maybe Bytes)
478− -- ^ The maximum size of filter cache (per segment in shard).
479− | CacheFilterExpire (Maybe NominalDiffTime)
480− -- ^ The expire after access time for filter cache.
481− | GatewaySnapshotInterval NominalDiffTime
482− -- ^ The gateway snapshot interval (only applies to shared gateways).
483− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
484− -- ^ A node matching any rule will be allowed to host shards from the index.
485− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
486− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
487− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
488− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
489− | RoutingAllocationEnable AllocationPolicy
490− -- ^ Enables shard allocation for a specific index.
491− | RoutingAllocationShardsPerNode ShardCount
492− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
493− | RecoveryInitialShards InitialShardCount
494− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
495− | GCDeletes NominalDiffTime
496− | TTLDisablePurge Bool
497− -- ^ Disables temporarily the purge of expired docs.
498− | TranslogFSType FSType
499− | IndexCompoundFormat CompoundFormat
500− | IndexCompoundOnFlush Bool
501− | WarmerEnabled Bool
502− deriving (Eq, Show, Generic, Typeable)
503−
504−data AllocationPolicy = AllocAll
505− -- ^ Allows shard allocation for all shards.
506− | AllocPrimaries
507− -- ^ Allows shard allocation only for primary shards.
508− | AllocNewPrimaries
509− -- ^ Allows shard allocation only for primary shards for new indices.
510− | AllocNone
511− -- ^ No shard allocation is allowed
512− deriving (Eq, Read, Show, Generic, Typeable)
513−
514−data ReplicaBounds = ReplicasBounded Int Int
515− | ReplicasLowerBounded Int
516− | ReplicasUnbounded
517− deriving (Eq, Read, Show, Generic, Typeable)
518−
519−-- | A measure of bytes used for various configurations. You may want
520−-- to use smart constructors like 'gigabytes' for larger values.
521−--
522−-- >>> gigabytes 9
523−-- Bytes 9000000000
524−--
525−-- >>> megabytes 9
526−-- Bytes 9000000
527−--
528−-- >>> kilobytes 9
529−-- Bytes 9000
530−newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
531−
532−gigabytes :: Int -> Bytes
533−gigabytes n = megabytes (1000 * n)
534−
535−
536−megabytes :: Int -> Bytes
537−megabytes n = kilobytes (1000 * n)
538−
539−
540−kilobytes :: Int -> Bytes
541−kilobytes n = Bytes (1000 * n)
542−
543−
544−data FSType = FSSimple
545− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
546−
547−data InitialShardCount = QuorumShards
548− | QuorumMinus1Shards
549− | FullShards
550− | FullMinus1Shards
551− | ExplicitShards Int
552− deriving (Eq, Read, Show, Generic, Typeable)
553−
554−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
555− , nodeAttrFilterValues :: NonEmpty Text}
556− deriving (Eq, Read, Show, Generic, Ord)
557−
558−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
559−
560−data CompoundFormat = CompoundFileFormat Bool
561− | MergeSegmentVsTotalIndex Double
562− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
563− deriving (Eq, Read, Show, Generic, Typeable)
564−
565−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
566−
567−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
568− , sSummaryFixedSettings :: IndexSettings
569− , sSummaryUpdateable :: [UpdatableIndexSetting]}
570− deriving (Eq, Show, Generic, Typeable)
571−
572−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
573−type Reply = Network.HTTP.Client.Response L.ByteString
574−type Method = NHTM.Method
575−
576−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
577−
578− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
579−-}
580−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
581−
582−data FieldType = GeoPointType
583− | GeoShapeType
584− | FloatType
585− | IntegerType
586− | LongType
587− | ShortType
588− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
589−
590−data FieldDefinition =
591− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
592−
593−{-| An 'IndexTemplate' defines a template that will automatically be
594− applied to new indices created. The templates include both
595− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
596− controls if the template will be applied to the index created.
597− Specify mappings as follows: @[toJSON TweetMapping, ...]@
598−
599− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
600−-}
601−data IndexTemplate =
602− IndexTemplate { templatePattern :: TemplatePattern
603− , templateSettings :: Maybe IndexSettings
604− , templateMappings :: [Value]
605− }
606−
607−data MappingField =
608− MappingField { mappingFieldName :: FieldName
609− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
610−
611−{-| Support for type reification of 'Mapping's is currently incomplete, for
612− now the mapping API verbiage expects a 'ToJSON'able blob.
613−
614− Indexes have mappings, mappings are schemas for the documents contained in the
615− index. I'd recommend having only one mapping per index, always having a mapping,
616− and keeping different kinds of documents separated if possible.
617−-}
618−data Mapping = Mapping { typeName :: TypeName
619− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
620−
621−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
622− operation index, create, delete, and update. 'BulkIndex' behaves like an
623− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
624−
625− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
626−-}
627−data BulkOperation =
628− BulkIndex IndexName MappingName DocId Value
629− | BulkCreate IndexName MappingName DocId Value
630− | BulkDelete IndexName MappingName DocId
631− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
632−
633−{-| 'EsResult' describes the standard wrapper JSON document that you see in
634− successful Elasticsearch lookups or lookups that couldn't find the document.
635−-}
636−data EsResult a = EsResult { _index :: Text
637− , _type :: Text
638− , _id :: Text
639− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
640−
641−{-| 'EsResultFound' contains the document and its metadata inside of an
642− 'EsResult' when the document was successfully found.
643−-}
644−data EsResultFound a = EsResultFound { _version :: DocVersion
645− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
646−
647−{-| 'EsError' is the generic type that will be returned when there was a
648− problem. If you can't parse the expected response, its a good idea to
649− try parsing this.
650−-}
651−data EsError = EsError { errorStatus :: Int
652− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
653−
654−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
655−returned by the ElasticSearch server. If you encounter this error, please
656−verify that your domain data types and FromJSON instances are working properly
657−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
658−sure that your mappings are correct, then this error may be an indication of an
659−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
660−and be sure to include the exception body.
661−-}
662−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
663− deriving (Eq, Read, Show, Generic, Typeable)
664−
665−instance Exception EsProtocolException
666−
667−data IndexAlias = IndexAlias { srcIndex :: IndexName
668− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
669−
670−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
671−
672−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
673− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
674−
675−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
676− , aliasCreateFilter :: Maybe Filter}
677− deriving (Read, Show, Eq, Generic, Typeable)
678−
679−data AliasRouting = AllAliasRouting RoutingValue
680− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
681− deriving (Read, Show, Eq, Generic, Typeable)
682−
683−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
684−
685−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
686−
687−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
688−
689−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
690−
691−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
692−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
693− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
694−
695−{-| 'DocVersion' is an integer version number for a document between 1
696−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
697−-}
698−newtype DocVersion = DocVersion {
699− docVersionNumber :: Int
700− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
701−
702−-- | Smart constructor for in-range doc version
703−mkDocVersion :: Int -> Maybe DocVersion
704−mkDocVersion i
705− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
706− Just $ DocVersion i
707− | otherwise = Nothing
708−
709−
710−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
711−own version numbers instead of ones from ES.
712−-}
713−newtype ExternalDocVersion = ExternalDocVersion DocVersion
714− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
715−
716−{-| 'VersionControl' is specified when indexing documents as a
717−optimistic concurrency control.
718−-}
719−data VersionControl = NoVersionControl
720− -- ^ Don't send a version. This is a pure overwrite.
721− | InternalVersion DocVersion
722− -- ^ Use the default ES versioning scheme. Only
723− -- index the document if the version is the same
724− -- as the one specified. Only applicable to
725− -- updates, as you should be getting Version from
726− -- a search result.
727− | ExternalGT ExternalDocVersion
728− -- ^ Use your own version numbering. Only index
729− -- the document if the version is strictly higher
730− -- OR the document doesn't exist. The given
731− -- version will be used as the new version number
732− -- for the stored document. N.B. All updates must
733− -- increment this number, meaning there is some
734− -- global, external ordering of updates.
735− | ExternalGTE ExternalDocVersion
736− -- ^ Use your own version numbering. Only index
737− -- the document if the version is equal or higher
738− -- than the stored version. Will succeed if there
739− -- is no existing document. The given version will
740− -- be used as the new version number for the
741− -- stored document. Use with care, as this could
742− -- result in data loss.
743− | ForceVersion ExternalDocVersion
744− -- ^ The document will always be indexed and the
745− -- given version will be the new version. This is
746− -- typically used for correcting errors. Use with
747− -- care, as this could result in data loss.
748− deriving (Read, Show, Eq, Generic, Ord)
749−
750−{-| 'DocumentParent' is used to specify a parent document.
751−-}
752−newtype DocumentParent = DocumentParent DocId
753− deriving (Eq, Read, Show, Generic, Typeable)
754−
755−{-| 'IndexDocumentSettings' are special settings supplied when indexing
756−a document. For the best backwards compatiblity when new fields are
757−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
758−-}
759−data IndexDocumentSettings =
760− IndexDocumentSettings { idsVersionControl :: VersionControl
761− , idsParent :: Maybe DocumentParent
762− } deriving (Eq, Read, Show, Generic, Typeable)
763−
764−{-| Reasonable default settings. Chooses no version control and no parent.
765−-}
766−defaultIndexDocumentSettings :: IndexDocumentSettings
767−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
768−
769−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
770− dependent with later sorts acting as tie-breakers for earlier sorts.
771−-}
772−type Sort = [SortSpec]
773−
774−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
775− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
776− 'DistanceUnit' to express "nearness" to a single geographical point as a
777− sort specification.
778−
779−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
780−-}
781−data SortSpec = DefaultSortSpec DefaultSort
782− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
783−
784−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
785− 'mkSort' convenience function for when you want to specify only the most
786− common parameters.
787−
788−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
789−-}
790−data DefaultSort =
791− DefaultSort { sortFieldName :: FieldName
792− , sortOrder :: SortOrder
793− -- default False
794− , ignoreUnmapped :: Bool
795− , sortMode :: Maybe SortMode
796− , missingSort :: Maybe Missing
797− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
798−
799−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
800− encoded into "asc" or "desc" when turned into JSON.
801−
802−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
803−-}
804−data SortOrder = Ascending
805− | Descending deriving (Eq, Read, Show, Generic, Typeable)
806−
807−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
808− sorted last, first, or using a custom value as a substitute.
809−
810−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
811−-}
812−data Missing = LastMissing
813− | FirstMissing
814− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
815−
816−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
817−
818−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
819−-}
820−data SortMode = SortMin
821− | SortMax
822− | SortSum
823− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
824−
825−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
826− that you can concisely describe the usual kind of 'SortSpec's you want.
827−-}
828−mkSort :: FieldName -> SortOrder -> DefaultSort
829−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
830−
831−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
832− 'Query's cannot be cached.
833−-}
834−type Cache = Bool -- caching on/off
835−defaultCache :: Cache
836−defaultCache = False
837−
838−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
839−-}
840−type PrefixValue = Text
841−
842−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
843− JSON encoding baked in. Used all over the place.
844−-}
845−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
846−
847−{-| 'ShardCount' is part of 'IndexSettings'
848−-}
849−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
850−
851−{-| 'ReplicaCount' is part of 'IndexSettings'
852−-}
853−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
854−
855−{-| 'IndexName' is used to describe which index to query/create/delete
856−-}
857−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
858−
859−{-| 'IndexSelection' is used for APIs which take a single index, a list of
860− indexes, or the special @_all@ index.
861−-}
862−data IndexSelection = IndexList (NonEmpty IndexName)
863− | AllIndexes deriving (Eq, Generic, Show, Typeable)
864−
865−{-| 'TemplateName' is used to describe which template to query/create/delete
866−-}
867−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
868−
869−{-| 'TemplatePattern' represents a pattern which is matched against index names
870−-}
871−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
872−
873−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
874− the data in the indices.
875−-}
876−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
877−
878−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
879− Can be set by the user or created by ES itself. Often used in client
880− functions for poking at specific documents.
881−-}
882−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
883−
884−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
885−-}
886−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
887−
888−{-| 'FieldName' is used all over the place wherever a specific field within
889− a document needs to be specified, usually in 'Query's or 'Filter's.
890−-}
891−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
892−
893−
894−{-| 'Script' is often used in place of 'FieldName' to specify more
895−complex ways of extracting a value from a document.
896−-}
897−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
898−
899−{-| 'CacheName' is used in 'RegexpFilter' for describing the
900− 'CacheKey' keyed caching behavior.
901−-}
902−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
903−
904−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
905−-}
906−newtype CacheKey =
907− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
908−newtype Existence =
909− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
910−newtype NullValue =
911− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
912−newtype CutoffFrequency =
913− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
914−newtype Analyzer =
915− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
916−newtype MaxExpansions =
917− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
918−
919−{-| 'Lenient', if set to true, will cause format based failures to be
920− ignored. I don't know what the bloody default is, Elasticsearch
921− documentation didn't say what it was. Let me know if you figure it out.
922−-}
923−newtype Lenient =
924− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
925−newtype Tiebreaker =
926− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
927−newtype Boost =
928− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
929−newtype BoostTerms =
930− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
931−
932−{-| 'MinimumMatch' controls how many should clauses in the bool query should
933− match. Can be an absolute value (2) or a percentage (30%) or a
934− combination of both.
935−-}
936−newtype MinimumMatch =
937− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
938−newtype DisableCoord =
939− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
940−newtype IgnoreTermFrequency =
941− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
942−newtype MinimumTermFrequency =
943− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
944−newtype MaxQueryTerms =
945− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
946−newtype Fuzziness =
947− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
948−
949−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
950−newtype PrefixLength =
951− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
952−newtype TypeName =
953− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
954−newtype PercentMatch =
955− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
956−newtype StopWord =
957− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
958−newtype QueryPath =
959− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
960−
961−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
962− heavy, because all terms in the index need to be examined, just in case
963− they match. Leading wildcards can be disabled by setting
964− 'AllowLeadingWildcard' to false. -}
965−newtype AllowLeadingWildcard =
966− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
967−newtype LowercaseExpanded =
968− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
969−newtype EnablePositionIncrements =
970− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
971−
972−{-| By default, wildcard terms in a query are not analyzed.
973− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
974−-}
975−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
976−
977−{-| 'GeneratePhraseQueries' defaults to false.
978−-}
979−newtype GeneratePhraseQueries =
980− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
981−
982−{-| 'Locale' is used for string conversions - defaults to ROOT.
983−-}
984−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
985−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
986−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
987−
988−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
989− phrase matches. Default is 0.
990−-}
991−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
992−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
993−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
994−
995−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
996−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
408+ , Analysis(..)
409+ , AnalyzerDefinition(..)
410+ , TokenizerDefinition(..)
411+ , TokenFilterDefinition(..)
412+ , CharFilterDefinition(..)
413+ , Ngram(..)
414+ , TokenChar(..)
415+ , Shingle(..)
416+ , Language(..)
417+ ) where
418+
419+import Bloodhound.Import
420+
421+import Database.Bloodhound.Internal.Aggregation
422+import Database.Bloodhound.Internal.Analysis
423+import Database.Bloodhound.Internal.Client
424+import Database.Bloodhound.Internal.Highlight
425+import Database.Bloodhound.Internal.Newtypes
426+import Database.Bloodhound.Internal.Query
427+import Database.Bloodhound.Internal.Sort
428+import Database.Bloodhound.Internal.Suggest
997429
998430{-| 'unpackId' is a silly convenience function that gets used once.
999431-}
@@ -1001,8 +433,6 @@ unpackId :: DocId -> Text
1001433unpackId (DocId docId) = docId
1002434
1003435type TrackSortScores = Bool
1004−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1005−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
1006436
1007437data Search = Search { queryBody :: Maybe Query
1008438 , filterBody :: Maybe Filter
@@ -1014,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
1014444 , from :: From
1015445 , size :: Size
1016446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
1017448 , fields :: Maybe [FieldName]
1018− , source :: Maybe Source } deriving (Eq, Read, Show, Generic, Typeable)
449+ , scriptFields :: Maybe ScriptFields
450+ , source :: Maybe Source
451+ , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
452+ } deriving (Eq, Show)
453+
454+
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'
460+ , "sort" .= sort
461+ , "aggregations" .= searchAggs
462+ , "highlight" .= highlight
463+ , "from" .= sFrom
464+ , "size" .= sSize
465+ , "track_scores" .= sTrackSortScores
466+ , "search_after" .= sAfter
467+ , "fields" .= sFields
468+ , "script_fields" .= sScriptFields
469+ , "_source" .= sSource
470+ , "suggest" .= sSuggest]
471+
472+ where query' = case sFilter of
473+ Nothing -> mquery
474+ Just x ->
475+ Just
476+ . QueryBoolQuery
477+ $ mkBoolQuery (maybeToList mquery)
478+ [x] [] []
1019479
1020480data SearchType = SearchTypeQueryThenFetch
1021481 | SearchTypeDfsQueryThenFetch
1022− | SearchTypeCount
1023− | SearchTypeScan
1024− | SearchTypeQueryAndFetch
1025− | SearchTypeDfsQueryAndFetch
1026− deriving (Eq, Read, Show, Generic, Typeable)
482+ deriving (Eq, Show)
1027483
1028484data Source =
1029485 NoSource
1030486 | SourcePatterns PatternOrPatterns
1031487 | SourceIncludeExclude Include Exclude
1032− deriving (Read, Show, Eq, Generic, Typeable)
1033−
1034−data PatternOrPatterns = PopPattern Pattern
1035− | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1036−
1037−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1038−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1039−
1040−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
1041−
1042−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1043− , highlightFields :: [FieldHighlight]
1044− } deriving (Read, Show, Eq, Generic, Typeable)
1045−
1046−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1047− deriving (Read, Show, Eq, Generic, Typeable)
1048−
1049−
1050−data HighlightSettings = Plain PlainHighlight
1051− | Postings PostingsHighlight
1052− | FastVector FastVectorHighlight
1053− deriving (Read, Show, Eq, Generic, Typeable)
1054−data PlainHighlight =
1055− PlainHighlight { plainCommon :: Maybe CommonHighlight
1056− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1057−
1058− -- This requires that index_options are set to 'offset' in the mapping.
1059−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1060−
1061−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1062−data FastVectorHighlight =
1063− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1064− , fvNonPostSettings :: Maybe NonPostings
1065− , boundaryChars :: Maybe Text
1066− , boundaryMaxScan :: Maybe Int
1067− , fragmentOffset :: Maybe Int
1068− , matchedFields :: [Text]
1069− , phraseLimit :: Maybe Int
1070− } deriving (Read, Show, Eq, Generic, Typeable)
1071−
1072−data CommonHighlight =
1073− CommonHighlight { order :: Maybe Text
1074− , forceSource :: Maybe Bool
1075− , tag :: Maybe HighlightTag
1076− , encoder :: Maybe HighlightEncoder
1077− , noMatchSize :: Maybe Int
1078− , highlightQuery :: Maybe Query
1079− , requireFieldMatch :: Maybe Bool
1080− } deriving (Read, Show, Eq, Generic, Typeable)
1081−
1082−-- Settings that are only applicable to FastVector and Plain highlighters.
1083−data NonPostings =
1084− NonPostings { fragmentSize :: Maybe Int
1085− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1086−
1087−data HighlightEncoder = DefaultEncoder
1088− | HTMLEncoder
1089− deriving (Read, Show, Eq, Generic, Typeable)
1090−
1091−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1092−data HighlightTag = TagSchema Text
1093− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1094− deriving (Read, Show, Eq, Generic, Typeable)
1095−
1096−
1097−data Query =
1098− TermQuery Term (Maybe Boost)
1099− | TermsQuery Text (NonEmpty Text)
1100− | QueryMatchQuery MatchQuery
1101− | QueryMultiMatchQuery MultiMatchQuery
1102− | QueryBoolQuery BoolQuery
1103− | QueryBoostingQuery BoostingQuery
1104− | QueryCommonTermsQuery CommonTermsQuery
1105− | ConstantScoreFilter Filter Boost
1106− | ConstantScoreQuery Query Boost
1107− | QueryDisMaxQuery DisMaxQuery
1108− | QueryFilteredQuery FilteredQuery
1109− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1110− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1111− | QueryFuzzyQuery FuzzyQuery
1112− | QueryHasChildQuery HasChildQuery
1113− | QueryHasParentQuery HasParentQuery
1114− | IdsQuery MappingName [DocId]
1115− | QueryIndicesQuery IndicesQuery
1116− | MatchAllQuery (Maybe Boost)
1117− | QueryMoreLikeThisQuery MoreLikeThisQuery
1118− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1119− | QueryNestedQuery NestedQuery
1120− | QueryPrefixQuery PrefixQuery
1121− | QueryQueryStringQuery QueryStringQuery
1122− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1123− | QueryRangeQuery RangeQuery
1124− | QueryRegexpQuery RegexpQuery
1125− deriving (Eq, Read, Show, Generic, Typeable)
1126−
1127−data RegexpQuery =
1128− RegexpQuery { regexpQueryField :: FieldName
1129− , regexpQuery :: Regexp
1130− , regexpQueryFlags :: RegexpFlags
1131− , regexpQueryBoost :: Maybe Boost
1132− } deriving (Eq, Read, Show, Generic, Typeable)
1133−
1134−data RangeQuery =
1135− RangeQuery { rangeQueryField :: FieldName
1136− , rangeQueryRange :: RangeValue
1137− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1138−
1139−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1140−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1141−
1142−data SimpleQueryStringQuery =
1143− SimpleQueryStringQuery
1144− { simpleQueryStringQuery :: QueryString
1145− , simpleQueryStringField :: Maybe FieldOrFields
1146− , simpleQueryStringOperator :: Maybe BooleanOperator
1147− , simpleQueryStringAnalyzer :: Maybe Analyzer
1148− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1149− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1150− , simpleQueryStringLocale :: Maybe Locale
1151− } deriving (Eq, Read, Show, Generic, Typeable)
1152−
1153−data SimpleQueryFlag =
1154− SimpleQueryAll
1155− | SimpleQueryNone
1156− | SimpleQueryAnd
1157− | SimpleQueryOr
1158− | SimpleQueryPrefix
1159− | SimpleQueryPhrase
1160− | SimpleQueryPrecedence
1161− | SimpleQueryEscape
1162− | SimpleQueryWhitespace
1163− | SimpleQueryFuzzy
1164− | SimpleQueryNear
1165− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1166−
1167−-- use_dis_max and tie_breaker when fields are plural?
1168−data QueryStringQuery =
1169− QueryStringQuery
1170− { queryStringQuery :: QueryString
1171− , queryStringDefaultField :: Maybe FieldName
1172− , queryStringOperator :: Maybe BooleanOperator
1173− , queryStringAnalyzer :: Maybe Analyzer
1174− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1175− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1176− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1177− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1178− , queryStringFuzziness :: Maybe Fuzziness
1179− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1180− , queryStringPhraseSlop :: Maybe PhraseSlop
1181− , queryStringBoost :: Maybe Boost
1182− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1183− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1184− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1185− , queryStringLenient :: Maybe Lenient
1186− , queryStringLocale :: Maybe Locale
1187− } deriving (Eq, Read, Show, Generic, Typeable)
1188−
1189−mkQueryStringQuery :: QueryString -> QueryStringQuery
1190−mkQueryStringQuery qs =
1191− QueryStringQuery qs Nothing Nothing
1192− Nothing Nothing Nothing Nothing
1193− Nothing Nothing Nothing Nothing
1194− Nothing Nothing Nothing Nothing
1195− Nothing Nothing
1196−
1197−data FieldOrFields = FofField FieldName
1198− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1199−
1200−data PrefixQuery =
1201− PrefixQuery
1202− { prefixQueryField :: FieldName
1203− , prefixQueryPrefixValue :: Text
1204− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
488+ deriving (Eq, Show)
1205489
1206−data NestedQuery =
1207− NestedQuery
1208− { nestedQueryPath :: QueryPath
1209− , nestedQueryScoreType :: ScoreType
1210− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1211−
1212−data MoreLikeThisFieldQuery =
1213− MoreLikeThisFieldQuery
1214− { moreLikeThisFieldText :: Text
1215− , moreLikeThisFieldFields :: FieldName
1216− -- default 0.3 (30%)
1217− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1218− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1219− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1220− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1221− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1222− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1223− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1224− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1225− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1226− , moreLikeThisFieldBoost :: Maybe Boost
1227− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1228− } deriving (Eq, Read, Show, Generic, Typeable)
1229−
1230−data MoreLikeThisQuery =
1231− MoreLikeThisQuery
1232− { moreLikeThisText :: Text
1233− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1234− -- default 0.3 (30%)
1235− , moreLikeThisPercentMatch :: Maybe PercentMatch
1236− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1237− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1238− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1239− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1240− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1241− , moreLikeThisMinWordLength :: Maybe MinWordLength
1242− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1243− , moreLikeThisBoostTerms :: Maybe BoostTerms
1244− , moreLikeThisBoost :: Maybe Boost
1245− , moreLikeThisAnalyzer :: Maybe Analyzer
1246− } deriving (Eq, Read, Show, Generic, Typeable)
1247−
1248−data IndicesQuery =
1249− IndicesQuery
1250− { indicesQueryIndices :: [IndexName]
1251− , indicesQuery :: Query
1252− -- default "all"
1253− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1254−
1255−data HasParentQuery =
1256− HasParentQuery
1257− { hasParentQueryType :: TypeName
1258− , hasParentQuery :: Query
1259− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1260−
1261−data HasChildQuery =
1262− HasChildQuery
1263− { hasChildQueryType :: TypeName
1264− , hasChildQuery :: Query
1265− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1266−
1267−data ScoreType =
1268− ScoreTypeMax
1269− | ScoreTypeSum
1270− | ScoreTypeAvg
1271− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1272−
1273−data FuzzyQuery =
1274− FuzzyQuery { fuzzyQueryField :: FieldName
1275− , fuzzyQueryValue :: Text
1276− , fuzzyQueryPrefixLength :: PrefixLength
1277− , fuzzyQueryMaxExpansions :: MaxExpansions
1278− , fuzzyQueryFuzziness :: Fuzziness
1279− , fuzzyQueryBoost :: Maybe Boost
1280− } deriving (Eq, Read, Show, Generic, Typeable)
1281−
1282−data FuzzyLikeFieldQuery =
1283− FuzzyLikeFieldQuery
1284− { fuzzyLikeField :: FieldName
1285− -- anaphora is good for the soul.
1286− , fuzzyLikeFieldText :: Text
1287− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1288− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1289− , fuzzyLikeFieldFuzziness :: Fuzziness
1290− , fuzzyLikeFieldPrefixLength :: PrefixLength
1291− , fuzzyLikeFieldBoost :: Boost
1292− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1293− } deriving (Eq, Read, Show, Generic, Typeable)
1294−
1295−data FuzzyLikeThisQuery =
1296− FuzzyLikeThisQuery
1297− { fuzzyLikeFields :: [FieldName]
1298− , fuzzyLikeText :: Text
1299− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1300− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1301− , fuzzyLikeFuzziness :: Fuzziness
1302− , fuzzyLikePrefixLength :: PrefixLength
1303− , fuzzyLikeBoost :: Boost
1304− , fuzzyLikeAnalyzer :: Maybe Analyzer
1305− } deriving (Eq, Read, Show, Generic, Typeable)
1306−
1307−data FilteredQuery =
1308− FilteredQuery
1309− { filteredQuery :: Query
1310− , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1311−
1312−data DisMaxQuery =
1313− DisMaxQuery { disMaxQueries :: [Query]
1314− -- default 0.0
1315− , disMaxTiebreaker :: Tiebreaker
1316− , disMaxBoost :: Maybe Boost
1317− } deriving (Eq, Read, Show, Generic, Typeable)
1318−
1319−data MatchQuery =
1320− MatchQuery { matchQueryField :: FieldName
1321− , matchQueryQueryString :: QueryString
1322− , matchQueryOperator :: BooleanOperator
1323− , matchQueryZeroTerms :: ZeroTermsQuery
1324− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1325− , matchQueryMatchType :: Maybe MatchQueryType
1326− , matchQueryAnalyzer :: Maybe Analyzer
1327− , matchQueryMaxExpansions :: Maybe MaxExpansions
1328− , matchQueryLenient :: Maybe Lenient
1329− , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1330−
1331−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1332− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1333−-}
1334−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1335−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1336−
1337−data MatchQueryType =
1338− MatchPhrase
1339− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1340−
1341−data MultiMatchQuery =
1342− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1343− , multiMatchQueryString :: QueryString
1344− , multiMatchQueryOperator :: BooleanOperator
1345− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1346− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1347− , multiMatchQueryType :: Maybe MultiMatchQueryType
1348− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1349− , multiMatchQueryAnalyzer :: Maybe Analyzer
1350− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1351− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1352−
1353−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1354− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1355− make a 'MultiMatchQuery'.
1356−-}
1357−
1358−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1359−mkMultiMatchQuery matchFields query =
1360− MultiMatchQuery matchFields query
1361− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1362−
1363−data MultiMatchQueryType =
1364− MultiMatchBestFields
1365− | MultiMatchMostFields
1366− | MultiMatchCrossFields
1367− | MultiMatchPhrase
1368− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1369−
1370−data BoolQuery =
1371− BoolQuery { boolQueryMustMatch :: [Query]
1372− , boolQueryMustNotMatch :: [Query]
1373− , boolQueryShouldMatch :: [Query]
1374− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1375− , boolQueryBoost :: Maybe Boost
1376− , boolQueryDisableCoord :: Maybe DisableCoord
1377− } deriving (Eq, Read, Show, Generic, Typeable)
1378−
1379−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1380−mkBoolQuery must mustNot should =
1381− BoolQuery must mustNot should Nothing Nothing Nothing
1382−
1383−data BoostingQuery =
1384− BoostingQuery { positiveQuery :: Query
1385− , negativeQuery :: Query
1386− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1387−
1388−data CommonTermsQuery =
1389− CommonTermsQuery { commonField :: FieldName
1390− , commonQuery :: QueryString
1391− , commonCutoffFrequency :: CutoffFrequency
1392− , commonLowFreqOperator :: BooleanOperator
1393− , commonHighFreqOperator :: BooleanOperator
1394− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1395− , commonBoost :: Maybe Boost
1396− , commonAnalyzer :: Maybe Analyzer
1397− , commonDisableCoord :: Maybe DisableCoord
1398− } deriving (Eq, Read, Show, Generic, Typeable)
1399−
1400−data CommonMinimumMatch =
1401− CommonMinimumMatchHighLow MinimumMatchHighLow
1402− | CommonMinimumMatch MinimumMatch
1403− deriving (Eq, Read, Show, Generic, Typeable)
1404−
1405−data MinimumMatchHighLow =
1406− MinimumMatchHighLow { lowFreq :: MinimumMatch
1407− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1408−
1409−data Filter = AndFilter [Filter] Cache
1410− | OrFilter [Filter] Cache
1411− | NotFilter Filter Cache
1412− | IdentityFilter
1413− | BoolFilter BoolMatch
1414− | ExistsFilter FieldName -- always cached
1415− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1416− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1417− | GeoDistanceRangeFilter GeoPoint DistanceRange
1418− | GeoPolygonFilter FieldName [LatLon]
1419− | IdsFilter MappingName [DocId]
1420− | LimitFilter Int
1421− | MissingFilter FieldName Existence NullValue
1422− | PrefixFilter FieldName PrefixValue Cache
1423− | QueryFilter Query Cache
1424− | RangeFilter FieldName RangeValue RangeExecution Cache
1425− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1426− | TermFilter Term Cache
1427− deriving (Eq, Read, Show, Generic, Typeable)
1428−
1429−data ZeroTermsQuery = ZeroTermsNone
1430− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1431−
1432−data RangeExecution = RangeExecutionIndex
1433− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1434−
1435−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1436−
1437−data RegexpFlags = AllRegexpFlags
1438− | NoRegexpFlags
1439− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1440−
1441−data RegexpFlag = AnyString
1442− | Automaton
1443− | Complement
1444− | Empty
1445− | Intersection
1446− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1447−
1448−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1449−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1450−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1451−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1452−
1453−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1454−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1455−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1456−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1457−
1458−data RangeValue = RangeDateLte LessThanEqD
1459− | RangeDateLt LessThanD
1460− | RangeDateGte GreaterThanEqD
1461− | RangeDateGt GreaterThanD
1462− | RangeDateGtLt GreaterThanD LessThanD
1463− | RangeDateGteLte GreaterThanEqD LessThanEqD
1464− | RangeDateGteLt GreaterThanEqD LessThanD
1465− | RangeDateGtLte GreaterThanD LessThanEqD
1466− | RangeDoubleLte LessThanEq
1467− | RangeDoubleLt LessThan
1468− | RangeDoubleGte GreaterThanEq
1469− | RangeDoubleGt GreaterThan
1470− | RangeDoubleGtLt GreaterThan LessThan
1471− | RangeDoubleGteLte GreaterThanEq LessThanEq
1472− | RangeDoubleGteLt GreaterThanEq LessThan
1473− | RangeDoubleGtLte GreaterThan LessThanEq
1474− deriving (Eq, Read, Show, Generic, Typeable)
1475−
1476−rangeValueToPair :: RangeValue -> [Pair]
1477−rangeValueToPair rv = case rv of
1478− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1479− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1480− RangeDateLt (LessThanD t) -> ["lt" .= t]
1481− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1482− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1483− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1484− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1485− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1486− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1487− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1488− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1489− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1490− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1491− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1492− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1493− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1494−
1495−data Term = Term { termField :: Text
1496− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1497−
1498−data BoolMatch = MustMatch Term Cache
1499− | MustNotMatch Term Cache
1500− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1501−
1502−-- "memory" or "indexed"
1503−data GeoFilterType = GeoFilterMemory
1504− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1505−
1506−data LatLon = LatLon { lat :: Double
1507− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1508−
1509−data GeoBoundingBox =
1510− GeoBoundingBox { topLeft :: LatLon
1511− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
490+instance ToJSON Source where
491+ toJSON NoSource = toJSON False
492+ toJSON (SourcePatterns patterns) = toJSON patterns
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1512494
1513−data GeoBoundingBoxConstraint =
1514− GeoBoundingBoxConstraint { geoBBField :: FieldName
1515− , constraintBox :: GeoBoundingBox
1516− , bbConstraintcache :: Cache
1517− , geoType :: GeoFilterType
1518− } deriving (Eq, Read, Show, Generic, Typeable)
495+data PatternOrPatterns = PopPattern Pattern
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1519497
1520−data GeoPoint =
1521− GeoPoint { geoField :: FieldName
1522− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
498+instance ToJSON PatternOrPatterns where
499+ toJSON (PopPattern pattern) = toJSON pattern
500+ toJSON (PopPatterns patterns) = toJSON patterns
1523501
1524−data DistanceUnit = Miles
1525− | Yards
1526− | Feet
1527− | Inches
1528− | Kilometers
1529− | Meters
1530− | Centimeters
1531− | Millimeters
1532− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1533504
1534−data DistanceType = Arc
1535− | SloppyArc -- doesn't exist <1.0
1536− | Plane deriving (Eq, Read, Show, Generic, Typeable)
505+instance ToJSON Include where
506+ toJSON (Include patterns) = toJSON patterns
1537507
1538−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1539− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
508+instance ToJSON Exclude where
509+ toJSON (Exclude patterns) = toJSON patterns
1540510
1541−data Distance =
1542− Distance { coefficient :: Double
1543− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1544512
1545−data DistanceRange =
1546− DistanceRange { distanceFrom :: Distance
1547− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
513+instance ToJSON Pattern where
514+ toJSON (Pattern pattern) = toJSON pattern
1548515
1549516data SearchResult a =
1550517 SearchResult { took :: Int
@@ -1552,2058 +519,12 @@ data SearchResult a =
1552519 , shards :: ShardResult
1553520 , searchHits :: SearchHits a
1554521 , aggregations :: Maybe AggregationResults
1555− , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
1556−
1557−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
1558−
1559−type Score = Maybe Double
1560−
1561−data SearchHits a =
1562− SearchHits { hitsTotal :: Int
1563− , maxScore :: Score
1564− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1565−
1566−
1567−instance Monoid (SearchHits a) where
1568− mempty = SearchHits 0 Nothing mempty
1569− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1570− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1571−
1572−
1573−data Hit a =
1574− Hit { hitIndex :: IndexName
1575− , hitType :: MappingName
1576− , hitDocId :: DocId
1577− , hitScore :: Score
1578− , hitSource :: Maybe a
1579− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1580−
1581−data ShardResult =
1582− ShardResult { shardTotal :: Int
1583− , shardsSuccessful :: Int
1584− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1585−
1586−type HitHighlight = M.Map Text [Text]
1587−
1588−showText :: Show a => a -> Text
1589−showText = T.pack . show
1590−
1591−readMay :: Read a => String -> Maybe a
1592−readMay s = case reads s of
1593− (a, ""):_ -> Just a
1594− _ -> Nothing
1595−
1596−parseReadText :: Read a => Text -> Parser a
1597−parseReadText = maybe mzero return . readMay . T.unpack
1598−
1599−type Aggregations = M.Map Text Aggregation
1600−
1601−emptyAggregations :: Aggregations
1602−emptyAggregations = M.empty
1603−
1604−mkAggregations :: Text -> Aggregation -> Aggregations
1605−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1606−
1607−data TermOrder = TermOrder{ termSortField :: Text
1608− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1609−
1610−data TermInclusion = TermInclusion Text
1611− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1612−
1613−data CollectionMode = BreadthFirst
1614− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1615−
1616−data ExecutionHint = Ordinals
1617− | GlobalOrdinals
1618− | GlobalOrdinalsHash
1619− | GlobalOrdinalsLowCardinality
1620− | Map deriving (Eq, Read, Show, Generic, Typeable)
1621−
1622−data TimeInterval = Weeks
1623− | Days
1624− | Hours
1625− | Minutes
1626− | Seconds deriving Eq
1627−
1628−data Interval = Year
1629− | Quarter
1630− | Month
1631− | Week
1632− | Day
1633− | Hour
1634− | Minute
1635− | Second
1636− | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1637−
1638−data Aggregation = TermsAgg TermsAggregation
1639− | DateHistogramAgg DateHistogramAggregation
1640− | ValueCountAgg ValueCountAggregation
1641− | FilterAgg FilterAggregation
1642− | DateRangeAgg DateRangeAggregation
1643− | MissingAgg MissingAggregation deriving (Eq, Read, Show, Generic, Typeable)
1644−
1645−data MissingAggregation = MissingAggregation
1646− { maField :: Text
1647− } deriving (Eq, Read, Show, Generic, Typeable)
1648−
1649−data TermsAggregation = TermsAggregation { term :: Either Text Text
1650− , termInclude :: Maybe TermInclusion
1651− , termExclude :: Maybe TermInclusion
1652− , termOrder :: Maybe TermOrder
1653− , termMinDocCount :: Maybe Int
1654− , termSize :: Maybe Int
1655− , termShardSize :: Maybe Int
1656− , termCollectMode :: Maybe CollectionMode
1657− , termExecutionHint :: Maybe ExecutionHint
1658− , termAggs :: Maybe Aggregations
1659− } deriving (Eq, Read, Show, Generic, Typeable)
1660−
1661−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1662− , dateInterval :: Interval
1663− , dateFormat :: Maybe Text
1664− -- pre and post deprecated in 1.5
1665− , datePreZone :: Maybe Text
1666− , datePostZone :: Maybe Text
1667− , datePreOffset :: Maybe Text
1668− , datePostOffset :: Maybe Text
1669− , dateAggs :: Maybe Aggregations
1670− } deriving (Eq, Read, Show, Generic, Typeable)
1671−
1672−
1673−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1674− , draFormat :: Maybe Text
1675− , draRanges :: NonEmpty DateRangeAggRange
1676− } deriving (Eq, Read, Show, Generic, Typeable)
1677−
1678−data DateRangeAggRange = DateRangeFrom DateMathExpr
1679− | DateRangeTo DateMathExpr
1680− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1681−
1682−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1683−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1684−
1685−
1686−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1687−data DateMathAnchor = DMNow
1688− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1689−
1690−data DateMathModifier = AddTime Int DateMathUnit
1691− | SubtractTime Int DateMathUnit
1692− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1693−
1694−data DateMathUnit = DMYear
1695− | DMMonth
1696− | DMWeek
1697− | DMDay
1698− | DMHour
1699− | DMMinute
1700− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1701−
1702−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1703−data ValueCountAggregation = FieldValueCount FieldName
1704− | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1705−
1706−-- | 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.
1707−data FilterAggregation = FilterAggregation { faFilter :: Filter
1708− , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1709−
1710−mkTermsAggregation :: Text -> TermsAggregation
1711−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1712−
1713−mkTermsScriptAggregation :: Text -> TermsAggregation
1714−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1715−
1716−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1717−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1718−
1719−instance ToJSON Version where
1720− toJSON Version {..} = object ["number" .= number
1721− ,"build_hash" .= build_hash
1722− ,"build_timestamp" .= build_timestamp
1723− ,"build_snapshot" .= build_snapshot
1724− ,"lucene_version" .= lucene_version]
1725−
1726−instance FromJSON Version where
1727− parseJSON = withObject "Version" parse
1728− where parse o = Version
1729− <$> o .: "number"
1730− <*> o .: "build_hash"
1731− <*> o .: "build_timestamp"
1732− <*> o .: "build_snapshot"
1733− <*> o .: "lucene_version"
1734−
1735−instance ToJSON TermOrder where
1736− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1737−
1738−instance ToJSON TermInclusion where
1739− toJSON (TermInclusion x) = toJSON x
1740− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1741− "flags" .= flags]
1742−
1743−instance ToJSON CollectionMode where
1744− toJSON BreadthFirst = "breadth_first"
1745− toJSON DepthFirst = "depth_first"
1746−
1747−instance ToJSON ExecutionHint where
1748− toJSON Ordinals = "ordinals"
1749− toJSON GlobalOrdinals = "global_ordinals"
1750− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1751− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1752− toJSON Map = "map"
1753−
1754−instance ToJSON Interval where
1755− toJSON Year = "year"
1756− toJSON Quarter = "quarter"
1757− toJSON Month = "month"
1758− toJSON Week = "week"
1759− toJSON Day = "day"
1760− toJSON Hour = "hour"
1761− toJSON Minute = "minute"
1762− toJSON Second = "second"
1763− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1764−
1765−instance Show TimeInterval where
1766− show Weeks = "w"
1767− show Days = "d"
1768− show Hours = "h"
1769− show Minutes = "m"
1770− show Seconds = "s"
1771−
1772−instance Read TimeInterval where
1773− readPrec = f =<< TR.get
1774− where
1775− f 'w' = return Weeks
1776− f 'd' = return Days
1777− f 'h' = return Hours
1778− f 'm' = return Minutes
1779− f 's' = return Seconds
1780− f _ = fail "TimeInterval expected one of w, d, h, m, s"
1781−
1782−instance ToJSON Aggregation where
1783− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1784− omitNulls ["terms" .= omitNulls [ toJSON' term,
1785− "include" .= include,
1786− "exclude" .= exclude,
1787− "order" .= order,
1788− "min_doc_count" .= minDocCount,
1789− "size" .= size,
1790− "shard_size" .= shardSize,
1791− "collect_mode" .= collectMode,
1792− "execution_hint" .= executionHint
1793− ],
1794− "aggs" .= termAggs ]
1795− where
1796− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1797−
1798− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1799− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1800− "interval" .= interval,
1801− "format" .= format,
1802− "pre_zone" .= preZone,
1803− "post_zone" .= postZone,
1804− "pre_offset" .= preOffset,
1805− "post_offset" .= postOffset
1806− ],
1807− "aggs" .= dateHistoAggs ]
1808− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1809− where v = case a of
1810− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1811− (ScriptValueCount (Script s)) -> object ["script" .= s]
1812− toJSON (FilterAgg (FilterAggregation filt ags)) =
1813− omitNulls [ "filter" .= filt
1814− , "aggs" .= ags]
1815− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1816− ]
1817− toJSON (MissingAgg (MissingAggregation{..})) =
1818− object ["missing" .= object ["field" .= maField]]
1819−
1820−instance ToJSON DateRangeAggregation where
1821− toJSON DateRangeAggregation {..} =
1822− omitNulls [ "field" .= draField
1823− , "format" .= draFormat
1824− , "ranges" .= toList draRanges
1825− ]
1826−
1827−instance ToJSON DateRangeAggRange where
1828− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1829− toJSON (DateRangeTo e) = object [ "to" .= e ]
1830− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1831−
1832−instance ToJSON DateMathExpr where
1833− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1834− where fmtA DMNow = "now"
1835− fmtA (DMDate date) = case toGregorian date of
1836− (y,m,d) -> showText y <> "-" <>
1837− showText m <> "-" <>
1838− showText d <> "||"
1839− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1840− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1841− fmtMod (RoundDownTo u) = "/" <> fmtU u
1842− fmtU DMYear = "y"
1843− fmtU DMMonth = "M"
1844− fmtU DMWeek = "w"
1845− fmtU DMDay = "d"
1846− fmtU DMHour = "h"
1847− fmtU DMMinute = "m"
1848− fmtU DMSecond = "s"
1849−
1850−
1851−type AggregationResults = M.Map Text Value
1852−
1853−class BucketAggregation a where
1854− key :: a -> BucketValue
1855− docCount :: a -> Int
1856− aggs :: a -> Maybe AggregationResults
1857−
1858−
1859−data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1860−
1861−data BucketValue = TextValue Text
1862− | ScientificValue Scientific
1863− | BoolValue Bool deriving (Read, Show)
1864−
1865−data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1866−
1867−data TermsResult = TermsResult { termKey :: BucketValue
1868− , termsDocCount :: Int
1869− , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1870−
1871−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1872− , dateKeyStr :: Maybe Text
1873− , dateDocCount :: Int
1874− , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1875−
1876−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1877− , dateRangeFrom :: Maybe UTCTime
1878− , dateRangeFromAsString :: Maybe Text
1879− , dateRangeTo :: Maybe UTCTime
1880− , dateRangeToAsString :: Maybe Text
1881− , dateRangeDocCount :: Int
1882− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1883−
1884−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1885−toTerms = toAggResult
1886−
1887−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1888−toDateHistogram = toAggResult
1889−
1890−toMissing :: Text -> AggregationResults -> Maybe MissingResult
1891−toMissing = toAggResult
1892−
1893−toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1894−toAggResult t a = M.lookup t a >>= deserialize
1895− where deserialize = parseMaybe parseJSON
1896−
1897−instance BucketAggregation TermsResult where
1898− key = termKey
1899− docCount = termsDocCount
1900− aggs = termsAggs
1901−
1902−instance BucketAggregation DateHistogramResult where
1903− key = TextValue . showText . dateKey
1904− docCount = dateDocCount
1905− aggs = dateHistogramAggs
1906−
1907−instance BucketAggregation DateRangeResult where
1908− key = TextValue . dateRangeKey
1909− docCount = dateRangeDocCount
1910− aggs = dateRangeAggs
1911−
1912−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1913− parseJSON (Object v) = Bucket <$>
1914− v .: "buckets"
1915− parseJSON _ = mempty
1916−
1917−instance FromJSON BucketValue where
1918− parseJSON (String t) = return $ TextValue t
1919− parseJSON (Number s) = return $ ScientificValue s
1920− parseJSON (Bool b) = return $ BoolValue b
1921− parseJSON _ = mempty
1922−
1923−instance FromJSON MissingResult where
1924− parseJSON = withObject "MissingResult" parse
1925− where parse v = MissingResult <$> v .: "doc_count"
1926−
1927−instance FromJSON TermsResult where
1928− parseJSON (Object v) = TermsResult <$>
1929− v .: "key" <*>
1930− v .: "doc_count" <*>
1931− v .:? "aggregations"
1932− parseJSON _ = mempty
1933−
1934−instance FromJSON DateHistogramResult where
1935− parseJSON (Object v) = DateHistogramResult <$>
1936− v .: "key" <*>
1937− v .:? "key_as_string" <*>
1938− v .: "doc_count" <*>
1939− v .:? "aggregations"
1940− parseJSON _ = mempty
1941−
1942−instance FromJSON DateRangeResult where
1943− parseJSON = withObject "DateRangeResult" parse
1944− where parse v = DateRangeResult <$>
1945− v .: "key" <*>
1946− (fmap posixMS <$> v .:? "from") <*>
1947− v .:? "from_as_string" <*>
1948− (fmap posixMS <$> v .:? "to") <*>
1949− v .:? "to_as_string" <*>
1950− v .: "doc_count" <*>
1951− v .:? "aggregations"
1952−
1953−instance FromJSON POSIXMS where
1954− parseJSON = withScientific "POSIXMS" (return . parse)
1955− where parse n = let n' = truncate n :: Integer
1956− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1957−
1958−instance Monoid Filter where
1959− mempty = IdentityFilter
1960− mappend a b = AndFilter [a, b] defaultCache
1961−
1962−instance Seminearring Filter where
1963− a <||> b = OrFilter [a, b] defaultCache
1964−
1965−instance ToJSON Filter where
1966− toJSON (AndFilter filters cache) =
1967− object ["and" .=
1968− object [ "filters" .= fmap toJSON filters
1969− , "_cache" .= cache]]
1970−
1971− toJSON (OrFilter filters cache) =
1972− object ["or" .=
1973− object [ "filters" .= fmap toJSON filters
1974− , "_cache" .= cache]]
1975−
1976− toJSON (NotFilter notFilter cache) =
1977− object ["not" .=
1978− object ["filter" .= notFilter
1979− , "_cache" .= cache]]
1980−
1981− toJSON (IdentityFilter) =
1982− object ["match_all" .= object []]
1983−
1984− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1985− object ["term" .= object base]
1986− where base = [termFilterField .= termFilterValue,
1987− "_cache" .= cache]
1988−
1989− toJSON (ExistsFilter (FieldName fieldName)) =
1990− object ["exists" .= object
1991− ["field" .= fieldName]]
1992−
1993− toJSON (BoolFilter boolMatch) =
1994− object ["bool" .= boolMatch]
1995−
1996− toJSON (GeoBoundingBoxFilter bbConstraint) =
1997− object ["geo_bounding_box" .= bbConstraint]
1998−
1999− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2000− distance distanceType optimizeBbox cache) =
2001− object ["geo_distance" .=
2002− object ["distance" .= distance
2003− , "distance_type" .= distanceType
2004− , "optimize_bbox" .= optimizeBbox
2005− , distanceGeoField .= geoDistLatLon
2006− , "_cache" .= cache]]
2007−
2008− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2009− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2010− object ["geo_distance_range" .=
2011− object ["from" .= geoDistRangeDistFrom
2012− , "to" .= drDistanceTo
2013− , gddrField .= drLatLon]]
2014−
2015− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2016− object ["geo_polygon" .=
2017− object [geoPolygonFilterField .=
2018− object ["points" .= fmap toJSON latLons]]]
2019−
2020− toJSON (IdsFilter (MappingName mappingName) values) =
2021− object ["ids" .=
2022− object ["type" .= mappingName
2023− , "values" .= fmap unpackId values]]
2024−
2025− toJSON (LimitFilter limit) =
2026− object ["limit" .= object ["value" .= limit]]
2027−
2028− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2029− object ["missing" .=
2030− object ["field" .= fieldName
2031− , "existence" .= existence
2032− , "null_value" .= nullValue]]
2033−
2034− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2035− object ["prefix" .=
2036− object [fieldName .= fieldValue
2037− , "_cache" .= cache]]
2038−
2039− toJSON (QueryFilter query False) =
2040− object ["query" .= toJSON query ]
2041− toJSON (QueryFilter query True) =
2042− object ["fquery" .=
2043− object [ "query" .= toJSON query
2044− , "_cache" .= True ]]
2045−
2046− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2047− object ["range" .=
2048− object [ fieldName .= object (rangeValueToPair rangeValue)
2049− , "execution" .= rangeExecution
2050− , "_cache" .= cache]]
2051−
2052− toJSON (RegexpFilter (FieldName fieldName)
2053− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2054− object ["regexp" .=
2055− object [fieldName .=
2056− object ["value" .= regexText
2057− , "flags" .= flags]
2058− , "_name" .= cacheName
2059− , "_cache" .= cache
2060− , "_cache_key" .= cacheKey]]
2061−
2062−instance FromJSON Filter where
2063− parseJSON = withObject "Filter" parse
2064− where parse o = andFilter `taggedWith` "and"
2065− <|> orFilter `taggedWith` "or"
2066− <|> notFilter `taggedWith` "not"
2067− <|> identityFilter `taggedWith` "match_all"
2068− <|> boolFilter `taggedWith` "bool"
2069− <|> existsFilter `taggedWith` "exists"
2070− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2071− <|> geoDistanceFilter `taggedWith` "geo_distance"
2072− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2073− <|> geoPolygonFilter `taggedWith` "geo_polygon"
2074− <|> idsFilter `taggedWith` "ids"
2075− <|> limitFilter `taggedWith` "limit"
2076− <|> missingFilter `taggedWith` "missing"
2077− <|> prefixFilter `taggedWith` "prefix"
2078− <|> queryFilter `taggedWith` "query"
2079− <|> fqueryFilter `taggedWith` "fquery"
2080− <|> rangeFilter `taggedWith` "range"
2081− <|> regexpFilter `taggedWith` "regexp"
2082− <|> termFilter `taggedWith` "term"
2083− where taggedWith parser k = parser =<< o .: k
2084− andFilter o = AndFilter <$> o .: "filters"
2085− <*> o .:? "_cache" .!= defaultCache
2086− orFilter o = OrFilter <$> o .: "filters"
2087− <*> o .:? "_cache" .!= defaultCache
2088− notFilter o = NotFilter <$> o .: "filter"
2089− <*> o .: "_cache" .!= defaultCache
2090− identityFilter :: Object -> Parser Filter
2091− identityFilter m
2092− | HM.null m = pure IdentityFilter
2093− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2094− boolFilter = pure . BoolFilter
2095− existsFilter o = ExistsFilter <$> o .: "field"
2096− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2097− geoDistanceFilter o = do
2098− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2099− [(fn, v)] -> do
2100− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2101− GeoDistanceFilter gp <$> o .: "distance"
2102− <*> o .: "distance_type"
2103− <*> o .: "optimize_bbox"
2104− <*> o .:? "_cache" .!= defaultCache
2105− _ -> fail "Could not find GeoDistanceFilter field name"
2106− geoDistanceRangeFilter o = do
2107− case HM.toList (deleteSeveral ["from", "to"] o) of
2108− [(fn, v)] -> do
2109− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2110− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2111− return (GeoDistanceRangeFilter gp rng)
2112− _ -> fail "Could not find GeoDistanceRangeFilter field name"
2113− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2114− idsFilter o = IdsFilter <$> o .: "type"
2115− <*> o .: "values"
2116− limitFilter o = LimitFilter <$> o .: "value"
2117− missingFilter o = MissingFilter <$> o .: "field"
2118− <*> o .: "existence"
2119− <*> o .: "null_value"
2120− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2121− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2122− _ -> fail "Could not parse PrefixFilter"
2123−
2124− queryFilter q = pure (QueryFilter q False)
2125− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2126− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2127− [(fn, v)] -> RangeFilter (FieldName fn)
2128− <$> parseJSON v
2129− <*> o .: "execution"
2130− <*> o .:? "_cache" .!= defaultCache
2131− _ -> fail "Could not find field name for RangeFilter"
2132− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2133− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2134− <$> o' .: "value"
2135− <*> o' .: "flags"
2136− <*> o .: "_name"
2137− <*> o .:? "_cache" .!= defaultCache
2138− <*> o .: "_cache_key"
2139− _ -> fail "Could not find field name for RegexpFilter"
2140− termFilter o = case HM.toList (HM.delete "_cache" o) of
2141− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2142− <$> o .:? "_cache" .!= defaultCache
2143− _ -> fail "Could not find term field for TermFilter"
2144−
2145−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2146−fieldTagged f o = case HM.toList o of
2147− [(k, Object o')] -> f (FieldName k) o'
2148− _ -> fail "Expected object with 1 field-named key"
2149−
2150−instance ToJSON GeoPoint where
2151− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2152− object [ geoPointField .= geoPointLatLon ]
2153−
2154−
2155−instance ToJSON Query where
2156− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2157− object [ "term" .=
2158− object [termQueryField .= object merged]]
2159− where
2160− base = [ "value" .= termQueryValue ]
2161− boosted = maybe [] (return . ("boost" .=)) boost
2162− merged = mappend base boosted
2163−
2164− toJSON (TermsQuery fieldName terms) =
2165− object [ "terms" .= object conjoined ]
2166− where conjoined = [fieldName .= terms]
2167−
2168− toJSON (IdsQuery idsQueryMappingName docIds) =
2169− object [ "ids" .= object conjoined ]
2170− where conjoined = [ "type" .= idsQueryMappingName
2171− , "values" .= fmap toJSON docIds ]
2172−
2173− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2174− object [ "query_string" .= qQueryStringQuery ]
2175−
2176− toJSON (QueryMatchQuery matchQuery) =
2177− object [ "match" .= matchQuery ]
2178−
2179− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2180− toJSON multiMatchQuery
2181−
2182− toJSON (QueryBoolQuery boolQuery) =
2183− object [ "bool" .= boolQuery ]
2184−
2185− toJSON (QueryBoostingQuery boostingQuery) =
2186− object [ "boosting" .= boostingQuery ]
2187−
2188− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2189− object [ "common" .= commonTermsQuery ]
2190−
2191− toJSON (ConstantScoreFilter csFilter boost) =
2192− object ["constant_score" .= object ["filter" .= csFilter
2193− , "boost" .= boost]]
2194−
2195− toJSON (ConstantScoreQuery query boost) =
2196− object ["constant_score" .= object ["query" .= query
2197− , "boost" .= boost]]
2198−
2199− toJSON (QueryDisMaxQuery disMaxQuery) =
2200− object [ "dis_max" .= disMaxQuery ]
2201−
2202− toJSON (QueryFilteredQuery qFilteredQuery) =
2203− object [ "filtered" .= qFilteredQuery ]
2204−
2205− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2206− object [ "fuzzy_like_this" .= fuzzyQuery ]
2207−
2208− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2209− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2210−
2211− toJSON (QueryFuzzyQuery fuzzyQuery) =
2212− object [ "fuzzy" .= fuzzyQuery ]
2213−
2214− toJSON (QueryHasChildQuery childQuery) =
2215− object [ "has_child" .= childQuery ]
2216−
2217− toJSON (QueryHasParentQuery parentQuery) =
2218− object [ "has_parent" .= parentQuery ]
2219−
2220− toJSON (QueryIndicesQuery qIndicesQuery) =
2221− object [ "indices" .= qIndicesQuery ]
2222−
2223− toJSON (MatchAllQuery boost) =
2224− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2225−
2226− toJSON (QueryMoreLikeThisQuery query) =
2227− object [ "more_like_this" .= query ]
2228−
2229− toJSON (QueryMoreLikeThisFieldQuery query) =
2230− object [ "more_like_this_field" .= query ]
2231−
2232− toJSON (QueryNestedQuery query) =
2233− object [ "nested" .= query ]
2234−
2235− toJSON (QueryPrefixQuery query) =
2236− object [ "prefix" .= query ]
2237−
2238− toJSON (QueryRangeQuery query) =
2239− object [ "range" .= query ]
2240−
2241− toJSON (QueryRegexpQuery query) =
2242− object [ "regexp" .= query ]
2243−
2244− toJSON (QuerySimpleQueryStringQuery query) =
2245− object [ "simple_query_string" .= query ]
2246−
2247−instance FromJSON Query where
2248− parseJSON v = withObject "Query" parse v
2249− where parse o = termQuery `taggedWith` "term"
2250− <|> termsQuery `taggedWith` "terms"
2251− <|> idsQuery `taggedWith` "ids"
2252− <|> queryQueryStringQuery `taggedWith` "query_string"
2253− <|> queryMatchQuery `taggedWith` "match"
2254− <|> queryMultiMatchQuery
2255− <|> queryBoolQuery `taggedWith` "bool"
2256− <|> queryBoostingQuery `taggedWith` "boosting"
2257− <|> queryCommonTermsQuery `taggedWith` "common"
2258− <|> constantScoreFilter `taggedWith` "constant_score"
2259− <|> constantScoreQuery `taggedWith` "constant_score"
2260− <|> queryDisMaxQuery `taggedWith` "dis_max"
2261− <|> queryFilteredQuery `taggedWith` "filtered"
2262− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2263− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2264− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2265− <|> queryHasChildQuery `taggedWith` "has_child"
2266− <|> queryHasParentQuery `taggedWith` "has_parent"
2267− <|> queryIndicesQuery `taggedWith` "indices"
2268− <|> matchAllQuery `taggedWith` "match_all"
2269− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2270− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2271− <|> queryNestedQuery `taggedWith` "nested"
2272− <|> queryPrefixQuery `taggedWith` "prefix"
2273− <|> queryRangeQuery `taggedWith` "range"
2274− <|> queryRegexpQuery `taggedWith` "regexp"
2275− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2276− where taggedWith parser k = parser =<< o .: k
2277− termQuery = fieldTagged $ \(FieldName fn) o ->
2278− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2279− termsQuery o = case HM.toList o of
2280− [(fn, vs)] -> do vals <- parseJSON vs
2281− case vals of
2282− x:xs -> return (TermsQuery fn (x :| xs))
2283− _ -> fail "Expected non empty list of values"
2284− _ -> fail "Expected object with 1 field-named key"
2285− idsQuery o = IdsQuery <$> o .: "type"
2286− <*> o .: "values"
2287− queryQueryStringQuery = pure . QueryQueryStringQuery
2288− queryMatchQuery = pure . QueryMatchQuery
2289− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2290− queryBoolQuery = pure . QueryBoolQuery
2291− queryBoostingQuery = pure . QueryBoostingQuery
2292− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2293− constantScoreFilter o = case HM.lookup "filter" o of
2294− Just x -> ConstantScoreFilter <$> parseJSON x
2295− <*> o .: "boost"
2296− _ -> fail "Does not appear to be a ConstantScoreFilter"
2297− constantScoreQuery o = case HM.lookup "query" o of
2298− Just x -> ConstantScoreQuery <$> parseJSON x
2299− <*> o .: "boost"
2300− _ -> fail "Does not appear to be a ConstantScoreQuery"
2301− queryDisMaxQuery = pure . QueryDisMaxQuery
2302− queryFilteredQuery = pure . QueryFilteredQuery
2303− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2304− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2305− queryFuzzyQuery = pure . QueryFuzzyQuery
2306− queryHasChildQuery = pure . QueryHasChildQuery
2307− queryHasParentQuery = pure . QueryHasParentQuery
2308− queryIndicesQuery = pure . QueryIndicesQuery
2309− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2310− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2311− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2312− queryNestedQuery = pure . QueryNestedQuery
2313− queryPrefixQuery = pure . QueryPrefixQuery
2314− queryRangeQuery = pure . QueryRangeQuery
2315− queryRegexpQuery = pure . QueryRegexpQuery
2316− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2317−
2318−
2319−omitNulls :: [(Text, Value)] -> Value
2320−omitNulls = object . filter notNull where
2321− notNull (_, Null) = False
2322− notNull (_, Array a) = (not . V.null) a
2323− notNull _ = True
2324−
2325−
2326−instance ToJSON SimpleQueryStringQuery where
2327− toJSON SimpleQueryStringQuery {..} =
2328− omitNulls (base ++ maybeAdd)
2329− where base = [ "query" .= simpleQueryStringQuery ]
2330− maybeAdd = [ "fields" .= simpleQueryStringField
2331− , "default_operator" .= simpleQueryStringOperator
2332− , "analyzer" .= simpleQueryStringAnalyzer
2333− , "flags" .= simpleQueryStringFlags
2334− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2335− , "locale" .= simpleQueryStringLocale ]
2336−
2337−instance FromJSON SimpleQueryStringQuery where
2338− parseJSON = withObject "SimpleQueryStringQuery" parse
2339− where parse o = SimpleQueryStringQuery <$> o .: "query"
2340− <*> o .:? "fields"
2341− <*> o .:? "default_operator"
2342− <*> o .:? "analyzer"
2343− <*> (parseFlags <$> o .:? "flags")
2344− <*> o .:? "lowercase_expanded_terms"
2345− <*> o .:? "locale"
2346− parseFlags (Just (x:xs)) = Just (x :| xs)
2347− parseFlags _ = Nothing
2348−
2349−instance ToJSON FieldOrFields where
2350− toJSON (FofField fieldName) =
2351− toJSON fieldName
2352− toJSON (FofFields fieldNames) =
2353− toJSON fieldNames
2354−
2355−instance FromJSON FieldOrFields where
2356− parseJSON v = FofField <$> parseJSON v
2357− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2358−
2359−instance ToJSON SimpleQueryFlag where
2360− toJSON SimpleQueryAll = "ALL"
2361− toJSON SimpleQueryNone = "NONE"
2362− toJSON SimpleQueryAnd = "AND"
2363− toJSON SimpleQueryOr = "OR"
2364− toJSON SimpleQueryPrefix = "PREFIX"
2365− toJSON SimpleQueryPhrase = "PHRASE"
2366− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2367− toJSON SimpleQueryEscape = "ESCAPE"
2368− toJSON SimpleQueryWhitespace = "WHITESPACE"
2369− toJSON SimpleQueryFuzzy = "FUZZY"
2370− toJSON SimpleQueryNear = "NEAR"
2371− toJSON SimpleQuerySlop = "SLOP"
2372−
2373−instance FromJSON SimpleQueryFlag where
2374− parseJSON = withText "SimpleQueryFlag" parse
2375− where parse "ALL" = pure SimpleQueryAll
2376− parse "NONE" = pure SimpleQueryNone
2377− parse "AND" = pure SimpleQueryAnd
2378− parse "OR" = pure SimpleQueryOr
2379− parse "PREFIX" = pure SimpleQueryPrefix
2380− parse "PHRASE" = pure SimpleQueryPhrase
2381− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2382− parse "ESCAPE" = pure SimpleQueryEscape
2383− parse "WHITESPACE" = pure SimpleQueryWhitespace
2384− parse "FUZZY" = pure SimpleQueryFuzzy
2385− parse "NEAR" = pure SimpleQueryNear
2386− parse "SLOP" = pure SimpleQuerySlop
2387− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2388−
2389−instance ToJSON RegexpQuery where
2390− toJSON (RegexpQuery (FieldName rqQueryField)
2391− (Regexp regexpQueryQuery) rqQueryFlags
2392− rqQueryBoost) =
2393− object [ rqQueryField .= omitNulls base ]
2394− where base = [ "value" .= regexpQueryQuery
2395− , "flags" .= rqQueryFlags
2396− , "boost" .= rqQueryBoost ]
2397−
2398−instance FromJSON RegexpQuery where
2399− parseJSON = withObject "RegexpQuery" parse
2400− where parse = fieldTagged $ \fn o ->
2401− RegexpQuery fn
2402− <$> o .: "value"
2403− <*> o .: "flags"
2404− <*> o .:? "boost"
2405−
2406−instance ToJSON QueryStringQuery where
2407− toJSON (QueryStringQuery qsQueryString
2408− qsDefaultField qsOperator
2409− qsAnalyzer qsAllowWildcard
2410− qsLowercaseExpanded qsEnablePositionIncrements
2411− qsFuzzyMaxExpansions qsFuzziness
2412− qsFuzzyPrefixLength qsPhraseSlop
2413− qsBoost qsAnalyzeWildcard
2414− qsGeneratePhraseQueries qsMinimumShouldMatch
2415− qsLenient qsLocale) =
2416− omitNulls base
2417− where
2418− base = [ "query" .= qsQueryString
2419− , "default_field" .= qsDefaultField
2420− , "default_operator" .= qsOperator
2421− , "analyzer" .= qsAnalyzer
2422− , "allow_leading_wildcard" .= qsAllowWildcard
2423− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2424− , "enable_position_increments" .= qsEnablePositionIncrements
2425− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2426− , "fuzziness" .= qsFuzziness
2427− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2428− , "phrase_slop" .= qsPhraseSlop
2429− , "boost" .= qsBoost
2430− , "analyze_wildcard" .= qsAnalyzeWildcard
2431− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2432− , "minimum_should_match" .= qsMinimumShouldMatch
2433− , "lenient" .= qsLenient
2434− , "locale" .= qsLocale ]
2435−
2436−instance FromJSON QueryStringQuery where
2437− parseJSON = withObject "QueryStringQuery" parse
2438− where parse o = QueryStringQuery
2439− <$> o .: "query"
2440− <*> o .:? "default_field"
2441− <*> o .:? "default_operator"
2442− <*> o .:? "analyzer"
2443− <*> o .:? "allow_leading_wildcard"
2444− <*> o .:? "lowercase_expanded_terms"
2445− <*> o .:? "enable_position_increments"
2446− <*> o .:? "fuzzy_max_expansions"
2447− <*> o .:? "fuzziness"
2448− <*> o .:? "fuzzy_prefix_length"
2449− <*> o .:? "phrase_slop"
2450− <*> o .:? "boost"
2451− <*> o .:? "analyze_wildcard"
2452− <*> o .:? "auto_generate_phrase_queries"
2453− <*> o .:? "minimum_should_match"
2454− <*> o .:? "lenient"
2455− <*> o .:? "locale"
2456−
2457−instance ToJSON RangeQuery where
2458− toJSON (RangeQuery (FieldName fieldName) range boost) =
2459− object [ fieldName .= object conjoined ]
2460− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2461−
2462−instance FromJSON RangeQuery where
2463− parseJSON = withObject "RangeQuery" parse
2464− where parse = fieldTagged $ \fn o ->
2465− RangeQuery fn
2466− <$> parseJSON (Object o)
2467− <*> o .: "boost"
2468−
2469−instance FromJSON RangeValue where
2470− parseJSON = withObject "RangeValue" parse
2471− where parse o = parseDate o
2472− <|> parseDouble o
2473− parseDate o = do lt <- o .:? "lt"
2474− lte <- o .:? "lte"
2475− gt <- o .:? "gt"
2476− gte <- o .:? "gte"
2477− case (lt, lte, gt, gte) of
2478− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2479− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2480− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2481− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2482− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2483− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2484− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2485− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2486− (Nothing, Nothing, Nothing, Nothing) -> mzero
2487− parseDouble o = do lt <- o .:? "lt"
2488− lte <- o .:? "lte"
2489− gt <- o .:? "gt"
2490− gte <- o .:? "gte"
2491− case (lt, lte, gt, gte) of
2492− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2493− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2494− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2495− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2496− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2497− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2498− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2499− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2500− (Nothing, Nothing, Nothing, Nothing) -> mzero
2501−
2502−instance ToJSON PrefixQuery where
2503− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2504− object [ fieldName .= omitNulls base ]
2505− where base = [ "value" .= queryValue
2506− , "boost" .= boost ]
2507−
2508−instance FromJSON PrefixQuery where
2509− parseJSON = withObject "PrefixQuery" parse
2510− where parse = fieldTagged $ \fn o ->
2511− PrefixQuery fn
2512− <$> o .: "value"
2513− <*> o .:? "boost"
2514−
2515−instance ToJSON NestedQuery where
2516− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2517− object [ "path" .= nqPath
2518− , "score_mode" .= nqScoreType
2519− , "query" .= nqQuery ]
2520−
2521−instance FromJSON NestedQuery where
2522− parseJSON = withObject "NestedQuery" parse
2523− where parse o = NestedQuery
2524− <$> o .: "path"
2525− <*> o .: "score_mode"
2526− <*> o .: "query"
2527−
2528−instance ToJSON MoreLikeThisFieldQuery where
2529− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2530− percent mtf mqt stopwords mindf maxdf
2531− minwl maxwl boostTerms boost analyzer) =
2532− object [ fieldName .= omitNulls base ]
2533− where base = [ "like_text" .= text
2534− , "percent_terms_to_match" .= percent
2535− , "min_term_freq" .= mtf
2536− , "max_query_terms" .= mqt
2537− , "stop_words" .= stopwords
2538− , "min_doc_freq" .= mindf
2539− , "max_doc_freq" .= maxdf
2540− , "min_word_length" .= minwl
2541− , "max_word_length" .= maxwl
2542− , "boost_terms" .= boostTerms
2543− , "boost" .= boost
2544− , "analyzer" .= analyzer ]
2545−
2546−instance FromJSON MoreLikeThisFieldQuery where
2547− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2548− where parse = fieldTagged $ \fn o ->
2549− MoreLikeThisFieldQuery
2550− <$> o .: "like_text"
2551− <*> pure fn
2552− <*> o .:? "percent_terms_to_match"
2553− <*> o .:? "min_term_freq"
2554− <*> o .:? "max_query_terms"
2555− -- <*> (optionalNE =<< o .:? "stop_words")
2556− <*> o .:? "stop_words"
2557− <*> o .:? "min_doc_freq"
2558− <*> o .:? "max_doc_freq"
2559− <*> o .:? "min_word_length"
2560− <*> o .:? "max_word_length"
2561− <*> o .:? "boost_terms"
2562− <*> o .:? "boost"
2563− <*> o .:? "analyzer"
2564− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2565−
2566−instance ToJSON MoreLikeThisQuery where
2567− toJSON (MoreLikeThisQuery text fields percent
2568− mtf mqt stopwords mindf maxdf
2569− minwl maxwl boostTerms boost analyzer) =
2570− omitNulls base
2571− where base = [ "like_text" .= text
2572− , "fields" .= fields
2573− , "percent_terms_to_match" .= percent
2574− , "min_term_freq" .= mtf
2575− , "max_query_terms" .= mqt
2576− , "stop_words" .= stopwords
2577− , "min_doc_freq" .= mindf
2578− , "max_doc_freq" .= maxdf
2579− , "min_word_length" .= minwl
2580− , "max_word_length" .= maxwl
2581− , "boost_terms" .= boostTerms
2582− , "boost" .= boost
2583− , "analyzer" .= analyzer ]
2584−
2585−instance FromJSON MoreLikeThisQuery where
2586− parseJSON = withObject "MoreLikeThisQuery" parse
2587− where parse o = MoreLikeThisQuery
2588− <$> o .: "like_text"
2589− -- <*> (optionalNE =<< o .:? "fields")
2590− <*> o .:? "fields"
2591− <*> o .:? "percent_terms_to_match"
2592− <*> o .:? "min_term_freq"
2593− <*> o .:? "max_query_terms"
2594− -- <*> (optionalNE =<< o .:? "stop_words")
2595− <*> o .:? "stop_words"
2596− <*> o .:? "min_doc_freq"
2597− <*> o .:? "max_doc_freq"
2598− <*> o .:? "min_word_length"
2599− <*> o .:? "max_word_length"
2600− <*> o .:? "boost_terms"
2601− <*> o .:? "boost"
2602− <*> o .:? "analyzer"
2603− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2604−
2605−instance ToJSON IndicesQuery where
2606− toJSON (IndicesQuery indices query noMatch) =
2607− omitNulls [ "indices" .= indices
2608− , "no_match_query" .= noMatch
2609− , "query" .= query ]
2610−
2611−instance FromJSON IndicesQuery where
2612− parseJSON = withObject "IndicesQuery" parse
2613− where parse o = IndicesQuery
2614− <$> o .:? "indices" .!= []
2615− <*> o .: "query"
2616− <*> o .:? "no_match_query"
2617−
2618−instance ToJSON HasParentQuery where
2619− toJSON (HasParentQuery queryType query scoreType) =
2620− omitNulls [ "parent_type" .= queryType
2621− , "score_type" .= scoreType
2622− , "query" .= query ]
2623−
2624−instance FromJSON HasParentQuery where
2625− parseJSON = withObject "HasParentQuery" parse
2626− where parse o = HasParentQuery
2627− <$> o .: "parent_type"
2628− <*> o .: "query"
2629− <*> o .:? "score_type"
2630−
2631−instance ToJSON HasChildQuery where
2632− toJSON (HasChildQuery queryType query scoreType) =
2633− omitNulls [ "query" .= query
2634− , "score_type" .= scoreType
2635− , "type" .= queryType ]
2636−
2637−instance FromJSON HasChildQuery where
2638− parseJSON = withObject "HasChildQuery" parse
2639− where parse o = HasChildQuery
2640− <$> o .: "type"
2641− <*> o .: "query"
2642− <*> o .:? "score_type"
2643−
2644−instance ToJSON FuzzyQuery where
2645− toJSON (FuzzyQuery (FieldName fieldName) queryText
2646− prefixLength maxEx fuzziness boost) =
2647− object [ fieldName .= omitNulls base ]
2648− where base = [ "value" .= queryText
2649− , "fuzziness" .= fuzziness
2650− , "prefix_length" .= prefixLength
2651− , "boost" .= boost
2652− , "max_expansions" .= maxEx ]
2653−
2654−instance FromJSON FuzzyQuery where
2655− parseJSON = withObject "FuzzyQuery" parse
2656− where parse = fieldTagged $ \fn o ->
2657− FuzzyQuery fn
2658− <$> o .: "value"
2659− <*> o .: "prefix_length"
2660− <*> o .: "max_expansions"
2661− <*> o .: "fuzziness"
2662− <*> o .:? "boost"
2663−
2664−instance ToJSON FuzzyLikeFieldQuery where
2665− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2666− fieldText maxTerms ignoreFreq fuzziness prefixLength
2667− boost analyzer) =
2668− object [ fieldName .=
2669− omitNulls [ "like_text" .= fieldText
2670− , "max_query_terms" .= maxTerms
2671− , "ignore_tf" .= ignoreFreq
2672− , "fuzziness" .= fuzziness
2673− , "prefix_length" .= prefixLength
2674− , "analyzer" .= analyzer
2675− , "boost" .= boost ]]
2676−
2677−instance FromJSON FuzzyLikeFieldQuery where
2678− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2679− where parse = fieldTagged $ \fn o ->
2680− FuzzyLikeFieldQuery fn
2681− <$> o .: "like_text"
2682− <*> o .: "max_query_terms"
2683− <*> o .: "ignore_tf"
2684− <*> o .: "fuzziness"
2685− <*> o .: "prefix_length"
2686− <*> o .: "boost"
2687− <*> o .:? "analyzer"
2688−
2689−instance ToJSON FuzzyLikeThisQuery where
2690− toJSON (FuzzyLikeThisQuery fields text maxTerms
2691− ignoreFreq fuzziness prefixLength boost analyzer) =
2692− omitNulls base
2693− where base = [ "fields" .= fields
2694− , "like_text" .= text
2695− , "max_query_terms" .= maxTerms
2696− , "ignore_tf" .= ignoreFreq
2697− , "fuzziness" .= fuzziness
2698− , "prefix_length" .= prefixLength
2699− , "analyzer" .= analyzer
2700− , "boost" .= boost ]
2701−
2702−instance FromJSON FuzzyLikeThisQuery where
2703− parseJSON = withObject "FuzzyLikeThisQuery" parse
2704− where parse o = FuzzyLikeThisQuery
2705− <$> o .:? "fields" .!= []
2706− <*> o .: "like_text"
2707− <*> o .: "max_query_terms"
2708− <*> o .: "ignore_tf"
2709− <*> o .: "fuzziness"
2710− <*> o .: "prefix_length"
2711− <*> o .: "boost"
2712− <*> o .:? "analyzer"
2713−
2714−instance ToJSON FilteredQuery where
2715− toJSON (FilteredQuery query fFilter) =
2716− object [ "query" .= query
2717− , "filter" .= fFilter ]
2718−
2719−instance FromJSON FilteredQuery where
2720− parseJSON = withObject "FilteredQuery" parse
2721− where parse o = FilteredQuery
2722− <$> o .: "query"
2723− <*> o .: "filter"
2724−
2725−instance ToJSON DisMaxQuery where
2726− toJSON (DisMaxQuery queries tiebreaker boost) =
2727− omitNulls base
2728− where base = [ "queries" .= queries
2729− , "boost" .= boost
2730− , "tie_breaker" .= tiebreaker ]
2731−
2732−instance FromJSON DisMaxQuery where
2733− parseJSON = withObject "DisMaxQuery" parse
2734− where parse o = DisMaxQuery
2735− <$> o .:? "queries" .!= []
2736− <*> o .: "tie_breaker"
2737− <*> o .:? "boost"
2738−
2739−instance ToJSON CommonTermsQuery where
2740− toJSON (CommonTermsQuery (FieldName fieldName)
2741− (QueryString query) cf lfo hfo msm
2742− boost analyzer disableCoord) =
2743− object [fieldName .= omitNulls base ]
2744− where base = [ "query" .= query
2745− , "cutoff_frequency" .= cf
2746− , "low_freq_operator" .= lfo
2747− , "minimum_should_match" .= msm
2748− , "boost" .= boost
2749− , "analyzer" .= analyzer
2750− , "disable_coord" .= disableCoord
2751− , "high_freq_operator" .= hfo ]
2752−
2753−instance FromJSON CommonTermsQuery where
2754− parseJSON = withObject "CommonTermsQuery" parse
2755− where parse = fieldTagged $ \fn o ->
2756− CommonTermsQuery fn
2757− <$> o .: "query"
2758− <*> o .: "cutoff_frequency"
2759− <*> o .: "low_freq_operator"
2760− <*> o .: "high_freq_operator"
2761− <*> o .:? "minimum_should_match"
2762− <*> o .:? "boost"
2763− <*> o .:? "analyzer"
2764− <*> o .:? "disable_coord"
2765−
2766−instance ToJSON CommonMinimumMatch where
2767− toJSON (CommonMinimumMatch mm) = toJSON mm
2768− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2769− object [ "low_freq" .= lowF
2770− , "high_freq" .= highF ]
2771−
2772−instance FromJSON CommonMinimumMatch where
2773− parseJSON v = parseMinimum v
2774− <|> parseMinimumHighLow v
2775− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2776− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2777− MinimumMatchHighLow
2778− <$> o .: "low_freq"
2779− <*> o .: "high_freq")
2780−
2781−
2782−instance ToJSON BoostingQuery where
2783− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2784− object [ "positive" .= bqPositiveQuery
2785− , "negative" .= bqNegativeQuery
2786− , "negative_boost" .= bqNegativeBoost ]
2787−
2788−instance FromJSON BoostingQuery where
2789− parseJSON = withObject "BoostingQuery" parse
2790− where parse o = BoostingQuery
2791− <$> o .: "positive"
2792− <*> o .: "negative"
2793− <*> o .: "negative_boost"
2794−
2795−instance ToJSON BoolQuery where
2796− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2797− omitNulls base
2798− where base = [ "must" .= mustM
2799− , "must_not" .= notM
2800− , "should" .= shouldM
2801− , "minimum_should_match" .= bqMin
2802− , "boost" .= boost
2803− , "disable_coord" .= disableCoord ]
2804−
2805−instance FromJSON BoolQuery where
2806− parseJSON = withObject "BoolQuery" parse
2807− where parse o = BoolQuery
2808− <$> o .:? "must" .!= []
2809− <*> o .:? "must_not" .!= []
2810− <*> o .:? "should" .!= []
2811− <*> o .:? "minimum_should_match"
2812− <*> o .:? "boost"
2813− <*> o .:? "disable_coord"
2814−
2815−instance ToJSON MatchQuery where
2816− toJSON (MatchQuery (FieldName fieldName)
2817− (QueryString mqQueryString) booleanOperator
2818− zeroTermsQuery cutoffFrequency matchQueryType
2819− analyzer maxExpansions lenient boost) =
2820− object [ fieldName .= omitNulls base ]
2821− where base = [ "query" .= mqQueryString
2822− , "operator" .= booleanOperator
2823− , "zero_terms_query" .= zeroTermsQuery
2824− , "cutoff_frequency" .= cutoffFrequency
2825− , "type" .= matchQueryType
2826− , "analyzer" .= analyzer
2827− , "max_expansions" .= maxExpansions
2828− , "lenient" .= lenient
2829− , "boost" .= boost ]
2830−
2831−instance FromJSON MatchQuery where
2832− parseJSON = withObject "MatchQuery" parse
2833− where parse = fieldTagged $ \fn o ->
2834− MatchQuery fn
2835− <$> o .: "query"
2836− <*> o .: "operator"
2837− <*> o .: "zero_terms_query"
2838− <*> o .:? "cutoff_frequency"
2839− <*> o .:? "type"
2840− <*> o .:? "analyzer"
2841− <*> o .:? "max_expansions"
2842− <*> o .:? "lenient"
2843− <*> o .:? "boost"
2844−
2845−instance ToJSON MultiMatchQuery where
2846− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2847− ztQ tb mmqt cf analyzer maxEx lenient) =
2848− object ["multi_match" .= omitNulls base]
2849− where base = [ "fields" .= fmap toJSON fields
2850− , "query" .= query
2851− , "operator" .= boolOp
2852− , "zero_terms_query" .= ztQ
2853− , "tiebreaker" .= tb
2854− , "type" .= mmqt
2855− , "cutoff_frequency" .= cf
2856− , "analyzer" .= analyzer
2857− , "max_expansions" .= maxEx
2858− , "lenient" .= lenient ]
2859−
2860−instance FromJSON MultiMatchQuery where
2861− parseJSON = withObject "MultiMatchQuery" parse
2862− where parse raw = do o <- raw .: "multi_match"
2863− MultiMatchQuery
2864− <$> o .:? "fields" .!= []
2865− <*> o .: "query"
2866− <*> o .: "operator"
2867− <*> o .: "zero_terms_query"
2868− <*> o .:? "tiebreaker"
2869− <*> o .:? "type"
2870− <*> o .:? "cutoff_frequency"
2871− <*> o .:? "analyzer"
2872− <*> o .:? "max_expansions"
2873− <*> o .:? "lenient"
2874−
2875−instance ToJSON MultiMatchQueryType where
2876− toJSON MultiMatchBestFields = "best_fields"
2877− toJSON MultiMatchMostFields = "most_fields"
2878− toJSON MultiMatchCrossFields = "cross_fields"
2879− toJSON MultiMatchPhrase = "phrase"
2880− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2881−
2882−instance FromJSON MultiMatchQueryType where
2883− parseJSON = withText "MultiMatchPhrasePrefix" parse
2884− where parse "best_fields" = pure MultiMatchBestFields
2885− parse "most_fields" = pure MultiMatchMostFields
2886− parse "cross_fields" = pure MultiMatchCrossFields
2887− parse "phrase" = pure MultiMatchPhrase
2888− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2889− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2890−
2891−instance ToJSON BooleanOperator where
2892− toJSON And = String "and"
2893− toJSON Or = String "or"
2894−
2895−instance FromJSON BooleanOperator where
2896− parseJSON = withText "BooleanOperator" parse
2897− where parse "and" = pure And
2898− parse "or" = pure Or
2899− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2900−
2901−instance ToJSON ZeroTermsQuery where
2902− toJSON ZeroTermsNone = String "none"
2903− toJSON ZeroTermsAll = String "all"
2904−
2905−instance FromJSON ZeroTermsQuery where
2906− parseJSON = withText "ZeroTermsQuery" parse
2907− where parse "none" = pure ZeroTermsNone
2908− parse "all" = pure ZeroTermsAll
2909− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2910−
2911−instance ToJSON MatchQueryType where
2912− toJSON MatchPhrase = "phrase"
2913− toJSON MatchPhrasePrefix = "phrase_prefix"
2914−
2915−instance FromJSON MatchQueryType where
2916− parseJSON = withText "MatchQueryType" parse
2917− where parse "phrase" = pure MatchPhrase
2918− parse "phrase_prefix" = pure MatchPhrasePrefix
2919− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2920−
2921−instance FromJSON Status where
2922− parseJSON (Object v) = Status <$>
2923− v .:? "ok" <*>
2924− v .: "status" <*>
2925− v .: "name" <*>
2926− v .: "version" <*>
2927− v .: "tagline"
2928− parseJSON _ = empty
2929−
2930−
2931−instance ToJSON IndexSettings where
2932− toJSON (IndexSettings s r) = object ["settings" .=
2933− object ["index" .=
2934− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2935− ]
2936− ]
2937−
2938−instance FromJSON IndexSettings where
2939− parseJSON = withObject "IndexSettings" parse
2940− where parse o = do s <- o .: "settings"
2941− i <- s .: "index"
2942− IndexSettings <$> i .: "number_of_shards"
2943− <*> i .: "number_of_replicas"
2944−
2945−instance ToJSON UpdatableIndexSetting where
2946− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2947− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2948− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2949− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2950− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2951− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2952− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2953− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2954− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2955− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2956− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2957− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2958− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2959− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2960− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2961− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2962− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2963− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2964− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2965− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2966− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2967− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2968− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2969− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2970− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2971− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2972− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2973− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2974−
2975−instance FromJSON UpdatableIndexSetting where
2976− parseJSON = withObject "UpdatableIndexSetting" parse
2977− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2978− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2979− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2980− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2981− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2982− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2983− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2984− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2985− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2986− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2987− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2988− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2989− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2990− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2991− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2992− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2993− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2994− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2995− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2996− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2997− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2998− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2999− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3000− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3001− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3002− <|> blocksRead `taggedAt` ["blocks", "read"]
3003− <|> blocksWrite `taggedAt` ["blocks", "write"]
3004− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3005− where taggedAt f ks = taggedAt' f (Object o) ks
3006− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3007− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3008− taggedAt' f v' ks) v
3009− numberOfReplicas = pure . NumberOfReplicas
3010− autoExpandReplicas = pure . AutoExpandReplicas
3011− refreshInterval = pure . RefreshInterval . ndtJSON
3012− indexConcurrency = pure . IndexConcurrency
3013− failOnMergeFailure = pure . FailOnMergeFailure
3014− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3015− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3016− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3017− translogDisableFlush = pure . TranslogDisableFlush
3018− cacheFilterMaxSize = pure . CacheFilterMaxSize
3019− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3020− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3021− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3022− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3023− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3024− routingAllocationEnable = pure . RoutingAllocationEnable
3025− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3026− recoveryInitialShards = pure . RecoveryInitialShards
3027− gcDeletes = pure . GCDeletes . ndtJSON
3028− ttlDisablePurge = pure . TTLDisablePurge
3029− translogFSType = pure . TranslogFSType
3030− compoundFormat = pure . IndexCompoundFormat
3031− compoundOnFlush = pure . IndexCompoundOnFlush
3032− warmerEnabled = pure . WarmerEnabled
3033− blocksReadOnly = pure . BlocksReadOnly
3034− blocksRead = pure . BlocksRead
3035− blocksWrite = pure . BlocksWrite
3036− blocksMetaData = pure . BlocksMetaData
3037−
3038−instance FromJSON IndexSettingsSummary where
3039− parseJSON = withObject "IndexSettingsSummary" parse
3040− where parse o = case HM.toList o of
3041− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3042− <$> parseJSON v
3043− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3044− _ -> fail "Expected single-key object with index name"
3045− redundant (NumberOfReplicas _) = True
3046− redundant _ = False
3047−
3048−-- | For some reason in several settings APIs, all leaf values get returned
3049−-- as strings. This function attepmts to recover from this for all
3050−-- non-recursive JSON types. If nothing can be done, the value is left alone.
3051−unStringlyTypeJSON :: Value -> Value
3052−unStringlyTypeJSON (String "true") = Bool True
3053−unStringlyTypeJSON (String "false") = Bool False
3054−unStringlyTypeJSON (String "null") = Null
3055−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3056− Just n -> Number n
3057− Nothing -> v
3058−unStringlyTypeJSON v = v
3059−
3060−
3061−parseSettings :: Object -> Parser [UpdatableIndexSetting]
3062−parseSettings o = do
3063− o' <- o .: "index"
3064− -- slice the index object into singleton hashmaps and try to parse each
3065− parses <- forM (HM.toList o') $ \(k, v) -> do
3066− -- blocks are now nested into the "index" key, which is not how they're serialized
3067− let atRoot = Object (HM.singleton k v)
3068− let atIndex = Object (HM.singleton "index" atRoot)
3069− optional (parseJSON atRoot <|> parseJSON atIndex)
3070− return (catMaybes parses)
3071−
3072−oPath :: ToJSON a => NonEmpty Text -> a -> Value
3073−oPath (k :| []) v = object [k .= v]
3074−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3075−
3076−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3077−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3078− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3079−
3080−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3081−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3082− where parse o = case HM.toList o of
3083− [] -> fail "Expected non-empty list of NodeAttrFilters"
3084− x:xs -> DT.mapM (uncurry parse') (x :| xs)
3085− parse' n = withText "Text" $ \t ->
3086− case T.splitOn "," t of
3087− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3088− [] -> fail "Expected non-empty list of filter values"
3089−
3090−instance ToJSON ReplicaBounds where
3091− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3092− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3093− toJSON ReplicasUnbounded = Bool False
3094−
3095−instance FromJSON ReplicaBounds where
3096− parseJSON v = withText "ReplicaBounds" parseText v
3097− <|> withBool "ReplicaBounds" parseBool v
3098− where parseText t = case T.splitOn "-" t of
3099− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3100− [a, b] -> ReplicasBounded <$> parseReadText a
3101− <*> parseReadText b
3102− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3103− parseBool False = pure ReplicasUnbounded
3104− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3105−
3106−instance ToJSON AllocationPolicy where
3107− toJSON AllocAll = String "all"
3108− toJSON AllocPrimaries = String "primaries"
3109− toJSON AllocNewPrimaries = String "new_primaries"
3110− toJSON AllocNone = String "none"
3111−
3112−instance FromJSON AllocationPolicy where
3113− parseJSON = withText "AllocationPolicy" parse
3114− where parse "all" = pure AllocAll
3115− parse "primaries" = pure AllocPrimaries
3116− parse "new_primaries" = pure AllocNewPrimaries
3117− parse "none" = pure AllocNone
3118− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3119−
3120−instance ToJSON InitialShardCount where
3121− toJSON QuorumShards = String "quorum"
3122− toJSON QuorumMinus1Shards = String "quorum-1"
3123− toJSON FullShards = String "full"
3124− toJSON FullMinus1Shards = String "full-1"
3125− toJSON (ExplicitShards x) = toJSON x
3126−
3127−instance FromJSON InitialShardCount where
3128− parseJSON v = withText "InitialShardCount" parseText v
3129− <|> ExplicitShards <$> parseJSON v
3130− where parseText "quorum" = pure QuorumShards
3131− parseText "quorum-1" = pure QuorumMinus1Shards
3132− parseText "full" = pure FullShards
3133− parseText "full-1" = pure FullMinus1Shards
3134− parseText _ = mzero
3135−
3136−instance ToJSON FSType where
3137− toJSON FSSimple = "simple"
3138− toJSON FSBuffered = "buffered"
3139−
3140−instance FromJSON FSType where
3141− parseJSON = withText "FSType" parse
3142− where parse "simple" = pure FSSimple
3143− parse "buffered" = pure FSBuffered
3144− parse t = fail ("Invalid FSType: " <> show t)
3145−
3146−instance ToJSON CompoundFormat where
3147− toJSON (CompoundFileFormat x) = Bool x
3148− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3149−
3150−instance FromJSON CompoundFormat where
3151− parseJSON v = CompoundFileFormat <$> parseJSON v
3152− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3153−
3154−instance ToJSON NominalDiffTimeJSON where
3155− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3156−
3157−instance FromJSON NominalDiffTimeJSON where
3158− parseJSON = withText "NominalDiffTime" parse
3159− where parse t = case T.takeEnd 1 t of
3160− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3161− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3162−
3163−instance ToJSON IndexTemplate where
3164− toJSON (IndexTemplate p s m) = merge
3165− (object [ "template" .= p
3166− , "mappings" .= foldl' merge (object []) m
3167− ])
3168− (toJSON s)
3169− where
3170− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3171− merge o Null = o
3172− merge _ _ = undefined
3173−
3174−instance (FromJSON a) => FromJSON (EsResult a) where
3175− parseJSON jsonVal@(Object v) = do
3176− found <- v .:? "found" .!= False
3177− fr <- if found
3178− then parseJSON jsonVal
3179− else return Nothing
3180− EsResult <$> v .: "_index" <*>
3181− v .: "_type" <*>
3182− v .: "_id" <*>
3183− pure fr
3184− parseJSON _ = empty
3185−
3186−instance (FromJSON a) => FromJSON (EsResultFound a) where
3187− parseJSON (Object v) = EsResultFound <$>
3188− v .: "_version" <*>
3189− v .: "_source"
3190− parseJSON _ = empty
3191−
3192−instance FromJSON EsError where
3193− parseJSON (Object v) = EsError <$>
3194− v .: "status" <*>
3195− v .: "error"
3196− parseJSON _ = empty
3197−
3198−instance FromJSON IndexAliasesSummary where
3199− parseJSON = withObject "IndexAliasesSummary" parse
3200− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3201− go ixn = withObject "index aliases" $ \ia -> do
3202− aliases <- ia .:? "aliases" .!= mempty
3203− forM (HM.toList aliases) $ \(aName, v) -> do
3204− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3205− IndexAliasSummary indexAlias <$> parseJSON v
3206−
3207−
3208−instance ToJSON IndexAliasAction where
3209− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3210− where Object iaObj = toJSON ia
3211− Object optsObj = toJSON opts
3212− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3213− where Object iaObj = toJSON ia
3214−
3215−instance ToJSON IndexAlias where
3216− toJSON IndexAlias {..} = object ["index" .= srcIndex
3217− , "alias" .= indexAlias
3218− ]
3219−
3220−instance ToJSON IndexAliasCreate where
3221− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3222− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3223− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3224−
3225−instance ToJSON AliasRouting where
3226− toJSON (AllAliasRouting v) = object ["routing" .= v]
3227− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3228− where prs = [("search_routing" .=) <$> srch
3229− ,("index_routing" .=) <$> idx]
3230−
3231−instance FromJSON AliasRouting where
3232− parseJSON = withObject "AliasRouting" parse
3233− where parse o = parseAll o <|> parseGranular o
3234− parseAll o = AllAliasRouting <$> o .: "routing"
3235− parseGranular o = do
3236− sr <- o .:? "search_routing"
3237− ir <- o .:? "index_routing"
3238− if isNothing sr && isNothing ir
3239− then fail "Both search_routing and index_routing can't be blank"
3240− else return (GranularAliasRouting sr ir)
3241−
3242−instance FromJSON IndexAliasCreate where
3243− parseJSON v = withObject "IndexAliasCreate" parse v
3244− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3245− <*> o .:? "filter"
3246−
3247−instance ToJSON SearchAliasRouting where
3248− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3249−
3250−instance FromJSON SearchAliasRouting where
3251− parseJSON = withText "SearchAliasRouting" parse
3252− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3253−
3254−instance ToJSON Search where
3255− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3256− omitNulls [ "query" .= query
3257− , "filter" .= sFilter
3258− , "sort" .= sort
3259− , "aggregations" .= searchAggs
3260− , "highlight" .= highlight
3261− , "from" .= sFrom
3262− , "size" .= sSize
3263− , "track_scores" .= sTrackSortScores
3264− , "fields" .= sFields
3265− , "_source" .= sSource]
3266−
3267−
3268−instance ToJSON Source where
3269− toJSON NoSource = toJSON False
3270− toJSON (SourcePatterns patterns) = toJSON patterns
3271− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3272−
3273−instance ToJSON PatternOrPatterns where
3274− toJSON (PopPattern pattern) = toJSON pattern
3275− toJSON (PopPatterns patterns) = toJSON patterns
3276−
3277−instance ToJSON Include where
3278− toJSON (Include patterns) = toJSON patterns
3279−
3280−instance ToJSON Exclude where
3281− toJSON (Exclude patterns) = toJSON patterns
3282−
3283−instance ToJSON Pattern where
3284− toJSON (Pattern pattern) = toJSON pattern
3285−
3286−
3287−instance ToJSON FieldHighlight where
3288− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3289− object [ fName .= fSettings ]
3290− toJSON (FieldHighlight (FieldName fName) Nothing) =
3291− object [ fName .= emptyObject ]
3292−
3293−instance ToJSON Highlights where
3294− toJSON (Highlights global fields) =
3295− omitNulls (("fields" .= fields)
3296− : highlightSettingsPairs global)
3297−
3298−instance ToJSON HighlightSettings where
3299− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3300−
3301−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3302−highlightSettingsPairs Nothing = []
3303−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3304−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3305−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3306−
3307−
3308−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3309−plainHighPairs Nothing = []
3310−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3311− [ "type" .= String "plain"]
3312− ++ commonHighlightPairs plCom
3313− ++ nonPostingsToPairs plNonPost
3314−
3315−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3316−postHighPairs Nothing = []
3317−postHighPairs (Just (PostingsHighlight pCom)) =
3318− ("type" .= String "postings")
3319− : commonHighlightPairs pCom
3320−
3321−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3322−fastVectorHighPairs Nothing = []
3323−fastVectorHighPairs (Just
3324− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3325− fvBoundMaxScan fvFragOff fvMatchedFields
3326− fvPhraseLim)) =
3327− [ "type" .= String "fvh"
3328− , "boundary_chars" .= fvBoundChars
3329− , "boundary_max_scan" .= fvBoundMaxScan
3330− , "fragment_offset" .= fvFragOff
3331− , "matched_fields" .= fvMatchedFields
3332− , "phraseLimit" .= fvPhraseLim]
3333− ++ commonHighlightPairs fvCom
3334− ++ nonPostingsToPairs fvNonPostSettings
3335−
3336−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3337−deleteSeveral ks hm = foldr HM.delete hm ks
3338−
3339−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3340−commonHighlightPairs Nothing = []
3341−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3342− chNoMatchSize chHighlightQuery
3343− chRequireFieldMatch)) =
3344− [ "order" .= chScore
3345− , "force_source" .= chForceSource
3346− , "encoder" .= chEncoder
3347− , "no_match_size" .= chNoMatchSize
3348− , "highlight_query" .= chHighlightQuery
3349− , "require_fieldMatch" .= chRequireFieldMatch]
3350− ++ highlightTagToPairs chTag
3351−
3352−
3353−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3354−nonPostingsToPairs Nothing = []
3355−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3356− [ "fragment_size" .= npFragSize
3357− , "number_of_fragments" .= npNumOfFrags]
3358−
3359−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3360−parseNEJSON [] = fail "Expected non-empty list"
3361−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3362−
3363−
3364−instance ToJSON HighlightEncoder where
3365− toJSON DefaultEncoder = String "default"
3366− toJSON HTMLEncoder = String "html"
3367−
3368−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3369−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3370−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3371− , "post_tags" .= post]
3372−highlightTagToPairs Nothing = []
3373−
3374−instance ToJSON SortSpec where
3375− toJSON (DefaultSortSpec
3376− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3377− dsSortMode dsMissingSort dsNestedFilter)) =
3378− object [dsSortFieldName .= omitNulls base] where
3379− base = [ "order" .= dsSortOrder
3380− , "ignore_unmapped" .= dsIgnoreUnmapped
3381− , "mode" .= dsSortMode
3382− , "missing" .= dsMissingSort
3383− , "nested_filter" .= dsNestedFilter ]
3384−
3385− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3386− object [ "unit" .= units
3387− , field .= gdsLatLon
3388− , "order" .= gdsSortOrder ]
3389−
3390−
3391−instance ToJSON SortOrder where
3392− toJSON Ascending = String "asc"
3393− toJSON Descending = String "desc"
3394−
3395−
3396−instance ToJSON SortMode where
3397− toJSON SortMin = String "min"
3398− toJSON SortMax = String "max"
3399− toJSON SortSum = String "sum"
3400− toJSON SortAvg = String "avg"
3401−
3402−
3403−instance ToJSON Missing where
3404− toJSON LastMissing = String "_last"
3405− toJSON FirstMissing = String "_first"
3406− toJSON (CustomMissing txt) = String txt
3407−
3408−
3409−instance ToJSON ScoreType where
3410− toJSON ScoreTypeMax = "max"
3411− toJSON ScoreTypeAvg = "avg"
3412− toJSON ScoreTypeSum = "sum"
3413− toJSON ScoreTypeNone = "none"
3414−
3415−instance FromJSON ScoreType where
3416− parseJSON = withText "ScoreType" parse
3417− where parse "max" = pure ScoreTypeMax
3418− parse "avg" = pure ScoreTypeAvg
3419− parse "sum" = pure ScoreTypeSum
3420− parse "none" = pure ScoreTypeNone
3421− parse t = fail ("Unexpected ScoreType: " <> show t)
3422−
3423−instance ToJSON Distance where
3424− toJSON (Distance dCoefficient dUnit) =
3425− String boltedTogether where
3426− coefText = showText dCoefficient
3427− (String unitText) = toJSON dUnit
3428− boltedTogether = mappend coefText unitText
3429−
3430−instance FromJSON Distance where
3431− parseJSON = withText "Distance" parse
3432− where parse t = Distance <$> parseCoeff nT
3433− <*> parseJSON (String unitT)
3434− where (nT, unitT) = T.span validForNumber t
3435− -- may be a better way to do this
3436− validForNumber '-' = True
3437− validForNumber '.' = True
3438− validForNumber 'e' = True
3439− validForNumber c = isNumber c
3440− parseCoeff "" = fail "Empty string cannot be parsed as number"
3441− parseCoeff s = return (read (T.unpack s))
3442−
3443−instance ToJSON DistanceUnit where
3444− toJSON Miles = String "mi"
3445− toJSON Yards = String "yd"
3446− toJSON Feet = String "ft"
3447− toJSON Inches = String "in"
3448− toJSON Kilometers = String "km"
3449− toJSON Meters = String "m"
3450− toJSON Centimeters = String "cm"
3451− toJSON Millimeters = String "mm"
3452− toJSON NauticalMiles = String "nmi"
3453−
3454−
3455−instance FromJSON DistanceUnit where
3456− parseJSON = withText "DistanceUnit" parse
3457− where parse "mi" = pure Miles
3458− parse "yd" = pure Yards
3459− parse "ft" = pure Feet
3460− parse "in" = pure Inches
3461− parse "km" = pure Kilometers
3462− parse "m" = pure Meters
3463− parse "cm" = pure Centimeters
3464− parse "mm" = pure Millimeters
3465− parse "nmi" = pure NauticalMiles
3466− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3467−
3468−instance ToJSON DistanceType where
3469− toJSON Arc = String "arc"
3470− toJSON SloppyArc = String "sloppy_arc"
3471− toJSON Plane = String "plane"
3472−
3473−instance FromJSON DistanceType where
3474− parseJSON = withText "DistanceType" parse
3475− where parse "arc" = pure Arc
3476− parse "sloppy_arc" = pure SloppyArc
3477− parse "plane" = pure Plane
3478− parse t = fail ("Unrecognized DistanceType: " <> show t)
3479−
3480−
3481−instance ToJSON OptimizeBbox where
3482− toJSON NoOptimizeBbox = String "none"
3483− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3484−
3485−instance FromJSON OptimizeBbox where
3486− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3487− <|> parseOptimize v
3488− where parseNoOptimize "none" = pure NoOptimizeBbox
3489− parseNoOptimize _ = mzero
3490− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3491−
3492−instance ToJSON GeoBoundingBoxConstraint where
3493− toJSON (GeoBoundingBoxConstraint
3494− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3495− object [gbbcGeoBBField .= gbbcConstraintBox
3496− , "_cache" .= cache
3497− , "type" .= type']
3498−
3499−instance FromJSON GeoBoundingBoxConstraint where
3500− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3501− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3502− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3503− <$> parseJSON v
3504− <*> o .:? "_cache" .!= defaultCache
3505− <*> o .: "type"
3506− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3507−
3508−instance ToJSON GeoFilterType where
3509− toJSON GeoFilterMemory = String "memory"
3510− toJSON GeoFilterIndexed = String "indexed"
3511−
3512−instance FromJSON GeoFilterType where
3513− parseJSON = withText "GeoFilterType" parse
3514− where parse "memory" = pure GeoFilterMemory
3515− parse "indexed" = pure GeoFilterIndexed
3516− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3517−
3518−instance ToJSON GeoBoundingBox where
3519− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3520− object ["top_left" .= gbbTopLeft
3521− , "bottom_right" .= gbbBottomRight]
3522−
3523−instance FromJSON GeoBoundingBox where
3524− parseJSON = withObject "GeoBoundingBox" parse
3525− where parse o = GeoBoundingBox
3526− <$> o .: "top_left"
3527− <*> o .: "bottom_right"
3528−
3529−instance ToJSON LatLon where
3530− toJSON (LatLon lLat lLon) =
3531− object ["lat" .= lLat
3532− , "lon" .= lLon]
3533−
3534−instance FromJSON LatLon where
3535− parseJSON = withObject "LatLon" parse
3536− where parse o = LatLon <$> o .: "lat"
3537− <*> o .: "lon"
3538−
3539−-- index for smaller ranges, fielddata for longer ranges
3540−instance ToJSON RangeExecution where
3541− toJSON RangeExecutionIndex = "index"
3542− toJSON RangeExecutionFielddata = "fielddata"
3543−
3544−
3545−instance FromJSON RangeExecution where
3546− parseJSON = withText "RangeExecution" parse
3547− where parse "index" = pure RangeExecutionIndex
3548− parse "fielddata" = pure RangeExecutionFielddata
3549− parse t = error ("Unrecognized RangeExecution " <> show t)
3550−
3551−instance ToJSON RegexpFlags where
3552− toJSON AllRegexpFlags = String "ALL"
3553− toJSON NoRegexpFlags = String "NONE"
3554− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3555− where flagStrs = map flagStr . nub $ h:fs
3556− flagStr AnyString = "ANYSTRING"
3557− flagStr Automaton = "AUTOMATON"
3558− flagStr Complement = "COMPLEMENT"
3559− flagStr Empty = "EMPTY"
3560− flagStr Intersection = "INTERSECTION"
3561− flagStr Interval = "INTERVAL"
3562−
3563−instance FromJSON RegexpFlags where
3564− parseJSON = withText "RegexpFlags" parse
3565− where parse "ALL" = pure AllRegexpFlags
3566− parse "NONE" = pure NoRegexpFlags
3567− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3568−
3569−instance FromJSON RegexpFlag where
3570− parseJSON = withText "RegexpFlag" parse
3571− where parse "ANYSTRING" = pure AnyString
3572− parse "AUTOMATON" = pure Automaton
3573− parse "COMPLEMENT" = pure Complement
3574− parse "EMPTY" = pure Empty
3575− parse "INTERSECTION" = pure Intersection
3576− parse "INTERVAL" = pure Interval
3577− parse f = fail ("Unknown RegexpFlag: " <> show f)
3578−
3579−instance ToJSON Term where
3580− toJSON (Term field value) = object ["term" .= object
3581− [field .= value]]
3582−
3583−instance FromJSON Term where
3584− parseJSON = withObject "Term" parse
3585− where parse o = do termObj <- o .: "term"
3586− case HM.toList termObj of
3587− [(fn, v)] -> Term fn <$> parseJSON v
3588− _ -> fail "Expected object with 1 field-named key"
3589−
3590−instance ToJSON BoolMatch where
3591− toJSON (MustMatch term cache) = object ["must" .= term,
3592− "_cache" .= cache]
3593− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3594− "_cache" .= cache]
3595− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3596− "_cache" .= cache]
3597−
3598−instance FromJSON BoolMatch where
3599− parseJSON = withObject "BoolMatch" parse
3600− where parse o = mustMatch `taggedWith` "must"
3601− <|> mustNotMatch `taggedWith` "must_not"
3602− <|> shouldMatch `taggedWith` "should"
3603− where taggedWith parser k = parser =<< o .: k
3604− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3605− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3606− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
522+ , scrollId :: Maybe ScrollId
523+ -- ^ Only one Suggestion request / response per
524+ -- Search is supported.
525+ , suggest :: Maybe NamedSuggestionResponse
526+ }
527+ deriving (Eq, Show)
3607528
3608529instance (FromJSON a) => FromJSON (SearchResult a) where
3609530 parseJSON (Object v) = SearchResult <$>
@@ -3612,459 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3612533 v .: "_shards" <*>
3613534 v .: "hits" <*>
3614535 v .:? "aggregations" <*>
3615− v .:? "_scroll_id"
3616− parseJSON _ = empty
3617−
3618−instance (FromJSON a) => FromJSON (SearchHits a) where
3619− parseJSON (Object v) = SearchHits <$>
3620− v .: "total" <*>
3621− v .: "max_score" <*>
3622− v .: "hits"
536+ v .:? "_scroll_id" <*>
537+ v .:? "suggest"
3623538 parseJSON _ = empty
3624539
3625−instance (FromJSON a) => FromJSON (Hit a) where
3626− parseJSON (Object v) = Hit <$>
3627− v .: "_index" <*>
3628− v .: "_type" <*>
3629− v .: "_id" <*>
3630− v .: "_score" <*>
3631− v .:? "_source" <*>
3632− v .:? "highlight"
3633− parseJSON _ = empty
3634−
3635−instance FromJSON ShardResult where
3636− parseJSON (Object v) = ShardResult <$>
3637− v .: "total" <*>
3638− v .: "successful" <*>
3639− v .: "failed"
3640− parseJSON _ = empty
3641−
3642−
3643−instance FromJSON DocVersion where
3644− parseJSON v = do
3645− i <- parseJSON v
3646− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3647−
3648−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3649−instance FromJSON ReplicaCount where
3650− parseJSON v = parseAsInt v
3651− <|> parseAsString v
3652− where parseAsInt = fmap ReplicaCount . parseJSON
3653− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3654−
3655−instance FromJSON ShardCount where
3656− parseJSON v = parseAsInt v
3657− <|> parseAsString v
3658− where parseAsInt = fmap ShardCount . parseJSON
3659− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3660−
3661−instance Bounded DocVersion where
3662− minBound = DocVersion 1
3663− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3664−
3665−instance Enum DocVersion where
3666− succ x
3667− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3668− | otherwise = succError "DocVersion"
3669− pred x
3670− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3671− | otherwise = predError "DocVersion"
3672− toEnum i =
3673− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3674− fromEnum = docVersionNumber
3675− enumFrom = boundedEnumFrom
3676− enumFromThen = boundedEnumFromThen
3677−
3678−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3679−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3680−
3681−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3682−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3683−
3684−
3685−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3686− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3687−
3688−
3689−-- | Either specifies an exact repo name or one with globs in it,
3690−-- e.g. @RepoPattern "foo*"@ __NOTE__:@ Patterns are not supported on ES < 1.7
3691−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3692− | RepoPattern Text
3693− deriving (Eq, Generic, Show, Typeable)
3694−
3695−-- | The unique name of a snapshot repository.
3696−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3697− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3698−
3699−
3700−-- | A generic representation of a snapshot repo. This is what gets
3701−-- sent to and parsed from the server. For repo types enabled by
3702−-- plugins that aren't exported by this library, consider making a
3703−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3704−-- type, consider submitting a pull request to have it included in the
3705−-- library proper
3706−data GenericSnapshotRepo = GenericSnapshotRepo {
3707− gSnapshotRepoName :: SnapshotRepoName
3708− , gSnapshotRepoType :: SnapshotRepoType
3709− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3710− } deriving (Eq, Generic, Show, Typeable)
3711−
3712−
3713−instance SnapshotRepo GenericSnapshotRepo where
3714− toGSnapshotRepo = id
3715− fromGSnapshotRepo = Right
3716−
3717−
3718−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3719− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3720−
3721−
3722−-- | Opaque representation of snapshot repo settings. Instances of
3723−-- 'SnapshotRepo' will produce this.
3724−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3725− deriving (Eq, Generic, Show, Typeable, ToJSON)
3726−
3727−
3728− -- Regardless of whether you send strongly typed json, my version of
3729− -- ES sends back stringly typed json in the settings, e.g. booleans
3730− -- as strings, so we'll try to convert them.
3731−instance FromJSON GenericSnapshotRepoSettings where
3732− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3733−
3734−-- | The result of running 'verifySnapshotRepo'.
3735−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3736− deriving (Eq, Generic, Show, Typeable)
3737−
3738−
3739−instance FromJSON SnapshotVerification where
3740− parseJSON = withObject "SnapshotVerification" parse
3741− where
3742− parse o = do
3743− o2 <- o .: "nodes"
3744− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3745− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3746− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3747−
3748−
3749−data SnapshotNodeVerification = SnapshotNodeVerification {
3750− snvFullId :: FullNodeId
3751− , snvNodeName :: NodeName
3752− } deriving (Eq, Generic, Show, Typeable)
3753−
3754−
3755−-- | Unique, automatically-generated name assigned to nodes that are
3756−-- usually returned in node-oriented APIs.
3757−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3758− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3759−
3760−
3761−newtype NodeName = NodeName { nodeName :: Text }
3762− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3763−
3764−
3765−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
3766− repoUpdateVerify :: Bool
3767− -- ^ After creation/update, synchronously check that nodes can
3768− -- write to this repo. Defaults to True. You may use False if you
3769− -- need a faster response and plan on verifying manually later
3770− -- with 'verifySnapshotRepo'.
3771− } deriving (Eq, Show, Generic, Typeable)
3772−
3773−
3774−-- | Reasonable defaults for repo creation/update
3775−--
3776−-- * repoUpdateVerify True
3777−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
3778−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
3779−
3780−
3781−-- | A filesystem-based snapshot repo that ships with elasticsearch.
3782−data FsSnapshotRepo = FsSnapshotRepo {
3783− fsrName :: SnapshotRepoName
3784− , fsrLocation :: FilePath
3785− , fsrCompressMetadata :: Bool
3786− , fsrChunkSize :: Maybe Bytes
3787− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
3788− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
3789− } deriving (Eq, Generic, Show, Typeable)
3790−
3791−
3792−instance SnapshotRepo FsSnapshotRepo where
3793− toGSnapshotRepo FsSnapshotRepo {..} =
3794− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
3795− where
3796− Object settings = object $ [ "location" .= fsrLocation
3797− , "compress" .= fsrCompressMetadata
3798− ] ++ optionalPairs
3799− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
3800− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
3801− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
3802− ]
3803− fromGSnapshotRepo GenericSnapshotRepo {..}
3804− | gSnapshotRepoType == fsRepoType = do
3805− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
3806− parseRepo $ do
3807− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
3808− <*> o .:? "compress" .!= False
3809− <*> o .:? "chunk_size"
3810− <*> o .:? "max_restore_bytes_per_sec"
3811− <*> o .:? "max_snapshot_bytes_per_sec"
3812− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
3813−
3814−
3815−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
3816−parseRepo parser = case parseEither (const parser) () of
3817− Left e -> Left (OtherRepoConversionError (T.pack e))
3818− Right a -> Right a
3819−
3820−
3821−fsRepoType :: SnapshotRepoType
3822−fsRepoType = SnapshotRepoType "fs"
3823−
3824−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
3825−class SnapshotRepo r where
3826− toGSnapshotRepo :: r -> GenericSnapshotRepo
3827− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
3828−
3829−
3830−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType
3831− -- ^ Expected type
3832− SnapshotRepoType
3833− -- ^ Actual type
3834− | OtherRepoConversionError Text
3835− deriving (Show, Eq, Generic, Typeable)
3836−
3837−
3838−instance Exception SnapshotRepoConversionError
3839−
3840−
3841−data SnapshotCreateSettings = SnapshotCreateSettings {
3842− snapWaitForCompletion :: Bool
3843− -- ^ Should the API call return immediately after initializing
3844− -- the snapshot or wait until completed? Note that if this is
3845− -- enabled it could wait a long time, so you should adjust your
3846− -- 'ManagerSettings' accordingly to set long timeouts or
3847− -- explicitly handle timeouts.
3848− , snapIndices :: Maybe (NonEmpty IndexName)
3849− -- ^ Nothing will snapshot all indices. Just [] is permissable and
3850− -- will essentially be a no-op snapshot.
3851− , snapIgnoreUnavailable :: Bool
3852− -- ^ If set to True, any matched indices that don't exist will be
3853− -- ignored. Otherwise it will be an error and fail.
3854− , snapIncludeGlobalState :: Bool
3855− , snapPartial :: Bool
3856− -- ^ If some indices failed to snapshot (e.g. if not all primary
3857− -- shards are available), should the process proceed?
3858− } deriving (Eq, Generic, Show, Typeable)
3859−
3860−
3861−-- | Reasonable defaults for snapshot creation
3862−--
3863−-- * snapWaitForCompletion False
3864−-- * snapIndices Nothing
3865−-- * snapIgnoreUnavailable False
3866−-- * snapIncludeGlobalState True
3867−-- * snapPartial False
3868−defaultSnapshotCreateSettings :: SnapshotCreateSettings
3869−defaultSnapshotCreateSettings = SnapshotCreateSettings {
3870− snapWaitForCompletion = False
3871− , snapIndices = Nothing
3872− , snapIgnoreUnavailable = False
3873− , snapIncludeGlobalState = True
3874− , snapPartial = False
3875− }
3876−
3877−
3878−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
3879− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
3880−
3881−
3882−-- | Either specifies an exact snapshot name or one with globs in it,
3883−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
3884−-- ES < 1.7
3885−data SnapshotPattern = ExactSnap SnapshotName
3886− | SnapPattern Text
3887− deriving (Eq, Generic, Show, Typeable)
3888−
3889−
3890−-- | General information about the state of a snapshot. Has some
3891−-- redundancies with 'SnapshotStatus'
3892−data SnapshotInfo = SnapshotInfo {
3893− snapInfoShards :: ShardResult
3894− --TODO: what does failures produce? list of what?
3895− , snapInfoDuration :: NominalDiffTime
3896− , snapInfoEndTime :: UTCTime
3897− , snapInfoStartTime :: UTCTime
3898− , snapInfoState :: SnapshotState
3899− , snapInfoIndices :: [IndexName]
3900− , snapInfoName :: SnapshotName
3901− } deriving (Eq, Generic, Show, Typeable)
3902−
3903−
3904−instance FromJSON SnapshotInfo where
3905− parseJSON = withObject "SnapshotInfo" parse
3906− where
3907− parse o = SnapshotInfo <$> o .: "shards"
3908− <*> (unMS <$> o .: "duration_in_millis")
3909− <*> (posixMS <$> o .: "end_time_in_millis")
3910− <*> (posixMS <$> o .: "start_time_in_millis")
3911− <*> o .: "state"
3912− <*> o .: "indices"
3913− <*> o .: "snapshot"
3914−
3915−-- | Milliseconds
3916−newtype MS = MS NominalDiffTime
3917−
3918−
3919−-- keeps the unexported constructor warnings at bay
3920−unMS :: MS -> NominalDiffTime
3921−unMS (MS t) = t
3922−
3923−
3924−instance FromJSON MS where
3925− parseJSON = withScientific "MS" (return . MS . parse)
3926− where
3927− parse n = fromInteger ((truncate n) * 1000)
3928−
3929−
3930−data SnapshotState = SnapshotInit
3931− | SnapshotStarted
3932− | SnapshotSuccess
3933− | SnapshotFailed
3934− | SnapshotAborted
3935− | SnapshotMissing
3936− | SnapshotWaiting
3937− deriving (Show, Eq, Generic, Typeable)
3938−
3939−instance FromJSON SnapshotState where
3940− parseJSON = withText "SnapshotState" parse
3941− where
3942− parse "INIT" = return SnapshotInit
3943− parse "STARTED" = return SnapshotStarted
3944− parse "SUCCESS" = return SnapshotSuccess
3945− parse "FAILED" = return SnapshotFailed
3946− parse "ABORTED" = return SnapshotAborted
3947− parse "MISSING" = return SnapshotMissing
3948− parse "WAITING" = return SnapshotWaiting
3949− parse t = fail ("Invalid snapshot state " <> T.unpack t)
3950−
3951−
3952−newtype SnapshotName = SnapshotName { snapshotName :: Text }
3953− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
3954−
3955−
3956−data SnapshotRestoreSettings = SnapshotRestoreSettings {
3957− snapRestoreWaitForCompletion :: Bool
3958− -- ^ Should the API call return immediately after initializing
3959− -- the restore or wait until completed? Note that if this is
3960− -- enabled, it could wait a long time, so you should adjust your
3961− -- 'ManagerSettings' accordingly to set long timeouts or
3962− -- explicitly handle timeouts.
3963− , snapRestoreIndices :: Maybe (NonEmpty IndexName)
3964− -- ^ Nothing will restore all indices in the snapshot. Just [] is
3965− -- permissable and will essentially be a no-op restore.
3966− , snapRestoreIgnoreUnavailable :: Bool
3967− -- ^ If set to True, any indices that do not exist will be ignored
3968− -- during snapshot rather than failing the restore.
3969− , snapRestoreIncludeGlobalState :: Bool
3970− -- ^ If set to false, will ignore any global state in the snapshot
3971− -- and will not restore it.
3972− , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
3973− -- ^ A regex pattern for matching indices. Used with
3974− -- 'snapRestoreRenameReplacement', the restore can reference the
3975− -- matched index and create a new index name upon restore.
3976− , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
3977− -- ^ Expression of how index renames should be constructed.
3978− , snapRestorePartial :: Bool
3979− -- ^ If some indices fail to restore, should the process proceed?
3980− , snapRestoreIncludeAliases :: Bool
3981− -- ^ Should the restore also restore the aliases captured in the
3982− -- snapshot.
3983− , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
3984− -- ^ Settings to apply during the restore process.
3985− , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
3986− -- ^ This type could be more rich but it isn't clear which
3987− -- settings are allowed to be ignored during restore, so we're
3988− -- going with including this feature in a basic form rather than
3989− -- omitting it. One example here would be
3990− -- "index.refresh_interval". Any setting specified here will
3991− -- revert back to the server default during the restore process.
3992− } deriving (Eq, Generic, Show, Typeable)
3993−
3994−-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
3995−newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
3996− deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
3997−
3998−
3999−-- | A single token in a index renaming scheme for a restore. These
4000−-- are concatenated into a string before being sent to
4001−-- ElasticSearch. Check out these Java
4002−-- <https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html
4003−-- docs> to find out more if you're into that sort of thing.
4004−data RestoreRenameToken = RRTLit Text
4005− -- ^ Just a literal string of characters
4006− | RRSubWholeMatch
4007− -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4008− | RRSubGroup RRGroupRefNum
4009− -- ^ A specific reference to a group number
4010− deriving (Show, Eq, Generic, Typeable)
4011−
4012−
4013−-- | A group number for regex matching. Only values from 1-9 are
4014−-- supported. Construct with mkRRGroupRefNum
4015−newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4016− deriving (Show, Eq, Generic, Typeable, Ord)
4017−
4018−instance Bounded RRGroupRefNum where
4019− minBound = RRGroupRefNum 1
4020− maxBound = RRGroupRefNum 9
4021−
4022−
4023−
4024−-- | Only allows valid group number references (0-9).
4025−mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4026−mkRRGroupRefNum i
4027− | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4028− Just $ RRGroupRefNum i
4029− | otherwise = Nothing
4030−
4031−
4032−-- | Reasonable defaults for snapshot restores
4033−--
4034−-- * snapRestoreWaitForCompletion False
4035−-- * snapRestoreIndices Nothing
4036−-- * snapRestoreIgnoreUnavailable False
4037−-- * snapRestoreIncludeGlobalState True
4038−-- * snapRestoreRenamePattern Nothing
4039−-- * snapRestoreRenameReplacement Nothing
4040−-- * snapRestorePartial False
4041−-- * snapRestoreIncludeAliases True
4042−-- * snapRestoreIndexSettingsOverrides Nothing
4043−-- * snapRestoreIgnoreIndexSettings Nothing
4044−defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4045−defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4046− snapRestoreWaitForCompletion = False
4047− , snapRestoreIndices = Nothing
4048− , snapRestoreIgnoreUnavailable = False
4049− , snapRestoreIncludeGlobalState = True
4050− , snapRestoreRenamePattern = Nothing
4051− , snapRestoreRenameReplacement = Nothing
4052− , snapRestorePartial = False
4053− , snapRestoreIncludeAliases = True
4054− , snapRestoreIndexSettingsOverrides = Nothing
4055− , snapRestoreIgnoreIndexSettings = Nothing
4056− }
4057−
4058−
4059−-- | Index settings that can be overridden. The docs only mention you
4060−-- can update number of replicas, but there may be more. You
4061−-- definitely cannot override shard count.
4062−data RestoreIndexSettings = RestoreIndexSettings {
4063− restoreOverrideReplicas :: Maybe ReplicaCount
4064− } deriving (Show, Eq, Generic, Typeable)
4065−
4066−
4067−instance ToJSON RestoreIndexSettings where
4068− toJSON RestoreIndexSettings {..} = object prs
4069− where
4070− prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
540+newtype ScrollId =
541+ ScrollId Text
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)