@@ -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, 2015, 2016 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
1714-- License : BSD-style (see the file LICENSE)
1815-- Maintainer : Chris Allen <cma@bitemyapp.com
1916-- Stability : provisional
20−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
2118--
2219-- Data types for describing actions and data structures performed to interact
2320-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -45,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,2035 +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−
2086− toJSON (IdsQuery idsQueryMappingName docIds) =
2087− object [ "ids" .= object conjoined ]
2088− where conjoined = [ "type" .= idsQueryMappingName
2089− , "values" .= fmap toJSON docIds ]
2090−
2091− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2092− object [ "query_string" .= qQueryStringQuery ]
2093−
2094− toJSON (QueryMatchQuery matchQuery) =
2095− object [ "match" .= matchQuery ]
2096−
2097− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2098− toJSON multiMatchQuery
2099−
2100− toJSON (QueryBoolQuery boolQuery) =
2101− object [ "bool" .= boolQuery ]
2102−
2103− toJSON (QueryBoostingQuery boostingQuery) =
2104− object [ "boosting" .= boostingQuery ]
2105−
2106− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2107− object [ "common" .= commonTermsQuery ]
2108−
2109− toJSON (ConstantScoreFilter csFilter boost) =
2110− object ["constant_score" .= object ["filter" .= csFilter
2111− , "boost" .= boost]]
2112−
2113− toJSON (ConstantScoreQuery query boost) =
2114− object ["constant_score" .= object ["query" .= query
2115− , "boost" .= boost]]
2116−
2117− toJSON (QueryDisMaxQuery disMaxQuery) =
2118− object [ "dis_max" .= disMaxQuery ]
2119−
2120− toJSON (QueryFilteredQuery qFilteredQuery) =
2121− object [ "filtered" .= qFilteredQuery ]
2122−
2123− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2124− object [ "fuzzy_like_this" .= fuzzyQuery ]
2125−
2126− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2127− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2128−
2129− toJSON (QueryFuzzyQuery fuzzyQuery) =
2130− object [ "fuzzy" .= fuzzyQuery ]
2131−
2132− toJSON (QueryHasChildQuery childQuery) =
2133− object [ "has_child" .= childQuery ]
2134−
2135− toJSON (QueryHasParentQuery parentQuery) =
2136− object [ "has_parent" .= parentQuery ]
2137−
2138− toJSON (QueryIndicesQuery qIndicesQuery) =
2139− object [ "indices" .= qIndicesQuery ]
2140−
2141− toJSON (MatchAllQuery boost) =
2142− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2143−
2144− toJSON (QueryMoreLikeThisQuery query) =
2145− object [ "more_like_this" .= query ]
2146−
2147− toJSON (QueryMoreLikeThisFieldQuery query) =
2148− object [ "more_like_this_field" .= query ]
2149−
2150− toJSON (QueryNestedQuery query) =
2151− object [ "nested" .= query ]
2152−
2153− toJSON (QueryPrefixQuery query) =
2154− object [ "prefix" .= query ]
2155−
2156− toJSON (QueryRangeQuery query) =
2157− object [ "range" .= query ]
2158−
2159− toJSON (QueryRegexpQuery query) =
2160− object [ "regexp" .= query ]
2161−
2162− toJSON (QuerySimpleQueryStringQuery query) =
2163− object [ "simple_query_string" .= query ]
2164−
2165−instance FromJSON Query where
2166− parseJSON v = withObject "Query" parse v
2167− where parse o = termQuery `taggedWith` "term"
2168− <|> termsQuery `taggedWith` "terms"
2169− <|> idsQuery `taggedWith` "ids"
2170− <|> queryQueryStringQuery `taggedWith` "query_string"
2171− <|> queryMatchQuery `taggedWith` "match"
2172− <|> queryMultiMatchQuery
2173− <|> queryBoolQuery `taggedWith` "bool"
2174− <|> queryBoostingQuery `taggedWith` "boosting"
2175− <|> queryCommonTermsQuery `taggedWith` "common"
2176− <|> constantScoreFilter `taggedWith` "constant_score"
2177− <|> constantScoreQuery `taggedWith` "constant_score"
2178− <|> queryDisMaxQuery `taggedWith` "dis_max"
2179− <|> queryFilteredQuery `taggedWith` "filtered"
2180− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2181− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2182− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2183− <|> queryHasChildQuery `taggedWith` "has_child"
2184− <|> queryHasParentQuery `taggedWith` "has_parent"
2185− <|> queryIndicesQuery `taggedWith` "indices"
2186− <|> matchAllQuery `taggedWith` "match_all"
2187− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2188− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2189− <|> queryNestedQuery `taggedWith` "nested"
2190− <|> queryPrefixQuery `taggedWith` "prefix"
2191− <|> queryRangeQuery `taggedWith` "range"
2192− <|> queryRegexpQuery `taggedWith` "regexp"
2193− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2194− where taggedWith parser k = parser =<< o .: k
2195− termQuery = fieldTagged $ \(FieldName fn) o ->
2196− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2197− termsQuery o = case HM.toList o of
2198− [(fn, vs)] -> do vals <- parseJSON vs
2199− case vals of
2200− x:xs -> return (TermsQuery fn (x :| xs))
2201− _ -> fail "Expected non empty list of values"
2202− _ -> fail "Expected object with 1 field-named key"
2203− idsQuery o = IdsQuery <$> o .: "type"
2204− <*> o .: "values"
2205− queryQueryStringQuery = pure . QueryQueryStringQuery
2206− queryMatchQuery = pure . QueryMatchQuery
2207− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2208− queryBoolQuery = pure . QueryBoolQuery
2209− queryBoostingQuery = pure . QueryBoostingQuery
2210− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2211− constantScoreFilter o = case HM.lookup "filter" o of
2212− Just x -> ConstantScoreFilter <$> parseJSON x
2213− <*> o .: "boost"
2214− _ -> fail "Does not appear to be a ConstantScoreFilter"
2215− constantScoreQuery o = case HM.lookup "query" o of
2216− Just x -> ConstantScoreQuery <$> parseJSON x
2217− <*> o .: "boost"
2218− _ -> fail "Does not appear to be a ConstantScoreQuery"
2219− queryDisMaxQuery = pure . QueryDisMaxQuery
2220− queryFilteredQuery = pure . QueryFilteredQuery
2221− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2222− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2223− queryFuzzyQuery = pure . QueryFuzzyQuery
2224− queryHasChildQuery = pure . QueryHasChildQuery
2225− queryHasParentQuery = pure . QueryHasParentQuery
2226− queryIndicesQuery = pure . QueryIndicesQuery
2227− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2228− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2229− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2230− queryNestedQuery = pure . QueryNestedQuery
2231− queryPrefixQuery = pure . QueryPrefixQuery
2232− queryRangeQuery = pure . QueryRangeQuery
2233− queryRegexpQuery = pure . QueryRegexpQuery
2234− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2235−
2236−
2237−omitNulls :: [(Text, Value)] -> Value
2238−omitNulls = object . filter notNull where
2239− notNull (_, Null) = False
2240− notNull (_, Array a) = (not . V.null) a
2241− notNull _ = True
2242−
2243−
2244−instance ToJSON SimpleQueryStringQuery where
2245− toJSON SimpleQueryStringQuery {..} =
2246− omitNulls (base ++ maybeAdd)
2247− where base = [ "query" .= simpleQueryStringQuery ]
2248− maybeAdd = [ "fields" .= simpleQueryStringField
2249− , "default_operator" .= simpleQueryStringOperator
2250− , "analyzer" .= simpleQueryStringAnalyzer
2251− , "flags" .= simpleQueryStringFlags
2252− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2253− , "locale" .= simpleQueryStringLocale ]
2254−
2255−instance FromJSON SimpleQueryStringQuery where
2256− parseJSON = withObject "SimpleQueryStringQuery" parse
2257− where parse o = SimpleQueryStringQuery <$> o .: "query"
2258− <*> o .:? "fields"
2259− <*> o .:? "default_operator"
2260− <*> o .:? "analyzer"
2261− <*> (parseFlags <$> o .:? "flags")
2262− <*> o .:? "lowercase_expanded_terms"
2263− <*> o .:? "locale"
2264− parseFlags (Just (x:xs)) = Just (x :| xs)
2265− parseFlags _ = Nothing
2266−
2267−instance ToJSON FieldOrFields where
2268− toJSON (FofField fieldName) =
2269− toJSON fieldName
2270− toJSON (FofFields fieldNames) =
2271− toJSON fieldNames
2272−
2273−instance FromJSON FieldOrFields where
2274− parseJSON v = FofField <$> parseJSON v
2275− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2276−
2277−instance ToJSON SimpleQueryFlag where
2278− toJSON SimpleQueryAll = "ALL"
2279− toJSON SimpleQueryNone = "NONE"
2280− toJSON SimpleQueryAnd = "AND"
2281− toJSON SimpleQueryOr = "OR"
2282− toJSON SimpleQueryPrefix = "PREFIX"
2283− toJSON SimpleQueryPhrase = "PHRASE"
2284− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2285− toJSON SimpleQueryEscape = "ESCAPE"
2286− toJSON SimpleQueryWhitespace = "WHITESPACE"
2287− toJSON SimpleQueryFuzzy = "FUZZY"
2288− toJSON SimpleQueryNear = "NEAR"
2289− toJSON SimpleQuerySlop = "SLOP"
2290−
2291−instance FromJSON SimpleQueryFlag where
2292− parseJSON = withText "SimpleQueryFlag" parse
2293− where parse "ALL" = pure SimpleQueryAll
2294− parse "NONE" = pure SimpleQueryNone
2295− parse "AND" = pure SimpleQueryAnd
2296− parse "OR" = pure SimpleQueryOr
2297− parse "PREFIX" = pure SimpleQueryPrefix
2298− parse "PHRASE" = pure SimpleQueryPhrase
2299− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2300− parse "ESCAPE" = pure SimpleQueryEscape
2301− parse "WHITESPACE" = pure SimpleQueryWhitespace
2302− parse "FUZZY" = pure SimpleQueryFuzzy
2303− parse "NEAR" = pure SimpleQueryNear
2304− parse "SLOP" = pure SimpleQuerySlop
2305− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2306−
2307−instance ToJSON RegexpQuery where
2308− toJSON (RegexpQuery (FieldName rqQueryField)
2309− (Regexp regexpQueryQuery) rqQueryFlags
2310− rqQueryBoost) =
2311− object [ rqQueryField .= omitNulls base ]
2312− where base = [ "value" .= regexpQueryQuery
2313− , "flags" .= rqQueryFlags
2314− , "boost" .= rqQueryBoost ]
2315−
2316−instance FromJSON RegexpQuery where
2317− parseJSON = withObject "RegexpQuery" parse
2318− where parse = fieldTagged $ \fn o ->
2319− RegexpQuery fn
2320− <$> o .: "value"
2321− <*> o .: "flags"
2322− <*> o .:? "boost"
2323−
2324−instance ToJSON QueryStringQuery where
2325− toJSON (QueryStringQuery qsQueryString
2326− qsDefaultField qsOperator
2327− qsAnalyzer qsAllowWildcard
2328− qsLowercaseExpanded qsEnablePositionIncrements
2329− qsFuzzyMaxExpansions qsFuzziness
2330− qsFuzzyPrefixLength qsPhraseSlop
2331− qsBoost qsAnalyzeWildcard
2332− qsGeneratePhraseQueries qsMinimumShouldMatch
2333− qsLenient qsLocale) =
2334− omitNulls base
2335− where
2336− base = [ "query" .= qsQueryString
2337− , "default_field" .= qsDefaultField
2338− , "default_operator" .= qsOperator
2339− , "analyzer" .= qsAnalyzer
2340− , "allow_leading_wildcard" .= qsAllowWildcard
2341− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2342− , "enable_position_increments" .= qsEnablePositionIncrements
2343− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2344− , "fuzziness" .= qsFuzziness
2345− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2346− , "phrase_slop" .= qsPhraseSlop
2347− , "boost" .= qsBoost
2348− , "analyze_wildcard" .= qsAnalyzeWildcard
2349− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2350− , "minimum_should_match" .= qsMinimumShouldMatch
2351− , "lenient" .= qsLenient
2352− , "locale" .= qsLocale ]
2353−
2354−instance FromJSON QueryStringQuery where
2355− parseJSON = withObject "QueryStringQuery" parse
2356− where parse o = QueryStringQuery
2357− <$> o .: "query"
2358− <*> o .:? "default_field"
2359− <*> o .:? "default_operator"
2360− <*> o .:? "analyzer"
2361− <*> o .:? "allow_leading_wildcard"
2362− <*> o .:? "lowercase_expanded_terms"
2363− <*> o .:? "enable_position_increments"
2364− <*> o .:? "fuzzy_max_expansions"
2365− <*> o .:? "fuzziness"
2366− <*> o .:? "fuzzy_prefix_length"
2367− <*> o .:? "phrase_slop"
2368− <*> o .:? "boost"
2369− <*> o .:? "analyze_wildcard"
2370− <*> o .:? "auto_generate_phrase_queries"
2371− <*> o .:? "minimum_should_match"
2372− <*> o .:? "lenient"
2373− <*> o .:? "locale"
2374−
2375−instance ToJSON RangeQuery where
2376− toJSON (RangeQuery (FieldName fieldName) range boost) =
2377− object [ fieldName .= object conjoined ]
2378− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2379−
2380−instance FromJSON RangeQuery where
2381− parseJSON = withObject "RangeQuery" parse
2382− where parse = fieldTagged $ \fn o ->
2383− RangeQuery fn
2384− <$> parseJSON (Object o)
2385− <*> o .: "boost"
2386−
2387−instance FromJSON RangeValue where
2388− parseJSON = withObject "RangeValue" parse
2389− where parse o = parseDate o
2390− <|> parseDouble o
2391− parseDate o = do lt <- o .:? "lt"
2392− lte <- o .:? "lte"
2393− gt <- o .:? "gt"
2394− gte <- o .:? "gte"
2395− case (lt, lte, gt, gte) of
2396− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2397− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2398− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2399− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2400− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2401− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2402− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2403− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2404− (Nothing, Nothing, Nothing, Nothing) -> mzero
2405− parseDouble o = do lt <- o .:? "lt"
2406− lte <- o .:? "lte"
2407− gt <- o .:? "gt"
2408− gte <- o .:? "gte"
2409− case (lt, lte, gt, gte) of
2410− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2411− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2412− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2413− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2414− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2415− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2416− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2417− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2418− (Nothing, Nothing, Nothing, Nothing) -> mzero
2419−
2420−instance ToJSON PrefixQuery where
2421− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2422− object [ fieldName .= omitNulls base ]
2423− where base = [ "value" .= queryValue
2424− , "boost" .= boost ]
2425−
2426−instance FromJSON PrefixQuery where
2427− parseJSON = withObject "PrefixQuery" parse
2428− where parse = fieldTagged $ \fn o ->
2429− PrefixQuery fn
2430− <$> o .: "value"
2431− <*> o .:? "boost"
2432−
2433−instance ToJSON NestedQuery where
2434− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2435− object [ "path" .= nqPath
2436− , "score_mode" .= nqScoreType
2437− , "query" .= nqQuery ]
2438−
2439−instance FromJSON NestedQuery where
2440− parseJSON = withObject "NestedQuery" parse
2441− where parse o = NestedQuery
2442− <$> o .: "path"
2443− <*> o .: "score_mode"
2444− <*> o .: "query"
2445−
2446−instance ToJSON MoreLikeThisFieldQuery where
2447− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2448− percent mtf mqt stopwords mindf maxdf
2449− minwl maxwl boostTerms boost analyzer) =
2450− object [ fieldName .= omitNulls base ]
2451− where base = [ "like_text" .= text
2452− , "percent_terms_to_match" .= percent
2453− , "min_term_freq" .= mtf
2454− , "max_query_terms" .= mqt
2455− , "stop_words" .= stopwords
2456− , "min_doc_freq" .= mindf
2457− , "max_doc_freq" .= maxdf
2458− , "min_word_length" .= minwl
2459− , "max_word_length" .= maxwl
2460− , "boost_terms" .= boostTerms
2461− , "boost" .= boost
2462− , "analyzer" .= analyzer ]
2463−
2464−instance FromJSON MoreLikeThisFieldQuery where
2465− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2466− where parse = fieldTagged $ \fn o ->
2467− MoreLikeThisFieldQuery
2468− <$> o .: "like_text"
2469− <*> pure fn
2470− <*> o .:? "percent_terms_to_match"
2471− <*> o .:? "min_term_freq"
2472− <*> o .:? "max_query_terms"
2473− <*> (optionalNE =<< o .:? "stop_words")
2474− <*> o .:? "min_doc_freq"
2475− <*> o .:? "max_doc_freq"
2476− <*> o .:? "min_word_length"
2477− <*> o .:? "max_word_length"
2478− <*> o .:? "boost_terms"
2479− <*> o .:? "boost"
2480− <*> o .:? "analyzer"
2481− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2482−
2483−instance ToJSON MoreLikeThisQuery where
2484− toJSON (MoreLikeThisQuery text fields percent
2485− mtf mqt stopwords mindf maxdf
2486− minwl maxwl boostTerms boost analyzer) =
2487− omitNulls base
2488− where base = [ "like_text" .= text
2489− , "fields" .= fields
2490− , "percent_terms_to_match" .= percent
2491− , "min_term_freq" .= mtf
2492− , "max_query_terms" .= mqt
2493− , "stop_words" .= stopwords
2494− , "min_doc_freq" .= mindf
2495− , "max_doc_freq" .= maxdf
2496− , "min_word_length" .= minwl
2497− , "max_word_length" .= maxwl
2498− , "boost_terms" .= boostTerms
2499− , "boost" .= boost
2500− , "analyzer" .= analyzer ]
2501−
2502−instance FromJSON MoreLikeThisQuery where
2503− parseJSON = withObject "MoreLikeThisQuery" parse
2504− where parse o = MoreLikeThisQuery
2505− <$> o .: "like_text"
2506− <*> (optionalNE =<< o .:? "fields")
2507− <*> o .:? "percent_terms_to_match"
2508− <*> o .:? "min_term_freq"
2509− <*> o .:? "max_query_terms"
2510− <*> (optionalNE =<< o .:? "stop_words")
2511− <*> o .:? "min_doc_freq"
2512− <*> o .:? "max_doc_freq"
2513− <*> o .:? "min_word_length"
2514− <*> o .:? "max_word_length"
2515− <*> o .:? "boost_terms"
2516− <*> o .:? "boost"
2517− <*> o .:? "analyzer"
2518− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2519−
2520−instance ToJSON IndicesQuery where
2521− toJSON (IndicesQuery indices query noMatch) =
2522− omitNulls [ "indices" .= indices
2523− , "no_match_query" .= noMatch
2524− , "query" .= query ]
2525−
2526−instance FromJSON IndicesQuery where
2527− parseJSON = withObject "IndicesQuery" parse
2528− where parse o = IndicesQuery
2529− <$> o .:? "indices" .!= []
2530− <*> o .: "query"
2531− <*> o .:? "no_match_query"
2532−
2533−instance ToJSON HasParentQuery where
2534− toJSON (HasParentQuery queryType query scoreType) =
2535− omitNulls [ "parent_type" .= queryType
2536− , "score_type" .= scoreType
2537− , "query" .= query ]
2538−
2539−instance FromJSON HasParentQuery where
2540− parseJSON = withObject "HasParentQuery" parse
2541− where parse o = HasParentQuery
2542− <$> o .: "parent_type"
2543− <*> o .: "query"
2544− <*> o .:? "score_type"
2545−
2546−instance ToJSON HasChildQuery where
2547− toJSON (HasChildQuery queryType query scoreType) =
2548− omitNulls [ "query" .= query
2549− , "score_type" .= scoreType
2550− , "type" .= queryType ]
2551−
2552−instance FromJSON HasChildQuery where
2553− parseJSON = withObject "HasChildQuery" parse
2554− where parse o = HasChildQuery
2555− <$> o .: "type"
2556− <*> o .: "query"
2557− <*> o .:? "score_type"
2558−
2559−instance ToJSON FuzzyQuery where
2560− toJSON (FuzzyQuery (FieldName fieldName) queryText
2561− prefixLength maxEx fuzziness boost) =
2562− object [ fieldName .= omitNulls base ]
2563− where base = [ "value" .= queryText
2564− , "fuzziness" .= fuzziness
2565− , "prefix_length" .= prefixLength
2566− , "boost" .= boost
2567− , "max_expansions" .= maxEx ]
2568−
2569−instance FromJSON FuzzyQuery where
2570− parseJSON = withObject "FuzzyQuery" parse
2571− where parse = fieldTagged $ \fn o ->
2572− FuzzyQuery fn
2573− <$> o .: "value"
2574− <*> o .: "prefix_length"
2575− <*> o .: "max_expansions"
2576− <*> o .: "fuzziness"
2577− <*> o .:? "boost"
2578−
2579−instance ToJSON FuzzyLikeFieldQuery where
2580− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2581− fieldText maxTerms ignoreFreq fuzziness prefixLength
2582− boost analyzer) =
2583− object [ fieldName .=
2584− omitNulls [ "like_text" .= fieldText
2585− , "max_query_terms" .= maxTerms
2586− , "ignore_tf" .= ignoreFreq
2587− , "fuzziness" .= fuzziness
2588− , "prefix_length" .= prefixLength
2589− , "analyzer" .= analyzer
2590− , "boost" .= boost ]]
2591−
2592−instance FromJSON FuzzyLikeFieldQuery where
2593− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2594− where parse = fieldTagged $ \fn o ->
2595− FuzzyLikeFieldQuery fn
2596− <$> o .: "like_text"
2597− <*> o .: "max_query_terms"
2598− <*> o .: "ignore_tf"
2599− <*> o .: "fuzziness"
2600− <*> o .: "prefix_length"
2601− <*> o .: "boost"
2602− <*> o .:? "analyzer"
2603−
2604−instance ToJSON FuzzyLikeThisQuery where
2605− toJSON (FuzzyLikeThisQuery fields text maxTerms
2606− ignoreFreq fuzziness prefixLength boost analyzer) =
2607− omitNulls base
2608− where base = [ "fields" .= fields
2609− , "like_text" .= text
2610− , "max_query_terms" .= maxTerms
2611− , "ignore_tf" .= ignoreFreq
2612− , "fuzziness" .= fuzziness
2613− , "prefix_length" .= prefixLength
2614− , "analyzer" .= analyzer
2615− , "boost" .= boost ]
2616−
2617−instance FromJSON FuzzyLikeThisQuery where
2618− parseJSON = withObject "FuzzyLikeThisQuery" parse
2619− where parse o = FuzzyLikeThisQuery
2620− <$> o .:? "fields" .!= []
2621− <*> o .: "like_text"
2622− <*> o .: "max_query_terms"
2623− <*> o .: "ignore_tf"
2624− <*> o .: "fuzziness"
2625− <*> o .: "prefix_length"
2626− <*> o .: "boost"
2627− <*> o .:? "analyzer"
2628−
2629−instance ToJSON FilteredQuery where
2630− toJSON (FilteredQuery query fFilter) =
2631− object [ "query" .= query
2632− , "filter" .= fFilter ]
2633−
2634−instance FromJSON FilteredQuery where
2635− parseJSON = withObject "FilteredQuery" parse
2636− where parse o = FilteredQuery
2637− <$> o .: "query"
2638− <*> o .: "filter"
2639−
2640−instance ToJSON DisMaxQuery where
2641− toJSON (DisMaxQuery queries tiebreaker boost) =
2642− omitNulls base
2643− where base = [ "queries" .= queries
2644− , "boost" .= boost
2645− , "tie_breaker" .= tiebreaker ]
2646−
2647−instance FromJSON DisMaxQuery where
2648− parseJSON = withObject "DisMaxQuery" parse
2649− where parse o = DisMaxQuery
2650− <$> o .:? "queries" .!= []
2651− <*> o .: "tie_breaker"
2652− <*> o .:? "boost"
2653−
2654−instance ToJSON CommonTermsQuery where
2655− toJSON (CommonTermsQuery (FieldName fieldName)
2656− (QueryString query) cf lfo hfo msm
2657− boost analyzer disableCoord) =
2658− object [fieldName .= omitNulls base ]
2659− where base = [ "query" .= query
2660− , "cutoff_frequency" .= cf
2661− , "low_freq_operator" .= lfo
2662− , "minimum_should_match" .= msm
2663− , "boost" .= boost
2664− , "analyzer" .= analyzer
2665− , "disable_coord" .= disableCoord
2666− , "high_freq_operator" .= hfo ]
2667−
2668−instance FromJSON CommonTermsQuery where
2669− parseJSON = withObject "CommonTermsQuery" parse
2670− where parse = fieldTagged $ \fn o ->
2671− CommonTermsQuery fn
2672− <$> o .: "query"
2673− <*> o .: "cutoff_frequency"
2674− <*> o .: "low_freq_operator"
2675− <*> o .: "high_freq_operator"
2676− <*> o .:? "minimum_should_match"
2677− <*> o .:? "boost"
2678− <*> o .:? "analyzer"
2679− <*> o .:? "disable_coord"
2680−
2681−instance ToJSON CommonMinimumMatch where
2682− toJSON (CommonMinimumMatch mm) = toJSON mm
2683− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2684− object [ "low_freq" .= lowF
2685− , "high_freq" .= highF ]
2686−
2687−instance FromJSON CommonMinimumMatch where
2688− parseJSON v = parseMinimum v
2689− <|> parseMinimumHighLow v
2690− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2691− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2692− MinimumMatchHighLow
2693− <$> o .: "low_freq"
2694− <*> o .: "high_freq")
2695−
2696−
2697−instance ToJSON BoostingQuery where
2698− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2699− object [ "positive" .= bqPositiveQuery
2700− , "negative" .= bqNegativeQuery
2701− , "negative_boost" .= bqNegativeBoost ]
2702−
2703−instance FromJSON BoostingQuery where
2704− parseJSON = withObject "BoostingQuery" parse
2705− where parse o = BoostingQuery
2706− <$> o .: "positive"
2707− <*> o .: "negative"
2708− <*> o .: "negative_boost"
2709−
2710−instance ToJSON BoolQuery where
2711− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2712− omitNulls base
2713− where base = [ "must" .= mustM
2714− , "must_not" .= notM
2715− , "should" .= shouldM
2716− , "minimum_should_match" .= bqMin
2717− , "boost" .= boost
2718− , "disable_coord" .= disableCoord ]
2719−
2720−instance FromJSON BoolQuery where
2721− parseJSON = withObject "BoolQuery" parse
2722− where parse o = BoolQuery
2723− <$> o .:? "must" .!= []
2724− <*> o .:? "must_not" .!= []
2725− <*> o .:? "should" .!= []
2726− <*> o .:? "minimum_should_match"
2727− <*> o .:? "boost"
2728− <*> o .:? "disable_coord"
2729−
2730−instance ToJSON MatchQuery where
2731− toJSON (MatchQuery (FieldName fieldName)
2732− (QueryString mqQueryString) booleanOperator
2733− zeroTermsQuery cutoffFrequency matchQueryType
2734− analyzer maxExpansions lenient boost) =
2735− object [ fieldName .= omitNulls base ]
2736− where base = [ "query" .= mqQueryString
2737− , "operator" .= booleanOperator
2738− , "zero_terms_query" .= zeroTermsQuery
2739− , "cutoff_frequency" .= cutoffFrequency
2740− , "type" .= matchQueryType
2741− , "analyzer" .= analyzer
2742− , "max_expansions" .= maxExpansions
2743− , "lenient" .= lenient
2744− , "boost" .= boost ]
2745−
2746−instance FromJSON MatchQuery where
2747− parseJSON = withObject "MatchQuery" parse
2748− where parse = fieldTagged $ \fn o ->
2749− MatchQuery fn
2750− <$> o .: "query"
2751− <*> o .: "operator"
2752− <*> o .: "zero_terms_query"
2753− <*> o .:? "cutoff_frequency"
2754− <*> o .:? "type"
2755− <*> o .:? "analyzer"
2756− <*> o .:? "max_expansions"
2757− <*> o .:? "lenient"
2758− <*> o .:? "boost"
2759−
2760−instance ToJSON MultiMatchQuery where
2761− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2762− ztQ tb mmqt cf analyzer maxEx lenient) =
2763− object ["multi_match" .= omitNulls base]
2764− where base = [ "fields" .= fmap toJSON fields
2765− , "query" .= query
2766− , "operator" .= boolOp
2767− , "zero_terms_query" .= ztQ
2768− , "tiebreaker" .= tb
2769− , "type" .= mmqt
2770− , "cutoff_frequency" .= cf
2771− , "analyzer" .= analyzer
2772− , "max_expansions" .= maxEx
2773− , "lenient" .= lenient ]
2774−
2775−instance FromJSON MultiMatchQuery where
2776− parseJSON = withObject "MultiMatchQuery" parse
2777− where parse raw = do o <- raw .: "multi_match"
2778− MultiMatchQuery
2779− <$> o .:? "fields" .!= []
2780− <*> o .: "query"
2781− <*> o .: "operator"
2782− <*> o .: "zero_terms_query"
2783− <*> o .:? "tiebreaker"
2784− <*> o .:? "type"
2785− <*> o .:? "cutoff_frequency"
2786− <*> o .:? "analyzer"
2787− <*> o .:? "max_expansions"
2788− <*> o .:? "lenient"
2789−
2790−instance ToJSON MultiMatchQueryType where
2791− toJSON MultiMatchBestFields = "best_fields"
2792− toJSON MultiMatchMostFields = "most_fields"
2793− toJSON MultiMatchCrossFields = "cross_fields"
2794− toJSON MultiMatchPhrase = "phrase"
2795− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2796−
2797−instance FromJSON MultiMatchQueryType where
2798− parseJSON = withText "MultiMatchPhrasePrefix" parse
2799− where parse "best_fields" = pure MultiMatchBestFields
2800− parse "most_fields" = pure MultiMatchMostFields
2801− parse "cross_fields" = pure MultiMatchCrossFields
2802− parse "phrase" = pure MultiMatchPhrase
2803− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2804− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2805−
2806−instance ToJSON BooleanOperator where
2807− toJSON And = String "and"
2808− toJSON Or = String "or"
2809−
2810−instance FromJSON BooleanOperator where
2811− parseJSON = withText "BooleanOperator" parse
2812− where parse "and" = pure And
2813− parse "or" = pure Or
2814− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2815−
2816−instance ToJSON ZeroTermsQuery where
2817− toJSON ZeroTermsNone = String "none"
2818− toJSON ZeroTermsAll = String "all"
2819−
2820−instance FromJSON ZeroTermsQuery where
2821− parseJSON = withText "ZeroTermsQuery" parse
2822− where parse "none" = pure ZeroTermsNone
2823− parse "all" = pure ZeroTermsAll
2824− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2825−
2826−instance ToJSON MatchQueryType where
2827− toJSON MatchPhrase = "phrase"
2828− toJSON MatchPhrasePrefix = "phrase_prefix"
2829−
2830−instance FromJSON MatchQueryType where
2831− parseJSON = withText "MatchQueryType" parse
2832− where parse "phrase" = pure MatchPhrase
2833− parse "phrase_prefix" = pure MatchPhrasePrefix
2834− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2835−
2836−instance FromJSON Status where
2837− parseJSON (Object v) = Status <$>
2838− v .:? "ok" <*>
2839− v .: "status" <*>
2840− v .: "name" <*>
2841− v .: "version" <*>
2842− v .: "tagline"
2843− parseJSON _ = empty
2844−
2845−
2846−instance ToJSON IndexSettings where
2847− toJSON (IndexSettings s r) = object ["settings" .=
2848− object ["index" .=
2849− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2850− ]
2851− ]
2852−
2853−instance FromJSON IndexSettings where
2854− parseJSON = withObject "IndexSettings" parse
2855− where parse o = do s <- o .: "settings"
2856− i <- s .: "index"
2857− IndexSettings <$> i .: "number_of_shards"
2858− <*> i .: "number_of_replicas"
2859−
2860−instance ToJSON UpdatableIndexSetting where
2861− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2862− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2863− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2864− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2865− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2866− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2867− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2868− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2869− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2870− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2871− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2872− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2873− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2874− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2875− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2876− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2877− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2878− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2879− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2880− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2881− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2882− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2883− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2884− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2885− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2886− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2887− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2888− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2889−
2890−instance FromJSON UpdatableIndexSetting where
2891− parseJSON = withObject "UpdatableIndexSetting" parse
2892− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2893− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2894− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2895− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2896− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2897− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2898− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2899− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2900− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2901− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2902− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2903− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2904− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2905− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2906− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2907− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2908− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2909− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2910− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2911− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2912− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2913− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2914− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2915− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2916− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2917− <|> blocksRead `taggedAt` ["blocks", "read"]
2918− <|> blocksWrite `taggedAt` ["blocks", "write"]
2919− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2920− where taggedAt f ks = taggedAt' f (Object o) ks
2921− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON =<< unStringlyTypeJSON v))
2922− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
2923− taggedAt' f v' ks) v
2924− numberOfReplicas = pure . NumberOfReplicas
2925− autoExpandReplicas = pure . AutoExpandReplicas
2926− refreshInterval = pure . RefreshInterval . ndtJSON
2927− indexConcurrency = pure . IndexConcurrency
2928− failOnMergeFailure = pure . FailOnMergeFailure
2929− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
2930− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
2931− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
2932− translogDisableFlush = pure . TranslogDisableFlush
2933− cacheFilterMaxSize = pure . CacheFilterMaxSize
2934− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
2935− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
2936− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
2937− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
2938− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
2939− routingAllocationEnable = pure . RoutingAllocationEnable
2940− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
2941− recoveryInitialShards = pure . RecoveryInitialShards
2942− gcDeletes = pure . GCDeletes . ndtJSON
2943− ttlDisablePurge = pure . TTLDisablePurge
2944− translogFSType = pure . TranslogFSType
2945− compoundFormat = pure . IndexCompoundFormat
2946− compoundOnFlush = pure . IndexCompoundOnFlush
2947− warmerEnabled = pure . WarmerEnabled
2948− blocksReadOnly = pure . BlocksReadOnly
2949− blocksRead = pure . BlocksRead
2950− blocksWrite = pure . BlocksWrite
2951− blocksMetaData = pure . BlocksMetaData
2952−
2953−instance FromJSON IndexSettingsSummary where
2954− parseJSON = withObject "IndexSettingsSummary" parse
2955− where parse o = case HM.toList o of
2956− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
2957− <$> parseJSON v
2958− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
2959− _ -> fail "Expected single-key object with index name"
2960− redundant (NumberOfReplicas _) = True
2961− redundant _ = False
2962−
2963−-- | For some reason in the settings API, all leaf values get returned
2964−-- as strings. This function attepmts to recover from this for all
2965−-- non-recursive JSON types. If nothing can be done or the same value
2966−-- would be return, it returns 'mzero'
2967−unStringlyTypeJSON :: MonadPlus m => Value -> m Value
2968−unStringlyTypeJSON (String "true") = return (Bool True)
2969−unStringlyTypeJSON (String "false") = return (Bool False)
2970−unStringlyTypeJSON (String "null") = return Null
2971−unStringlyTypeJSON (String t) = case readMay (T.unpack t) of
2972− Just n -> return (Number n)
2973− Nothing -> mzero
2974−unStringlyTypeJSON _ = mzero
2975−
2976−
2977−parseSettings :: Object -> Parser [UpdatableIndexSetting]
2978−parseSettings o = do
2979− o' <- o .: "index"
2980− -- slice the index object into singleton hashmaps and try to parse each
2981− parses <- forM (HM.toList o') $ \(k, v) -> do
2982− -- blocks are now nested into the "index" key, which is not how they're serialized
2983− let atRoot = Object (HM.singleton k v)
2984− let atIndex = Object (HM.singleton "index" atRoot)
2985− optional (parseJSON atRoot <|> parseJSON atIndex)
2986− return (catMaybes parses)
2987−
2988−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2989−oPath (k :| []) v = object [k .= v]
2990−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2991−
2992−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2993−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2994− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2995−
2996−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
2997−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
2998− where parse o = case HM.toList o of
2999− [] -> fail "Expected non-empty list of NodeAttrFilters"
3000− x:xs -> DT.mapM (uncurry parse') (x :| xs)
3001− parse' n = withText "Text" $ \t ->
3002− case T.splitOn "," t of
3003− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3004− [] -> fail "Expected non-empty list of filter values"
3005−
3006−instance ToJSON ReplicaBounds where
3007− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3008− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3009− toJSON ReplicasUnbounded = Bool False
3010−
3011−instance FromJSON ReplicaBounds where
3012− parseJSON v = withText "ReplicaBounds" parseText v
3013− <|> withBool "ReplicaBounds" parseBool v
3014− where parseText t = case T.splitOn "-" t of
3015− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3016− [a, b] -> ReplicasBounded <$> parseReadText a
3017− <*> parseReadText b
3018− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3019− parseBool False = pure ReplicasUnbounded
3020− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3021−
3022−instance ToJSON AllocationPolicy where
3023− toJSON AllocAll = String "all"
3024− toJSON AllocPrimaries = String "primaries"
3025− toJSON AllocNewPrimaries = String "new_primaries"
3026− toJSON AllocNone = String "none"
3027−
3028−instance FromJSON AllocationPolicy where
3029− parseJSON = withText "AllocationPolicy" parse
3030− where parse "all" = pure AllocAll
3031− parse "primaries" = pure AllocPrimaries
3032− parse "new_primaries" = pure AllocNewPrimaries
3033− parse "none" = pure AllocNone
3034− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3035−
3036−instance ToJSON InitialShardCount where
3037− toJSON QuorumShards = String "quorum"
3038− toJSON QuorumMinus1Shards = String "quorum-1"
3039− toJSON FullShards = String "full"
3040− toJSON FullMinus1Shards = String "full-1"
3041− toJSON (ExplicitShards x) = toJSON x
3042−
3043−instance FromJSON InitialShardCount where
3044− parseJSON v = withText "InitialShardCount" parseText v
3045− <|> ExplicitShards <$> parseJSON v
3046− where parseText "quorum" = pure QuorumShards
3047− parseText "quorum-1" = pure QuorumMinus1Shards
3048− parseText "full" = pure FullShards
3049− parseText "full-1" = pure FullMinus1Shards
3050− parseText _ = mzero
3051−
3052−instance ToJSON FSType where
3053− toJSON FSSimple = "simple"
3054− toJSON FSBuffered = "buffered"
3055−
3056−instance FromJSON FSType where
3057− parseJSON = withText "FSType" parse
3058− where parse "simple" = pure FSSimple
3059− parse "buffered" = pure FSBuffered
3060− parse t = fail ("Invalid FSType: " <> show t)
3061−
3062−instance ToJSON CompoundFormat where
3063− toJSON (CompoundFileFormat x) = Bool x
3064− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3065−
3066−instance FromJSON CompoundFormat where
3067− parseJSON v = CompoundFileFormat <$> parseJSON v
3068− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3069−
3070−instance ToJSON NominalDiffTimeJSON where
3071− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3072−
3073−instance FromJSON NominalDiffTimeJSON where
3074− parseJSON = withText "NominalDiffTime" parse
3075− where parse t = case T.takeEnd 1 t of
3076− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3077− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3078−
3079−instance ToJSON IndexTemplate where
3080− toJSON (IndexTemplate p s m) = merge
3081− (object [ "template" .= p
3082− , "mappings" .= foldl' merge (object []) m
3083− ])
3084− (toJSON s)
3085− where
3086− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3087− merge o Null = o
3088− merge _ _ = undefined
3089−
3090−instance (FromJSON a) => FromJSON (EsResult a) where
3091− parseJSON jsonVal@(Object v) = do
3092− found <- v .:? "found" .!= False
3093− fr <- if found
3094− then parseJSON jsonVal
3095− else return Nothing
3096− EsResult <$> v .: "_index" <*>
3097− v .: "_type" <*>
3098− v .: "_id" <*>
3099− pure fr
3100− parseJSON _ = empty
3101−
3102−instance (FromJSON a) => FromJSON (EsResultFound a) where
3103− parseJSON (Object v) = EsResultFound <$>
3104− v .: "_version" <*>
3105− v .: "_source"
3106− parseJSON _ = empty
3107−
3108−instance FromJSON EsError where
3109− parseJSON (Object v) = EsError <$>
3110− v .: "status" <*>
3111− v .: "error"
3112− parseJSON _ = empty
3113−
3114−instance FromJSON IndexAliasesSummary where
3115− parseJSON = withObject "IndexAliasesSummary" parse
3116− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3117− go ixn = withObject "index aliases" $ \ia -> do
3118− aliases <- ia .:? "aliases" .!= mempty
3119− forM (HM.toList aliases) $ \(aName, v) -> do
3120− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3121− IndexAliasSummary indexAlias <$> parseJSON v
3122−
3123−
3124−instance ToJSON IndexAliasAction where
3125− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3126− where Object iaObj = toJSON ia
3127− Object optsObj = toJSON opts
3128− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3129− where Object iaObj = toJSON ia
3130−
3131−instance ToJSON IndexAlias where
3132− toJSON IndexAlias {..} = object ["index" .= srcIndex
3133− , "alias" .= indexAlias
3134− ]
3135−
3136−instance ToJSON IndexAliasCreate where
3137− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3138− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3139− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3140−
3141−instance ToJSON AliasRouting where
3142− toJSON (AllAliasRouting v) = object ["routing" .= v]
3143− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3144− where prs = [("search_routing" .=) <$> srch
3145− ,("index_routing" .=) <$> idx]
3146−
3147−instance FromJSON AliasRouting where
3148− parseJSON = withObject "AliasRouting" parse
3149− where parse o = parseAll o <|> parseGranular o
3150− parseAll o = AllAliasRouting <$> o .: "routing"
3151− parseGranular o = do
3152− sr <- o .:? "search_routing"
3153− ir <- o .:? "index_routing"
3154− if isNothing sr && isNothing ir
3155− then fail "Both search_routing and index_routing can't be blank"
3156− else return (GranularAliasRouting sr ir)
3157−
3158−instance FromJSON IndexAliasCreate where
3159− parseJSON v = withObject "IndexAliasCreate" parse v
3160− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3161− <*> o .:? "filter"
3162−
3163−instance ToJSON SearchAliasRouting where
3164− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3165−
3166−instance FromJSON SearchAliasRouting where
3167− parseJSON = withText "SearchAliasRouting" parse
3168− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3169−
3170−instance ToJSON Search where
3171− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3172− omitNulls [ "query" .= query
3173− , "filter" .= sFilter
3174− , "sort" .= sort
3175− , "aggregations" .= searchAggs
3176− , "highlight" .= highlight
3177− , "from" .= sFrom
3178− , "size" .= sSize
3179− , "track_scores" .= sTrackSortScores
3180− , "fields" .= sFields
3181− , "_source" .= sSource]
3182−
3183−
3184−instance ToJSON Source where
3185− toJSON NoSource = toJSON False
3186− toJSON (SourcePatterns patterns) = toJSON patterns
3187− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3188−
3189−instance ToJSON PatternOrPatterns where
3190− toJSON (PopPattern pattern) = toJSON pattern
3191− toJSON (PopPatterns patterns) = toJSON patterns
3192−
3193−instance ToJSON Include where
3194− toJSON (Include patterns) = toJSON patterns
3195−
3196−instance ToJSON Exclude where
3197− toJSON (Exclude patterns) = toJSON patterns
3198−
3199−instance ToJSON Pattern where
3200− toJSON (Pattern pattern) = toJSON pattern
3201−
3202−
3203−instance ToJSON FieldHighlight where
3204− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3205− object [ fName .= fSettings ]
3206− toJSON (FieldHighlight (FieldName fName) Nothing) =
3207− object [ fName .= emptyObject ]
3208−
3209−instance ToJSON Highlights where
3210− toJSON (Highlights global fields) =
3211− omitNulls (("fields" .= fields)
3212− : highlightSettingsPairs global)
3213−
3214−instance ToJSON HighlightSettings where
3215− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3216−
3217−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3218−highlightSettingsPairs Nothing = []
3219−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3220−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3221−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3222−
3223−
3224−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3225−plainHighPairs Nothing = []
3226−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3227− [ "type" .= String "plain"]
3228− ++ commonHighlightPairs plCom
3229− ++ nonPostingsToPairs plNonPost
3230−
3231−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3232−postHighPairs Nothing = []
3233−postHighPairs (Just (PostingsHighlight pCom)) =
3234− ("type" .= String "postings")
3235− : commonHighlightPairs pCom
3236−
3237−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3238−fastVectorHighPairs Nothing = []
3239−fastVectorHighPairs (Just
3240− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3241− fvBoundMaxScan fvFragOff fvMatchedFields
3242− fvPhraseLim)) =
3243− [ "type" .= String "fvh"
3244− , "boundary_chars" .= fvBoundChars
3245− , "boundary_max_scan" .= fvBoundMaxScan
3246− , "fragment_offset" .= fvFragOff
3247− , "matched_fields" .= fvMatchedFields
3248− , "phraseLimit" .= fvPhraseLim]
3249− ++ commonHighlightPairs fvCom
3250− ++ nonPostingsToPairs fvNonPostSettings
3251−
3252−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3253−deleteSeveral ks hm = foldr HM.delete hm ks
3254−
3255−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3256−commonHighlightPairs Nothing = []
3257−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3258− chNoMatchSize chHighlightQuery
3259− chRequireFieldMatch)) =
3260− [ "order" .= chScore
3261− , "force_source" .= chForceSource
3262− , "encoder" .= chEncoder
3263− , "no_match_size" .= chNoMatchSize
3264− , "highlight_query" .= chHighlightQuery
3265− , "require_fieldMatch" .= chRequireFieldMatch]
3266− ++ highlightTagToPairs chTag
3267−
3268−
3269−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3270−nonPostingsToPairs Nothing = []
3271−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3272− [ "fragment_size" .= npFragSize
3273− , "number_of_fragments" .= npNumOfFrags]
3274−
3275−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3276−parseNEJSON [] = fail "Expected non-empty list"
3277−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3278−
3279−
3280−instance ToJSON HighlightEncoder where
3281− toJSON DefaultEncoder = String "default"
3282− toJSON HTMLEncoder = String "html"
3283−
3284−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3285−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3286−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3287− , "post_tags" .= post]
3288−highlightTagToPairs Nothing = []
3289−
3290−instance ToJSON SortSpec where
3291− toJSON (DefaultSortSpec
3292− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3293− dsSortMode dsMissingSort dsNestedFilter)) =
3294− object [dsSortFieldName .= omitNulls base] where
3295− base = [ "order" .= dsSortOrder
3296− , "ignore_unmapped" .= dsIgnoreUnmapped
3297− , "mode" .= dsSortMode
3298− , "missing" .= dsMissingSort
3299− , "nested_filter" .= dsNestedFilter ]
3300−
3301− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3302− object [ "unit" .= units
3303− , field .= gdsLatLon
3304− , "order" .= gdsSortOrder ]
3305−
3306−
3307−instance ToJSON SortOrder where
3308− toJSON Ascending = String "asc"
3309− toJSON Descending = String "desc"
3310−
3311−
3312−instance ToJSON SortMode where
3313− toJSON SortMin = String "min"
3314− toJSON SortMax = String "max"
3315− toJSON SortSum = String "sum"
3316− toJSON SortAvg = String "avg"
3317−
3318−
3319−instance ToJSON Missing where
3320− toJSON LastMissing = String "_last"
3321− toJSON FirstMissing = String "_first"
3322− toJSON (CustomMissing txt) = String txt
3323−
3324−
3325−instance ToJSON ScoreType where
3326− toJSON ScoreTypeMax = "max"
3327− toJSON ScoreTypeAvg = "avg"
3328− toJSON ScoreTypeSum = "sum"
3329− toJSON ScoreTypeNone = "none"
3330−
3331−instance FromJSON ScoreType where
3332− parseJSON = withText "ScoreType" parse
3333− where parse "max" = pure ScoreTypeMax
3334− parse "avg" = pure ScoreTypeAvg
3335− parse "sum" = pure ScoreTypeSum
3336− parse "none" = pure ScoreTypeNone
3337− parse t = fail ("Unexpected ScoreType: " <> show t)
3338−
3339−instance ToJSON Distance where
3340− toJSON (Distance dCoefficient dUnit) =
3341− String boltedTogether where
3342− coefText = showText dCoefficient
3343− (String unitText) = toJSON dUnit
3344− boltedTogether = mappend coefText unitText
3345−
3346−instance FromJSON Distance where
3347− parseJSON = withText "Distance" parse
3348− where parse t = Distance <$> parseCoeff nT
3349− <*> parseJSON (String unitT)
3350− where (nT, unitT) = T.span validForNumber t
3351− -- may be a better way to do this
3352− validForNumber '-' = True
3353− validForNumber '.' = True
3354− validForNumber 'e' = True
3355− validForNumber c = isNumber c
3356− parseCoeff "" = fail "Empty string cannot be parsed as number"
3357− parseCoeff s = return (read (T.unpack s))
3358−
3359−instance ToJSON DistanceUnit where
3360− toJSON Miles = String "mi"
3361− toJSON Yards = String "yd"
3362− toJSON Feet = String "ft"
3363− toJSON Inches = String "in"
3364− toJSON Kilometers = String "km"
3365− toJSON Meters = String "m"
3366− toJSON Centimeters = String "cm"
3367− toJSON Millimeters = String "mm"
3368− toJSON NauticalMiles = String "nmi"
3369−
3370−
3371−instance FromJSON DistanceUnit where
3372− parseJSON = withText "DistanceUnit" parse
3373− where parse "mi" = pure Miles
3374− parse "yd" = pure Yards
3375− parse "ft" = pure Feet
3376− parse "in" = pure Inches
3377− parse "km" = pure Kilometers
3378− parse "m" = pure Meters
3379− parse "cm" = pure Centimeters
3380− parse "mm" = pure Millimeters
3381− parse "nmi" = pure NauticalMiles
3382− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3383−
3384−instance ToJSON DistanceType where
3385− toJSON Arc = String "arc"
3386− toJSON SloppyArc = String "sloppy_arc"
3387− toJSON Plane = String "plane"
3388−
3389−instance FromJSON DistanceType where
3390− parseJSON = withText "DistanceType" parse
3391− where parse "arc" = pure Arc
3392− parse "sloppy_arc" = pure SloppyArc
3393− parse "plane" = pure Plane
3394− parse t = fail ("Unrecognized DistanceType: " <> show t)
3395−
3396−
3397−instance ToJSON OptimizeBbox where
3398− toJSON NoOptimizeBbox = String "none"
3399− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3400−
3401−instance FromJSON OptimizeBbox where
3402− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3403− <|> parseOptimize v
3404− where parseNoOptimize "none" = pure NoOptimizeBbox
3405− parseNoOptimize _ = mzero
3406− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3407−
3408−instance ToJSON GeoBoundingBoxConstraint where
3409− toJSON (GeoBoundingBoxConstraint
3410− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3411− object [gbbcGeoBBField .= gbbcConstraintBox
3412− , "_cache" .= cache
3413− , "type" .= type']
3414−
3415−instance FromJSON GeoBoundingBoxConstraint where
3416− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3417− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3418− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3419− <$> parseJSON v
3420− <*> o .:? "_cache" .!= defaultCache
3421− <*> o .: "type"
3422− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3423−
3424−instance ToJSON GeoFilterType where
3425− toJSON GeoFilterMemory = String "memory"
3426− toJSON GeoFilterIndexed = String "indexed"
3427−
3428−instance FromJSON GeoFilterType where
3429− parseJSON = withText "GeoFilterType" parse
3430− where parse "memory" = pure GeoFilterMemory
3431− parse "indexed" = pure GeoFilterIndexed
3432− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3433−
3434−instance ToJSON GeoBoundingBox where
3435− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3436− object ["top_left" .= gbbTopLeft
3437− , "bottom_right" .= gbbBottomRight]
3438−
3439−instance FromJSON GeoBoundingBox where
3440− parseJSON = withObject "GeoBoundingBox" parse
3441− where parse o = GeoBoundingBox
3442− <$> o .: "top_left"
3443− <*> o .: "bottom_right"
3444−
3445−instance ToJSON LatLon where
3446− toJSON (LatLon lLat lLon) =
3447− object ["lat" .= lLat
3448− , "lon" .= lLon]
3449−
3450−instance FromJSON LatLon where
3451− parseJSON = withObject "LatLon" parse
3452− where parse o = LatLon <$> o .: "lat"
3453− <*> o .: "lon"
3454−
3455−-- index for smaller ranges, fielddata for longer ranges
3456−instance ToJSON RangeExecution where
3457− toJSON RangeExecutionIndex = "index"
3458− toJSON RangeExecutionFielddata = "fielddata"
3459−
3460−
3461−instance FromJSON RangeExecution where
3462− parseJSON = withText "RangeExecution" parse
3463− where parse "index" = pure RangeExecutionIndex
3464− parse "fielddata" = pure RangeExecutionFielddata
3465− parse t = error ("Unrecognized RangeExecution " <> show t)
3466−
3467−instance ToJSON RegexpFlags where
3468− toJSON AllRegexpFlags = String "ALL"
3469− toJSON NoRegexpFlags = String "NONE"
3470− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3471− where flagStrs = map flagStr . nub $ h:fs
3472− flagStr AnyString = "ANYSTRING"
3473− flagStr Automaton = "AUTOMATON"
3474− flagStr Complement = "COMPLEMENT"
3475− flagStr Empty = "EMPTY"
3476− flagStr Intersection = "INTERSECTION"
3477− flagStr Interval = "INTERVAL"
3478−
3479−instance FromJSON RegexpFlags where
3480− parseJSON = withText "RegexpFlags" parse
3481− where parse "ALL" = pure AllRegexpFlags
3482− parse "NONE" = pure NoRegexpFlags
3483− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3484−
3485−instance FromJSON RegexpFlag where
3486− parseJSON = withText "RegexpFlag" parse
3487− where parse "ANYSTRING" = pure AnyString
3488− parse "AUTOMATON" = pure Automaton
3489− parse "COMPLEMENT" = pure Complement
3490− parse "EMPTY" = pure Empty
3491− parse "INTERSECTION" = pure Intersection
3492− parse "INTERVAL" = pure Interval
3493− parse f = fail ("Unknown RegexpFlag: " <> show f)
3494−
3495−instance ToJSON Term where
3496− toJSON (Term field value) = object ["term" .= object
3497− [field .= value]]
3498−
3499−instance FromJSON Term where
3500− parseJSON = withObject "Term" parse
3501− where parse o = do termObj <- o .: "term"
3502− case HM.toList termObj of
3503− [(fn, v)] -> Term fn <$> parseJSON v
3504− _ -> fail "Expected object with 1 field-named key"
3505−
3506−instance ToJSON BoolMatch where
3507− toJSON (MustMatch term cache) = object ["must" .= term,
3508− "_cache" .= cache]
3509− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3510− "_cache" .= cache]
3511− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3512− "_cache" .= cache]
3513−
3514−instance FromJSON BoolMatch where
3515− parseJSON = withObject "BoolMatch" parse
3516− where parse o = mustMatch `taggedWith` "must"
3517− <|> mustNotMatch `taggedWith` "must_not"
3518− <|> shouldMatch `taggedWith` "should"
3519− where taggedWith parser k = parser =<< o .: k
3520− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3521− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3522− 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)
3523528
3524529instance (FromJSON a) => FromJSON (SearchResult a) where
3525530 parseJSON (Object v) = SearchResult <$>
@@ -3528,71 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3528533 v .: "_shards" <*>
3529534 v .: "hits" <*>
3530535 v .:? "aggregations" <*>
3531− v .:? "_scroll_id"
3532− parseJSON _ = empty
3533−
3534−instance (FromJSON a) => FromJSON (SearchHits a) where
3535− parseJSON (Object v) = SearchHits <$>
3536− v .: "total" <*>
3537− v .: "max_score" <*>
3538− v .: "hits"
3539− parseJSON _ = empty
3540−
3541−instance (FromJSON a) => FromJSON (Hit a) where
3542− parseJSON (Object v) = Hit <$>
3543− v .: "_index" <*>
3544− v .: "_type" <*>
3545− v .: "_id" <*>
3546− v .: "_score" <*>
3547− v .:? "_source" <*>
3548− v .:? "highlight"
536+ v .:? "_scroll_id" <*>
537+ v .:? "suggest"
3549538 parseJSON _ = empty
3550539
3551−instance FromJSON ShardResult where
3552− parseJSON (Object v) = ShardResult <$>
3553− v .: "total" <*>
3554− v .: "successful" <*>
3555− v .: "failed"
3556− parseJSON _ = empty
3557−
3558−
3559−instance FromJSON DocVersion where
3560− parseJSON v = do
3561− i <- parseJSON v
3562− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3563−
3564−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3565−instance FromJSON ReplicaCount where
3566− parseJSON v = parseAsInt v
3567− <|> parseAsString v
3568− where parseAsInt = fmap ReplicaCount . parseJSON
3569− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3570−
3571−instance FromJSON ShardCount where
3572− parseJSON v = parseAsInt v
3573− <|> parseAsString v
3574− where parseAsInt = fmap ShardCount . parseJSON
3575− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3576−
3577−instance Bounded DocVersion where
3578− minBound = DocVersion 1
3579− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3580−
3581−instance Enum DocVersion where
3582− succ x
3583− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3584− | otherwise = succError "DocVersion"
3585− pred x
3586− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3587− | otherwise = predError "DocVersion"
3588− toEnum i =
3589− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3590− fromEnum = docVersionNumber
3591− enumFrom = boundedEnumFrom
3592− enumFromThen = boundedEnumFromThen
3593−
3594−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3595−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Show, Eq)
3596−
3597−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3598−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Show, Eq)
540+newtype ScrollId =
541+ ScrollId Text
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)