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