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