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