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