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