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