@@ -1,7 +1,10 @@
1+{-# LANGUAGE DeriveDataTypeable #-}
2+{-# LANGUAGE DeriveGeneric #-}
13{-# LANGUAGE FlexibleContexts #-}
24{-# LANGUAGE FlexibleInstances #-}
35{-# LANGUAGE GeneralizedNewtypeDeriving #-}
46{-# LANGUAGE MultiParamTypeClasses #-}
7+-- {-# LANGUAGE NoMonomorphismRestriction #-}
58{-# LANGUAGE NamedFieldPuns #-}
69{-# LANGUAGE OverloadedStrings #-}
710{-# LANGUAGE RecordWildCards #-}
@@ -10,11 +13,11 @@
1013-------------------------------------------------------------------------------
1114-- |
1215-- Module : Database.Bloodhound.Types
13−-- Copyright : (C) 2014, 2018 Chris Allen
16+-- Copyright : (C) 2014, 2015, 2016 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
@@ -44,13 +47,10 @@ module Database.Bloodhound.Types
4447 , mkDateHistogram
4548 , mkCardinalityAggregation
4649 , mkDocVersion
47− , mkStatsAggregation
48− , mkExtendedStatsAggregation
4950 , docVersionNumber
5051 , toMissing
5152 , toTerms
5253 , toDateHistogram
53− , toTopHits
5454 , omitNulls
5555 , BH(..)
5656 , runBH
@@ -62,7 +62,6 @@ module Database.Bloodhound.Types
6262 , MonadBH(..)
6363 , Version(..)
6464 , VersionNumber(..)
65− , MaybeNA(..)
6665 , BuildHash(..)
6766 , Status(..)
6867 , Existence(..)
@@ -71,7 +70,6 @@ module Database.Bloodhound.Types
7170 , UpdatableIndexSetting(..)
7271 , IndexSettingsSummary(..)
7372 , AllocationPolicy(..)
74− , Compression(..)
7573 , ReplicaBounds(..)
7674 , Bytes(..)
7775 , gigabytes
@@ -120,8 +118,8 @@ module Database.Bloodhound.Types
120118 , Pattern(..)
121119 , ShardResult(..)
122120 , Hit(..)
123− , HitFields(..)
124121 , Filter(..)
122+ , Seminearring(..)
125123 , BoolMatch(..)
126124 , Term(..)
127125 , GeoPoint(..)
@@ -148,22 +146,13 @@ module Database.Bloodhound.Types
148146 , RegexpFlags(..)
149147 , RegexpFlag(..)
150148 , FieldName(..)
151− , ScriptFields(..)
152− , ScriptFieldName
153− , ScriptFieldValue
154149 , Script(..)
155− , ScriptLanguage(..)
156− , ScriptInline(..)
157− , ScriptId(..)
158− , ScriptParams(..)
159− , ScriptParamName
160− , ScriptParamValue
161150 , IndexName(..)
162151 , IndexSelection(..)
163152 , NodeSelection(..)
164153 , NodeSelector(..)
165− , ForceMergeIndexSettings(..)
166− , defaultForceMergeIndexSettings
154+ , IndexOptimizationSettings(..)
155+ , defaultIndexOptimizationSettings
167156 , TemplateName(..)
168157 , TemplatePattern(..)
169158 , MappingName(..)
@@ -187,19 +176,8 @@ module Database.Bloodhound.Types
187176 , BoolQuery(..)
188177 , BoostingQuery(..)
189178 , 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(..)
202179 , DisMaxQuery(..)
180+ , FilteredQuery(..)
203181 , FuzzyLikeThisQuery(..)
204182 , FuzzyLikeFieldQuery(..)
205183 , FuzzyQuery(..)
@@ -215,16 +193,10 @@ module Database.Bloodhound.Types
215193 , RangeQuery(..)
216194 , RegexpQuery(..)
217195 , QueryString(..)
218− , TemplateQueryInline(..)
219− , TemplateQueryKeyValuePairs(..)
220− , WildcardQuery(..)
221196 , BooleanOperator(..)
222197 , ZeroTermsQuery(..)
223198 , CutoffFrequency(..)
224199 , Analyzer(..)
225− , Tokenizer(..)
226− , TokenFilter(..)
227− , CharFilter(..)
228200 , MaxExpansions(..)
229201 , Lenient(..)
230202 , MatchQueryType(..)
@@ -287,26 +259,6 @@ module Database.Bloodhound.Types
287259 , NodeName(..)
288260 , ClusterName(..)
289261 , 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(..)
310262 , EsAddress(..)
311263 , PluginName(..)
312264 , NodeInfo(..)
@@ -348,18 +300,6 @@ module Database.Bloodhound.Types
348300 , rrGroupRefNum
349301 , mkRRGroupRefNum
350302 , 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 (..)
363303
364304 , Aggregation(..)
365305 , Aggregations
@@ -372,7 +312,6 @@ module Database.Bloodhound.Types
372312 , ValueCountAggregation(..)
373313 , FilterAggregation(..)
374314 , CardinalityAggregation(..)
375− , MaxAggregation(..)
376315 , DateHistogramAggregation(..)
377316 , DateRangeAggregation(..)
378317 , DateRangeAggRange(..)
@@ -380,9 +319,6 @@ module Database.Bloodhound.Types
380319 , DateMathAnchor(..)
381320 , DateMathModifier(..)
382321 , DateMathUnit(..)
383− , TopHitsAggregation(..)
384− , StatisticsAggregation(..)
385− , SearchAfterKey
386322
387323 , Highlights(..)
388324 , FieldHighlight(..)
@@ -400,32 +336,724 @@ module Database.Bloodhound.Types
400336 , TermsResult(..)
401337 , DateHistogramResult(..)
402338 , DateRangeResult(..)
403− , TopHitResult(..)
404339
405340 , EsUsername(..)
406341 , EsPassword(..)
342+ ) where
407343
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
344+import Control.Applicative as A
345+import Control.Arrow (first)
346+import Control.Monad.Catch
347+import Control.Monad.Except
348+import Control.Monad.Reader
349+import Control.Monad.State
350+import Control.Monad.Writer
351+import Data.Aeson
352+import Data.Aeson.Types (Pair, Parser, emptyObject,
353+ parseEither, parseMaybe)
354+import qualified Data.ByteString.Lazy.Char8 as L
355+import Data.Char
356+import Data.Hashable (Hashable)
357+import qualified Data.HashMap.Strict as HM
358+import Data.List (foldl', intercalate, nub)
359+import Data.List.NonEmpty (NonEmpty (..), toList)
360+import qualified Data.Map.Strict as M
361+import Data.Maybe
362+import Data.Scientific (Scientific)
363+import Data.Text (Text)
364+import qualified Data.Text as T
365+import Data.Time.Calendar
366+import Data.Time.Clock (NominalDiffTime, UTCTime)
367+import Data.Time.Clock.POSIX
368+import qualified Data.Traversable as DT
369+import Data.Typeable (Typeable)
370+import qualified Data.Vector as V
371+import qualified Data.Version as Vers
372+import GHC.Enum
373+import GHC.Generics (Generic)
374+import Network.HTTP.Client
375+import qualified Network.HTTP.Types.Method as NHTM
376+import qualified Text.ParserCombinators.ReadP as RP
377+import qualified Text.Read as TR
378+
379+import Database.Bloodhound.Types.Class
380+import Database.Bloodhound.Types.Internal
381+
382+-- $setup
383+-- >>> :set -XOverloadedStrings
384+-- >>> import Data.Aeson
385+-- >>> import Database.Bloodhound
386+-- >>> let testServer = (Server "http://localhost:9200")
387+-- >>> let testIndex = IndexName "twitter"
388+-- >>> let testMapping = MappingName "tweet"
389+-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
390+
391+-- defaultIndexSettings is exported by Database.Bloodhound as well
392+-- no trailing slashes in servers, library handles building the path.
393+
394+-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
395+-- will be a noop. You can use the exported fields to customize it further, e.g.:
396+--
397+-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
398+mkBHEnv :: Server -> Manager -> BHEnv
399+mkBHEnv s m = BHEnv s m return
400+
401+newtype BH m a = BH {
402+ unBH :: ReaderT BHEnv m a
403+ } deriving ( Functor
404+ , A.Applicative
405+ , Monad
406+ , MonadIO
407+ , MonadState s
408+ , MonadWriter w
409+ , MonadError e
410+ , Alternative
411+ , MonadPlus
412+ , MonadFix
413+ , MonadThrow
414+ , MonadCatch
415+ , MonadMask)
416+
417+instance MonadTrans BH where
418+ lift = BH . lift
419+
420+instance (MonadReader r m) => MonadReader r (BH m) where
421+ ask = lift ask
422+ local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
423+ local f (m r)
424+
425+instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
426+ getBHEnv = BH getBHEnv
427+
428+runBH :: BHEnv -> BH m a -> m a
429+runBH e f = runReaderT (unBH f) e
430+
431+{-| 'Version' is embedded in 'Status' -}
432+data Version = Version { number :: VersionNumber
433+ , build_hash :: BuildHash
434+ , build_timestamp :: UTCTime
435+ , build_snapshot :: Bool
436+ , lucene_version :: VersionNumber } deriving (Eq, Read, Show, Generic, Typeable)
437+
438+-- | Traditional software versioning number
439+newtype VersionNumber = VersionNumber { versionNumber :: Vers.Version
440+ } deriving (Eq, Read, Show, Generic, Typeable, Ord)
441+
442+{-| 'Status' is a data type for describing the JSON body returned by
443+ Elasticsearch when you query its status. This was deprecated in 1.2.0.
444+
445+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
446+-}
447+
448+data Status = Status { ok :: Maybe Bool
449+ , status :: Int
450+ , name :: Text
451+ , version :: Version
452+ , tagline :: Text } deriving (Eq, Read, Show, Generic)
453+
454+{-| 'IndexSettings' is used to configure the shards and replicas when you create
455+ an Elasticsearch Index.
456+
457+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
458+-}
459+
460+data IndexSettings =
461+ IndexSettings { indexShards :: ShardCount
462+ , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
463+
464+{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
465+defaultIndexSettings :: IndexSettings
466+defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
467+
468+
469+{-| 'IndexOptimizationSettings' is used to configure index optimization. See
470+ <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
471+ for more info.
472+-}
473+data IndexOptimizationSettings =
474+ IndexOptimizationSettings { maxNumSegments :: Maybe Int
475+ -- ^ Number of segments to optimize to. 1 will fully optimize the index. If omitted, the default behavior is to only optimize if the server deems it necessary.
476+ , onlyExpungeDeletes :: Bool
477+ -- ^ Should the optimize process only expunge segments with deletes in them? If the purpose of the optimization is to free disk space, this should be set to True.
478+ , flushAfterOptimize :: Bool
479+ -- ^ Should a flush be performed after the optimize.
480+ } deriving (Eq, Show, Generic, Typeable)
481+
482+
483+{-| 'defaultIndexOptimizationSettings' implements the default settings that
484+ ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
485+ 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
486+-}
487+defaultIndexOptimizationSettings :: IndexOptimizationSettings
488+defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
489+
490+{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
491+
492+ <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
493+-}
494+data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
495+ -- ^ The number of replicas each shard has.
496+ | AutoExpandReplicas ReplicaBounds
497+ | BlocksReadOnly Bool
498+ -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
499+ | BlocksRead Bool
500+ -- ^ Set to True to disable read operations against the index.
501+ | BlocksWrite Bool
502+ -- ^ Set to True to disable write operations against the index.
503+ | BlocksMetaData Bool
504+ -- ^ Set to True to disable metadata operations against the index.
505+ | RefreshInterval NominalDiffTime
506+ -- ^ The async refresh interval of a shard
507+ | IndexConcurrency Int
508+ | FailOnMergeFailure Bool
509+ | TranslogFlushThresholdOps Int
510+ -- ^ When to flush on operations.
511+ | TranslogFlushThresholdSize Bytes
512+ -- ^ When to flush based on translog (bytes) size.
513+ | TranslogFlushThresholdPeriod NominalDiffTime
514+ -- ^ When to flush based on a period of not flushing.
515+ | TranslogDisableFlush Bool
516+ -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
517+ | CacheFilterMaxSize (Maybe Bytes)
518+ -- ^ The maximum size of filter cache (per segment in shard).
519+ | CacheFilterExpire (Maybe NominalDiffTime)
520+ -- ^ The expire after access time for filter cache.
521+ | GatewaySnapshotInterval NominalDiffTime
522+ -- ^ The gateway snapshot interval (only applies to shared gateways).
523+ | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
524+ -- ^ A node matching any rule will be allowed to host shards from the index.
525+ | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
526+ -- ^ A node matching any rule will NOT be allowed to host shards from the index.
527+ | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
528+ -- ^ Only nodes matching all rules will be allowed to host shards from the index.
529+ | RoutingAllocationEnable AllocationPolicy
530+ -- ^ Enables shard allocation for a specific index.
531+ | RoutingAllocationShardsPerNode ShardCount
532+ -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
533+ | RecoveryInitialShards InitialShardCount
534+ -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
535+ | GCDeletes NominalDiffTime
536+ | TTLDisablePurge Bool
537+ -- ^ Disables temporarily the purge of expired docs.
538+ | TranslogFSType FSType
539+ | IndexCompoundFormat CompoundFormat
540+ | IndexCompoundOnFlush Bool
541+ | WarmerEnabled Bool
542+ deriving (Eq, Show, Generic, Typeable)
543+
544+data AllocationPolicy = AllocAll
545+ -- ^ Allows shard allocation for all shards.
546+ | AllocPrimaries
547+ -- ^ Allows shard allocation only for primary shards.
548+ | AllocNewPrimaries
549+ -- ^ Allows shard allocation only for primary shards for new indices.
550+ | AllocNone
551+ -- ^ No shard allocation is allowed
552+ deriving (Eq, Read, Show, Generic, Typeable)
553+
554+data ReplicaBounds = ReplicasBounded Int Int
555+ | ReplicasLowerBounded Int
556+ | ReplicasUnbounded
557+ deriving (Eq, Read, Show, Generic, Typeable)
558+
559+-- | A measure of bytes used for various configurations. You may want
560+-- to use smart constructors like 'gigabytes' for larger values.
561+--
562+-- >>> gigabytes 9
563+-- Bytes 9000000000
564+--
565+-- >>> megabytes 9
566+-- Bytes 9000000
567+--
568+-- >>> kilobytes 9
569+-- Bytes 9000
570+newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
571+
572+gigabytes :: Int -> Bytes
573+gigabytes n = megabytes (1000 * n)
574+
575+
576+megabytes :: Int -> Bytes
577+megabytes n = kilobytes (1000 * n)
578+
579+
580+kilobytes :: Int -> Bytes
581+kilobytes n = Bytes (1000 * n)
582+
583+
584+data FSType = FSSimple
585+ | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
586+
587+data InitialShardCount = QuorumShards
588+ | QuorumMinus1Shards
589+ | FullShards
590+ | FullMinus1Shards
591+ | ExplicitShards Int
592+ deriving (Eq, Read, Show, Generic, Typeable)
593+
594+data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
595+ , nodeAttrFilterValues :: NonEmpty Text}
596+ deriving (Eq, Read, Show, Generic, Ord)
597+
598+newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
599+
600+data CompoundFormat = CompoundFileFormat Bool
601+ | MergeSegmentVsTotalIndex Double
602+ -- ^ percentage between 0 and 1 where 0 is false, 1 is true
603+ deriving (Eq, Read, Show, Generic, Typeable)
604+
605+newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
606+
607+data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
608+ , sSummaryFixedSettings :: IndexSettings
609+ , sSummaryUpdateable :: [UpdatableIndexSetting]}
610+ deriving (Eq, Show, Generic, Typeable)
611+
612+{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
613+type Reply = Network.HTTP.Client.Response L.ByteString
614+type Method = NHTM.Method
615+
616+{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
617+
618+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
619+-}
620+data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
621+
622+data FieldType = GeoPointType
623+ | GeoShapeType
624+ | FloatType
625+ | IntegerType
626+ | LongType
627+ | ShortType
628+ | ByteType deriving (Eq, Read, Show, Generic, Typeable)
629+
630+data FieldDefinition =
631+ FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
632+
633+{-| An 'IndexTemplate' defines a template that will automatically be
634+ applied to new indices created. The templates include both
635+ 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
636+ controls if the template will be applied to the index created.
637+ Specify mappings as follows: @[toJSON TweetMapping, ...]@
638+
639+ https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
640+-}
641+data IndexTemplate =
642+ IndexTemplate { templatePattern :: TemplatePattern
643+ , templateSettings :: Maybe IndexSettings
644+ , templateMappings :: [Value]
645+ }
646+
647+data MappingField =
648+ MappingField { mappingFieldName :: FieldName
649+ , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
650+
651+{-| Support for type reification of 'Mapping's is currently incomplete, for
652+ now the mapping API verbiage expects a 'ToJSON'able blob.
653+
654+ Indexes have mappings, mappings are schemas for the documents contained in the
655+ index. I'd recommend having only one mapping per index, always having a mapping,
656+ and keeping different kinds of documents separated if possible.
657+-}
658+data Mapping = Mapping { typeName :: TypeName
659+ , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
660+
661+{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
662+ operation index, create, delete, and update. 'BulkIndex' behaves like an
663+ "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
664+
665+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
666+-}
667+data BulkOperation =
668+ BulkIndex IndexName MappingName DocId Value
669+ | BulkCreate IndexName MappingName DocId Value
670+ | BulkDelete IndexName MappingName DocId
671+ | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
672+
673+{-| 'EsResult' describes the standard wrapper JSON document that you see in
674+ successful Elasticsearch lookups or lookups that couldn't find the document.
675+-}
676+data EsResult a = EsResult { _index :: Text
677+ , _type :: Text
678+ , _id :: Text
679+ , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
680+
681+{-| 'EsResultFound' contains the document and its metadata inside of an
682+ 'EsResult' when the document was successfully found.
683+-}
684+data EsResultFound a = EsResultFound { _version :: DocVersion
685+ , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
686+
687+{-| 'EsError' is the generic type that will be returned when there was a
688+ problem. If you can't parse the expected response, its a good idea to
689+ try parsing this.
690+-}
691+data EsError = EsError { errorStatus :: Int
692+ , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
693+
694+{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
695+returned by the ElasticSearch server. If you encounter this error, please
696+verify that your domain data types and FromJSON instances are working properly
697+(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
698+sure that your mappings are correct, then this error may be an indication of an
699+incompatibility between Bloodhound and ElasticSearch. Please open a bug report
700+and be sure to include the exception body.
701+-}
702+data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
703+ deriving (Eq, Read, Show, Generic, Typeable)
704+
705+instance Exception EsProtocolException
706+
707+data IndexAlias = IndexAlias { srcIndex :: IndexName
708+ , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
709+
710+newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
711+
712+data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
713+ | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
714+
715+data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
716+ , aliasCreateFilter :: Maybe Filter}
717+ deriving (Read, Show, Eq, Generic, Typeable)
718+
719+data AliasRouting = AllAliasRouting RoutingValue
720+ | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
721+ deriving (Read, Show, Eq, Generic, Typeable)
722+
723+newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
724+
725+newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
726+
727+newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
728+
729+newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
730+
731+{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
732+data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
733+ , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
734+
735+{-| 'DocVersion' is an integer version number for a document between 1
736+and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
737+-}
738+newtype DocVersion = DocVersion {
739+ docVersionNumber :: Int
740+ } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
741+
742+-- | Smart constructor for in-range doc version
743+mkDocVersion :: Int -> Maybe DocVersion
744+mkDocVersion i
745+ | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
746+ Just $ DocVersion i
747+ | otherwise = Nothing
748+
749+
750+{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
751+own version numbers instead of ones from ES.
752+-}
753+newtype ExternalDocVersion = ExternalDocVersion DocVersion
754+ deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
755+
756+{-| 'VersionControl' is specified when indexing documents as a
757+optimistic concurrency control.
758+-}
759+data VersionControl = NoVersionControl
760+ -- ^ Don't send a version. This is a pure overwrite.
761+ | InternalVersion DocVersion
762+ -- ^ Use the default ES versioning scheme. Only
763+ -- index the document if the version is the same
764+ -- as the one specified. Only applicable to
765+ -- updates, as you should be getting Version from
766+ -- a search result.
767+ | ExternalGT ExternalDocVersion
768+ -- ^ Use your own version numbering. Only index
769+ -- the document if the version is strictly higher
770+ -- OR the document doesn't exist. The given
771+ -- version will be used as the new version number
772+ -- for the stored document. N.B. All updates must
773+ -- increment this number, meaning there is some
774+ -- global, external ordering of updates.
775+ | ExternalGTE ExternalDocVersion
776+ -- ^ Use your own version numbering. Only index
777+ -- the document if the version is equal or higher
778+ -- than the stored version. Will succeed if there
779+ -- is no existing document. The given version will
780+ -- be used as the new version number for the
781+ -- stored document. Use with care, as this could
782+ -- result in data loss.
783+ | ForceVersion ExternalDocVersion
784+ -- ^ The document will always be indexed and the
785+ -- given version will be the new version. This is
786+ -- typically used for correcting errors. Use with
787+ -- care, as this could result in data loss.
788+ deriving (Read, Show, Eq, Generic, Ord)
789+
790+{-| 'DocumentParent' is used to specify a parent document.
791+-}
792+newtype DocumentParent = DocumentParent DocId
793+ deriving (Eq, Read, Show, Generic, Typeable)
794+
795+{-| 'IndexDocumentSettings' are special settings supplied when indexing
796+a document. For the best backwards compatiblity when new fields are
797+added, you should probably prefer to start with 'defaultIndexDocumentSettings'
798+-}
799+data IndexDocumentSettings =
800+ IndexDocumentSettings { idsVersionControl :: VersionControl
801+ , idsParent :: Maybe DocumentParent
802+ } deriving (Eq, Read, Show, Generic, Typeable)
803+
804+{-| Reasonable default settings. Chooses no version control and no parent.
805+-}
806+defaultIndexDocumentSettings :: IndexDocumentSettings
807+defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
808+
809+{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
810+ dependent with later sorts acting as tie-breakers for earlier sorts.
811+-}
812+type Sort = [SortSpec]
813+
814+{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
815+ 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
816+ 'DistanceUnit' to express "nearness" to a single geographical point as a
817+ sort specification.
818+
819+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
820+-}
821+data SortSpec = DefaultSortSpec DefaultSort
822+ | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
823+
824+{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
825+ 'mkSort' convenience function for when you want to specify only the most
826+ common parameters.
827+
828+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
829+-}
830+data DefaultSort =
831+ DefaultSort { sortFieldName :: FieldName
832+ , sortOrder :: SortOrder
833+ -- default False
834+ , ignoreUnmapped :: Bool
835+ , sortMode :: Maybe SortMode
836+ , missingSort :: Maybe Missing
837+ , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
838+
839+{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
840+ encoded into "asc" or "desc" when turned into JSON.
841+
842+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
843+-}
844+data SortOrder = Ascending
845+ | Descending deriving (Eq, Read, Show, Generic, Typeable)
846+
847+{-| 'Missing' prescribes how to handle missing fields. A missing field can be
848+ sorted last, first, or using a custom value as a substitute.
849+
850+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
851+-}
852+data Missing = LastMissing
853+ | FirstMissing
854+ | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
855+
856+{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
857+
858+http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
859+-}
860+data SortMode = SortMin
861+ | SortMax
862+ | SortSum
863+ | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
864+
865+{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
866+ that you can concisely describe the usual kind of 'SortSpec's you want.
867+-}
868+mkSort :: FieldName -> SortOrder -> DefaultSort
869+mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
870+
871+{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
872+ 'Query's cannot be cached.
873+-}
874+type Cache = Bool -- caching on/off
875+defaultCache :: Cache
876+defaultCache = False
877+
878+{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
879+-}
880+type PrefixValue = Text
881+
882+{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
883+ JSON encoding baked in. Used all over the place.
884+-}
885+data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
886+
887+{-| 'ShardCount' is part of 'IndexSettings'
888+-}
889+newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
890+
891+{-| 'ReplicaCount' is part of 'IndexSettings'
892+-}
893+newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
894+
895+{-| 'IndexName' is used to describe which index to query/create/delete
896+-}
897+newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
898+
899+{-| 'IndexSelection' is used for APIs which take a single index, a list of
900+ indexes, or the special @_all@ index.
901+-}
902+--TODO: this does not fully support <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/multi-index.html multi-index syntax>. It wouldn't be too hard to implement but you'd have to add the optional parameters (ignore_unavailable, allow_no_indices, expand_wildcards) to any APIs using it. Also would be a breaking API.
903+data IndexSelection = IndexList (NonEmpty IndexName)
904+ | AllIndexes deriving (Eq, Generic, Show, Typeable)
905+
906+{-| 'NodeSelection' is used for most cluster APIs. See <https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster.html#cluster-nodes here> for more details.
907+-}
908+data NodeSelection = LocalNode
909+ -- ^ Whatever node receives this request
910+ | NodeList (NonEmpty NodeSelector)
911+ | AllNodes deriving (Eq, Generic, Show, Typeable)
912+
913+
914+-- | An exact match or pattern to identify a node. Note that All of
915+-- these options support wildcarding, so your node name, server, attr
916+-- name can all contain * characters to be a fuzzy match.
917+data NodeSelector = NodeByName NodeName
918+ | NodeByFullNodeId FullNodeId
919+ | NodeByHost Server
920+ -- ^ e.g. 10.0.0.1 or even 10.0.0.*
921+ | NodeByAttribute NodeAttrName Text
922+ -- ^ NodeAttrName can be a pattern, e.g. rack*. The value can too.
923+ deriving (Eq, Generic, Show, Typeable)
924+
925+{-| 'TemplateName' is used to describe which template to query/create/delete
926+-}
927+newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
928+
929+{-| 'TemplatePattern' represents a pattern which is matched against index names
930+-}
931+newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
932+
933+{-| 'MappingName' is part of mappings which are how ES describes and schematizes
934+ the data in the indices.
935+-}
936+newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
937+
938+{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
939+ Can be set by the user or created by ES itself. Often used in client
940+ functions for poking at specific documents.
941+-}
942+newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
943+
944+{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
945+-}
946+newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
947+
948+{-| 'FieldName' is used all over the place wherever a specific field within
949+ a document needs to be specified, usually in 'Query's or 'Filter's.
950+-}
951+newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
952+
953+
954+{-| 'Script' is often used in place of 'FieldName' to specify more
955+complex ways of extracting a value from a document.
956+-}
957+newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
958+
959+{-| 'CacheName' is used in 'RegexpFilter' for describing the
960+ 'CacheKey' keyed caching behavior.
961+-}
962+newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
963+
964+{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
965+-}
966+newtype CacheKey =
967+ CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
968+newtype Existence =
969+ Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
970+newtype NullValue =
971+ NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
972+newtype CutoffFrequency =
973+ CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
974+newtype Analyzer =
975+ Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
976+newtype MaxExpansions =
977+ MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
978+
979+{-| 'Lenient', if set to true, will cause format based failures to be
980+ ignored. I don't know what the bloody default is, Elasticsearch
981+ documentation didn't say what it was. Let me know if you figure it out.
982+-}
983+newtype Lenient =
984+ Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
985+newtype Tiebreaker =
986+ Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
987+newtype Boost =
988+ Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
989+newtype BoostTerms =
990+ BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
991+
992+{-| 'MinimumMatch' controls how many should clauses in the bool query should
993+ match. Can be an absolute value (2) or a percentage (30%) or a
994+ combination of both.
995+-}
996+newtype MinimumMatch =
997+ MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
998+newtype DisableCoord =
999+ DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1000+newtype IgnoreTermFrequency =
1001+ IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1002+newtype MinimumTermFrequency =
1003+ MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1004+newtype MaxQueryTerms =
1005+ MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1006+newtype Fuzziness =
1007+ Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1008+
1009+{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
1010+newtype PrefixLength =
1011+ PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1012+newtype TypeName =
1013+ TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1014+newtype PercentMatch =
1015+ PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1016+newtype StopWord =
1017+ StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1018+newtype QueryPath =
1019+ QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1020+
1021+{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
1022+ heavy, because all terms in the index need to be examined, just in case
1023+ they match. Leading wildcards can be disabled by setting
1024+ 'AllowLeadingWildcard' to false. -}
1025+newtype AllowLeadingWildcard =
1026+ AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1027+newtype LowercaseExpanded =
1028+ LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1029+newtype EnablePositionIncrements =
1030+ EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1031+
1032+{-| By default, wildcard terms in a query are not analyzed.
1033+ Setting 'AnalyzeWildcard' to true enables best-effort analysis.
1034+-}
1035+newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1036+
1037+{-| 'GeneratePhraseQueries' defaults to false.
1038+-}
1039+newtype GeneratePhraseQueries =
1040+ GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1041+
1042+{-| 'Locale' is used for string conversions - defaults to ROOT.
1043+-}
1044+newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1045+newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1046+newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1047+
1048+{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
1049+ phrase matches. Default is 0.
1050+-}
1051+newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1052+newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1053+newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1054+
1055+-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
1056+newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
4291057
4301058{-| 'unpackId' is a silly convenience function that gets used once.
4311059-}
@@ -433,6 +1061,8 @@ unpackId :: DocId -> Text
4331061unpackId (DocId docId) = docId
4341062
4351063type TrackSortScores = Bool
1064+newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1065+newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
4361066
4371067data Search = Search { queryBody :: Maybe Query
4381068 , filterBody :: Maybe Filter
@@ -444,74 +1074,537 @@ data Search = Search { queryBody :: Maybe Query
4441074 , from :: From
4451075 , size :: Size
4461076 , searchType :: SearchType
447− , searchAfterKey :: Maybe SearchAfterKey
4481077 , 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] [] []
1078+ , source :: Maybe Source } deriving (Eq, Read, Show, Generic, Typeable)
4791079
4801080data SearchType = SearchTypeQueryThenFetch
4811081 | SearchTypeDfsQueryThenFetch
482− deriving (Eq, Show)
1082+ | SearchTypeCount
1083+ | SearchTypeScan
1084+ | SearchTypeQueryAndFetch
1085+ | SearchTypeDfsQueryAndFetch
1086+ deriving (Eq, Read, Show, Generic, Typeable)
4831087
4841088data Source =
4851089 NoSource
4861090 | SourcePatterns PatternOrPatterns
4871091 | 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 ]
1092+ deriving (Read, Show, Eq, Generic, Typeable)
4941093
4951094data PatternOrPatterns = PopPattern Pattern
496− | PopPatterns [Pattern] deriving (Eq, Read, Show)
1095+ | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
4971096
498−instance ToJSON PatternOrPatterns where
499− toJSON (PopPattern pattern) = toJSON pattern
500− toJSON (PopPatterns patterns) = toJSON patterns
1097+data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1098+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
5011099
502−data Include = Include [Pattern] deriving (Eq, Read, Show)
503−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1100+newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
5041101
505−instance ToJSON Include where
506− toJSON (Include patterns) = toJSON patterns
1102+data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1103+ , highlightFields :: [FieldHighlight]
1104+ } deriving (Read, Show, Eq, Generic, Typeable)
5071105
508−instance ToJSON Exclude where
509− toJSON (Exclude patterns) = toJSON patterns
1106+data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1107+ deriving (Read, Show, Eq, Generic, Typeable)
5101108
511−newtype Pattern = Pattern Text deriving (Eq, Read, Show)
5121109
513−instance ToJSON Pattern where
514− toJSON (Pattern pattern) = toJSON pattern
1110+data HighlightSettings = Plain PlainHighlight
1111+ | Postings PostingsHighlight
1112+ | FastVector FastVectorHighlight
1113+ deriving (Read, Show, Eq, Generic, Typeable)
1114+data PlainHighlight =
1115+ PlainHighlight { plainCommon :: Maybe CommonHighlight
1116+ , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1117+
1118+ -- This requires that index_options are set to 'offset' in the mapping.
1119+data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1120+
1121+-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1122+data FastVectorHighlight =
1123+ FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1124+ , fvNonPostSettings :: Maybe NonPostings
1125+ , boundaryChars :: Maybe Text
1126+ , boundaryMaxScan :: Maybe Int
1127+ , fragmentOffset :: Maybe Int
1128+ , matchedFields :: [Text]
1129+ , phraseLimit :: Maybe Int
1130+ } deriving (Read, Show, Eq, Generic, Typeable)
1131+
1132+data CommonHighlight =
1133+ CommonHighlight { order :: Maybe Text
1134+ , forceSource :: Maybe Bool
1135+ , tag :: Maybe HighlightTag
1136+ , encoder :: Maybe HighlightEncoder
1137+ , noMatchSize :: Maybe Int
1138+ , highlightQuery :: Maybe Query
1139+ , requireFieldMatch :: Maybe Bool
1140+ } deriving (Read, Show, Eq, Generic, Typeable)
1141+
1142+-- Settings that are only applicable to FastVector and Plain highlighters.
1143+data NonPostings =
1144+ NonPostings { fragmentSize :: Maybe Int
1145+ , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1146+
1147+data HighlightEncoder = DefaultEncoder
1148+ | HTMLEncoder
1149+ deriving (Read, Show, Eq, Generic, Typeable)
1150+
1151+-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1152+data HighlightTag = TagSchema Text
1153+ | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1154+ deriving (Read, Show, Eq, Generic, Typeable)
1155+
1156+
1157+data Query =
1158+ TermQuery Term (Maybe Boost)
1159+ | TermsQuery Text (NonEmpty Text)
1160+ | QueryMatchQuery MatchQuery
1161+ | QueryMultiMatchQuery MultiMatchQuery
1162+ | QueryBoolQuery BoolQuery
1163+ | QueryBoostingQuery BoostingQuery
1164+ | QueryCommonTermsQuery CommonTermsQuery
1165+ | ConstantScoreFilter Filter Boost
1166+ | ConstantScoreQuery Query Boost
1167+ | QueryDisMaxQuery DisMaxQuery
1168+ | QueryFilteredQuery FilteredQuery
1169+ | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1170+ | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1171+ | QueryFuzzyQuery FuzzyQuery
1172+ | QueryHasChildQuery HasChildQuery
1173+ | QueryHasParentQuery HasParentQuery
1174+ | IdsQuery MappingName [DocId]
1175+ | QueryIndicesQuery IndicesQuery
1176+ | MatchAllQuery (Maybe Boost)
1177+ | QueryMoreLikeThisQuery MoreLikeThisQuery
1178+ | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1179+ | QueryNestedQuery NestedQuery
1180+ | QueryPrefixQuery PrefixQuery
1181+ | QueryQueryStringQuery QueryStringQuery
1182+ | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1183+ | QueryRangeQuery RangeQuery
1184+ | QueryRegexpQuery RegexpQuery
1185+ deriving (Eq, Read, Show, Generic, Typeable)
1186+
1187+data RegexpQuery =
1188+ RegexpQuery { regexpQueryField :: FieldName
1189+ , regexpQuery :: Regexp
1190+ , regexpQueryFlags :: RegexpFlags
1191+ , regexpQueryBoost :: Maybe Boost
1192+ } deriving (Eq, Read, Show, Generic, Typeable)
1193+
1194+data RangeQuery =
1195+ RangeQuery { rangeQueryField :: FieldName
1196+ , rangeQueryRange :: RangeValue
1197+ , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1198+
1199+mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1200+mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1201+
1202+data SimpleQueryStringQuery =
1203+ SimpleQueryStringQuery
1204+ { simpleQueryStringQuery :: QueryString
1205+ , simpleQueryStringField :: Maybe FieldOrFields
1206+ , simpleQueryStringOperator :: Maybe BooleanOperator
1207+ , simpleQueryStringAnalyzer :: Maybe Analyzer
1208+ , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1209+ , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1210+ , simpleQueryStringLocale :: Maybe Locale
1211+ } deriving (Eq, Read, Show, Generic, Typeable)
1212+
1213+data SimpleQueryFlag =
1214+ SimpleQueryAll
1215+ | SimpleQueryNone
1216+ | SimpleQueryAnd
1217+ | SimpleQueryOr
1218+ | SimpleQueryPrefix
1219+ | SimpleQueryPhrase
1220+ | SimpleQueryPrecedence
1221+ | SimpleQueryEscape
1222+ | SimpleQueryWhitespace
1223+ | SimpleQueryFuzzy
1224+ | SimpleQueryNear
1225+ | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1226+
1227+-- use_dis_max and tie_breaker when fields are plural?
1228+data QueryStringQuery =
1229+ QueryStringQuery
1230+ { queryStringQuery :: QueryString
1231+ , queryStringDefaultField :: Maybe FieldName
1232+ , queryStringOperator :: Maybe BooleanOperator
1233+ , queryStringAnalyzer :: Maybe Analyzer
1234+ , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1235+ , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1236+ , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1237+ , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1238+ , queryStringFuzziness :: Maybe Fuzziness
1239+ , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1240+ , queryStringPhraseSlop :: Maybe PhraseSlop
1241+ , queryStringBoost :: Maybe Boost
1242+ , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1243+ , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1244+ , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1245+ , queryStringLenient :: Maybe Lenient
1246+ , queryStringLocale :: Maybe Locale
1247+ } deriving (Eq, Read, Show, Generic, Typeable)
1248+
1249+mkQueryStringQuery :: QueryString -> QueryStringQuery
1250+mkQueryStringQuery qs =
1251+ QueryStringQuery qs Nothing Nothing
1252+ Nothing Nothing Nothing Nothing
1253+ Nothing Nothing Nothing Nothing
1254+ Nothing Nothing Nothing Nothing
1255+ Nothing Nothing
1256+
1257+data FieldOrFields = FofField FieldName
1258+ | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1259+
1260+data PrefixQuery =
1261+ PrefixQuery
1262+ { prefixQueryField :: FieldName
1263+ , prefixQueryPrefixValue :: Text
1264+ , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1265+
1266+data NestedQuery =
1267+ NestedQuery
1268+ { nestedQueryPath :: QueryPath
1269+ , nestedQueryScoreType :: ScoreType
1270+ , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1271+
1272+data MoreLikeThisFieldQuery =
1273+ MoreLikeThisFieldQuery
1274+ { moreLikeThisFieldText :: Text
1275+ , moreLikeThisFieldFields :: FieldName
1276+ -- default 0.3 (30%)
1277+ , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1278+ , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1279+ , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1280+ , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1281+ , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1282+ , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1283+ , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1284+ , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1285+ , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1286+ , moreLikeThisFieldBoost :: Maybe Boost
1287+ , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1288+ } deriving (Eq, Read, Show, Generic, Typeable)
1289+
1290+data MoreLikeThisQuery =
1291+ MoreLikeThisQuery
1292+ { moreLikeThisText :: Text
1293+ , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1294+ -- default 0.3 (30%)
1295+ , moreLikeThisPercentMatch :: Maybe PercentMatch
1296+ , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1297+ , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1298+ , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1299+ , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1300+ , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1301+ , moreLikeThisMinWordLength :: Maybe MinWordLength
1302+ , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1303+ , moreLikeThisBoostTerms :: Maybe BoostTerms
1304+ , moreLikeThisBoost :: Maybe Boost
1305+ , moreLikeThisAnalyzer :: Maybe Analyzer
1306+ } deriving (Eq, Read, Show, Generic, Typeable)
1307+
1308+data IndicesQuery =
1309+ IndicesQuery
1310+ { indicesQueryIndices :: [IndexName]
1311+ , indicesQuery :: Query
1312+ -- default "all"
1313+ , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1314+
1315+data HasParentQuery =
1316+ HasParentQuery
1317+ { hasParentQueryType :: TypeName
1318+ , hasParentQuery :: Query
1319+ , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1320+
1321+data HasChildQuery =
1322+ HasChildQuery
1323+ { hasChildQueryType :: TypeName
1324+ , hasChildQuery :: Query
1325+ , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1326+
1327+data ScoreType =
1328+ ScoreTypeMax
1329+ | ScoreTypeSum
1330+ | ScoreTypeAvg
1331+ | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1332+
1333+data FuzzyQuery =
1334+ FuzzyQuery { fuzzyQueryField :: FieldName
1335+ , fuzzyQueryValue :: Text
1336+ , fuzzyQueryPrefixLength :: PrefixLength
1337+ , fuzzyQueryMaxExpansions :: MaxExpansions
1338+ , fuzzyQueryFuzziness :: Fuzziness
1339+ , fuzzyQueryBoost :: Maybe Boost
1340+ } deriving (Eq, Read, Show, Generic, Typeable)
1341+
1342+data FuzzyLikeFieldQuery =
1343+ FuzzyLikeFieldQuery
1344+ { fuzzyLikeField :: FieldName
1345+ -- anaphora is good for the soul.
1346+ , fuzzyLikeFieldText :: Text
1347+ , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1348+ , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1349+ , fuzzyLikeFieldFuzziness :: Fuzziness
1350+ , fuzzyLikeFieldPrefixLength :: PrefixLength
1351+ , fuzzyLikeFieldBoost :: Boost
1352+ , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1353+ } deriving (Eq, Read, Show, Generic, Typeable)
1354+
1355+data FuzzyLikeThisQuery =
1356+ FuzzyLikeThisQuery
1357+ { fuzzyLikeFields :: [FieldName]
1358+ , fuzzyLikeText :: Text
1359+ , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1360+ , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1361+ , fuzzyLikeFuzziness :: Fuzziness
1362+ , fuzzyLikePrefixLength :: PrefixLength
1363+ , fuzzyLikeBoost :: Boost
1364+ , fuzzyLikeAnalyzer :: Maybe Analyzer
1365+ } deriving (Eq, Read, Show, Generic, Typeable)
1366+
1367+data FilteredQuery =
1368+ FilteredQuery
1369+ { filteredQuery :: Query
1370+ , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1371+
1372+data DisMaxQuery =
1373+ DisMaxQuery { disMaxQueries :: [Query]
1374+ -- default 0.0
1375+ , disMaxTiebreaker :: Tiebreaker
1376+ , disMaxBoost :: Maybe Boost
1377+ } deriving (Eq, Read, Show, Generic, Typeable)
1378+
1379+data MatchQuery =
1380+ MatchQuery { matchQueryField :: FieldName
1381+ , matchQueryQueryString :: QueryString
1382+ , matchQueryOperator :: BooleanOperator
1383+ , matchQueryZeroTerms :: ZeroTermsQuery
1384+ , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1385+ , matchQueryMatchType :: Maybe MatchQueryType
1386+ , matchQueryAnalyzer :: Maybe Analyzer
1387+ , matchQueryMaxExpansions :: Maybe MaxExpansions
1388+ , matchQueryLenient :: Maybe Lenient
1389+ , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1390+
1391+{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1392+ enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1393+-}
1394+mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1395+mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1396+
1397+data MatchQueryType =
1398+ MatchPhrase
1399+ | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1400+
1401+data MultiMatchQuery =
1402+ MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1403+ , multiMatchQueryString :: QueryString
1404+ , multiMatchQueryOperator :: BooleanOperator
1405+ , multiMatchQueryZeroTerms :: ZeroTermsQuery
1406+ , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1407+ , multiMatchQueryType :: Maybe MultiMatchQueryType
1408+ , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1409+ , multiMatchQueryAnalyzer :: Maybe Analyzer
1410+ , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1411+ , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1412+
1413+{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1414+ enabling you to provide only the list of 'FieldName's and 'QueryString' to
1415+ make a 'MultiMatchQuery'.
1416+-}
1417+
1418+mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1419+mkMultiMatchQuery matchFields query =
1420+ MultiMatchQuery matchFields query
1421+ Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1422+
1423+data MultiMatchQueryType =
1424+ MultiMatchBestFields
1425+ | MultiMatchMostFields
1426+ | MultiMatchCrossFields
1427+ | MultiMatchPhrase
1428+ | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1429+
1430+data BoolQuery =
1431+ BoolQuery { boolQueryMustMatch :: [Query]
1432+ , boolQueryMustNotMatch :: [Query]
1433+ , boolQueryShouldMatch :: [Query]
1434+ , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1435+ , boolQueryBoost :: Maybe Boost
1436+ , boolQueryDisableCoord :: Maybe DisableCoord
1437+ } deriving (Eq, Read, Show, Generic, Typeable)
1438+
1439+mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1440+mkBoolQuery must mustNot should =
1441+ BoolQuery must mustNot should Nothing Nothing Nothing
1442+
1443+data BoostingQuery =
1444+ BoostingQuery { positiveQuery :: Query
1445+ , negativeQuery :: Query
1446+ , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1447+
1448+data CommonTermsQuery =
1449+ CommonTermsQuery { commonField :: FieldName
1450+ , commonQuery :: QueryString
1451+ , commonCutoffFrequency :: CutoffFrequency
1452+ , commonLowFreqOperator :: BooleanOperator
1453+ , commonHighFreqOperator :: BooleanOperator
1454+ , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1455+ , commonBoost :: Maybe Boost
1456+ , commonAnalyzer :: Maybe Analyzer
1457+ , commonDisableCoord :: Maybe DisableCoord
1458+ } deriving (Eq, Read, Show, Generic, Typeable)
1459+
1460+data CommonMinimumMatch =
1461+ CommonMinimumMatchHighLow MinimumMatchHighLow
1462+ | CommonMinimumMatch MinimumMatch
1463+ deriving (Eq, Read, Show, Generic, Typeable)
1464+
1465+data MinimumMatchHighLow =
1466+ MinimumMatchHighLow { lowFreq :: MinimumMatch
1467+ , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1468+
1469+data Filter = AndFilter [Filter] Cache
1470+ | OrFilter [Filter] Cache
1471+ | NotFilter Filter Cache
1472+ | IdentityFilter
1473+ | BoolFilter BoolMatch
1474+ | ExistsFilter FieldName -- always cached
1475+ | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1476+ | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1477+ | GeoDistanceRangeFilter GeoPoint DistanceRange
1478+ | GeoPolygonFilter FieldName [LatLon]
1479+ | IdsFilter MappingName [DocId]
1480+ | LimitFilter Int
1481+ | MissingFilter FieldName Existence NullValue
1482+ | PrefixFilter FieldName PrefixValue Cache
1483+ | QueryFilter Query Cache
1484+ | RangeFilter FieldName RangeValue RangeExecution Cache
1485+ | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1486+ | TermFilter Term Cache
1487+ deriving (Eq, Read, Show, Generic, Typeable)
1488+
1489+data ZeroTermsQuery = ZeroTermsNone
1490+ | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1491+
1492+data RangeExecution = RangeExecutionIndex
1493+ | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1494+
1495+newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1496+
1497+data RegexpFlags = AllRegexpFlags
1498+ | NoRegexpFlags
1499+ | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1500+
1501+data RegexpFlag = AnyString
1502+ | Automaton
1503+ | Complement
1504+ | Empty
1505+ | Intersection
1506+ | Interval deriving (Eq, Read, Show, Generic, Typeable)
1507+
1508+newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1509+newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1510+newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1511+newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1512+
1513+newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1514+newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1515+newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1516+newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1517+
1518+data RangeValue = RangeDateLte LessThanEqD
1519+ | RangeDateLt LessThanD
1520+ | RangeDateGte GreaterThanEqD
1521+ | RangeDateGt GreaterThanD
1522+ | RangeDateGtLt GreaterThanD LessThanD
1523+ | RangeDateGteLte GreaterThanEqD LessThanEqD
1524+ | RangeDateGteLt GreaterThanEqD LessThanD
1525+ | RangeDateGtLte GreaterThanD LessThanEqD
1526+ | RangeDoubleLte LessThanEq
1527+ | RangeDoubleLt LessThan
1528+ | RangeDoubleGte GreaterThanEq
1529+ | RangeDoubleGt GreaterThan
1530+ | RangeDoubleGtLt GreaterThan LessThan
1531+ | RangeDoubleGteLte GreaterThanEq LessThanEq
1532+ | RangeDoubleGteLt GreaterThanEq LessThan
1533+ | RangeDoubleGtLte GreaterThan LessThanEq
1534+ deriving (Eq, Read, Show, Generic, Typeable)
1535+
1536+rangeValueToPair :: RangeValue -> [Pair]
1537+rangeValueToPair rv = case rv of
1538+ RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1539+ RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1540+ RangeDateLt (LessThanD t) -> ["lt" .= t]
1541+ RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1542+ RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1543+ RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1544+ RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1545+ RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1546+ RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1547+ RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1548+ RangeDoubleLt (LessThan t) -> ["lt" .= t]
1549+ RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1550+ RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1551+ RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1552+ RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1553+ RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1554+
1555+data Term = Term { termField :: Text
1556+ , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1557+
1558+data BoolMatch = MustMatch Term Cache
1559+ | MustNotMatch Term Cache
1560+ | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1561+
1562+-- "memory" or "indexed"
1563+data GeoFilterType = GeoFilterMemory
1564+ | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1565+
1566+data LatLon = LatLon { lat :: Double
1567+ , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1568+
1569+data GeoBoundingBox =
1570+ GeoBoundingBox { topLeft :: LatLon
1571+ , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1572+
1573+data GeoBoundingBoxConstraint =
1574+ GeoBoundingBoxConstraint { geoBBField :: FieldName
1575+ , constraintBox :: GeoBoundingBox
1576+ , bbConstraintcache :: Cache
1577+ , geoType :: GeoFilterType
1578+ } deriving (Eq, Read, Show, Generic, Typeable)
1579+
1580+data GeoPoint =
1581+ GeoPoint { geoField :: FieldName
1582+ , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
1583+
1584+data DistanceUnit = Miles
1585+ | Yards
1586+ | Feet
1587+ | Inches
1588+ | Kilometers
1589+ | Meters
1590+ | Centimeters
1591+ | Millimeters
1592+ | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
1593+
1594+data DistanceType = Arc
1595+ | SloppyArc -- doesn't exist <1.0
1596+ | Plane deriving (Eq, Read, Show, Generic, Typeable)
1597+
1598+data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1599+ | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
1600+
1601+data Distance =
1602+ Distance { coefficient :: Double
1603+ , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1604+
1605+data DistanceRange =
1606+ DistanceRange { distanceFrom :: Distance
1607+ , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
5151608
5161609data SearchResult a =
5171610 SearchResult { took :: Int
@@ -519,24 +1612,2959 @@ data SearchResult a =
5191612 , shards :: ShardResult
5201613 , searchHits :: SearchHits a
5211614 , 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)
1615+ , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
5281616
529−instance (FromJSON a) => FromJSON (SearchResult a) where
530− parseJSON (Object v) = SearchResult <$>
531− v .: "took" <*>
532− v .: "timed_out" <*>
533− v .: "_shards" <*>
1617+newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
1618+
1619+type Score = Maybe Double
1620+
1621+data SearchHits a =
1622+ SearchHits { hitsTotal :: Int
1623+ , maxScore :: Score
1624+ , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1625+
1626+
1627+instance Monoid (SearchHits a) where
1628+ mempty = SearchHits 0 Nothing mempty
1629+ mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1630+ SearchHits (ta + tb) (max ma mb) (ha <> hb)
1631+
1632+
1633+data Hit a =
1634+ Hit { hitIndex :: IndexName
1635+ , hitType :: MappingName
1636+ , hitDocId :: DocId
1637+ , hitScore :: Score
1638+ , hitSource :: Maybe a
1639+ , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1640+
1641+data ShardResult =
1642+ ShardResult { shardTotal :: Int
1643+ , shardsSuccessful :: Int
1644+ , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1645+
1646+type HitHighlight = M.Map Text [Text]
1647+
1648+showText :: Show a => a -> Text
1649+showText = T.pack . show
1650+
1651+readMay :: Read a => String -> Maybe a
1652+readMay s = case reads s of
1653+ (a, ""):_ -> Just a
1654+ _ -> Nothing
1655+
1656+parseReadText :: Read a => Text -> Parser a
1657+parseReadText = maybe mzero return . readMay . T.unpack
1658+
1659+type Aggregations = M.Map Text Aggregation
1660+
1661+emptyAggregations :: Aggregations
1662+emptyAggregations = M.empty
1663+
1664+mkAggregations :: Text -> Aggregation -> Aggregations
1665+mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1666+
1667+data TermOrder = TermOrder{ termSortField :: Text
1668+ , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1669+
1670+data TermInclusion = TermInclusion Text
1671+ | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1672+
1673+data CollectionMode = BreadthFirst
1674+ | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1675+
1676+data ExecutionHint = Ordinals
1677+ | GlobalOrdinals
1678+ | GlobalOrdinalsHash
1679+ | GlobalOrdinalsLowCardinality
1680+ | Map deriving (Eq, Read, Show, Generic, Typeable)
1681+
1682+data TimeInterval = Weeks
1683+ | Days
1684+ | Hours
1685+ | Minutes
1686+ | Seconds deriving Eq
1687+
1688+data Interval = Year
1689+ | Quarter
1690+ | Month
1691+ | Week
1692+ | Day
1693+ | Hour
1694+ | Minute
1695+ | Second
1696+ | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1697+
1698+data Aggregation = TermsAgg TermsAggregation
1699+ | CardinalityAgg CardinalityAggregation
1700+ | DateHistogramAgg DateHistogramAggregation
1701+ | ValueCountAgg ValueCountAggregation
1702+ | FilterAgg FilterAggregation
1703+ | DateRangeAgg DateRangeAggregation
1704+ | MissingAgg MissingAggregation deriving (Eq, Read, Show, Generic, Typeable)
1705+
1706+data MissingAggregation = MissingAggregation
1707+ { maField :: Text
1708+ } deriving (Eq, Read, Show, Generic, Typeable)
1709+
1710+data TermsAggregation = TermsAggregation { term :: Either Text Text
1711+ , termInclude :: Maybe TermInclusion
1712+ , termExclude :: Maybe TermInclusion
1713+ , termOrder :: Maybe TermOrder
1714+ , termMinDocCount :: Maybe Int
1715+ , termSize :: Maybe Int
1716+ , termShardSize :: Maybe Int
1717+ , termCollectMode :: Maybe CollectionMode
1718+ , termExecutionHint :: Maybe ExecutionHint
1719+ , termAggs :: Maybe Aggregations
1720+ } deriving (Eq, Read, Show, Generic, Typeable)
1721+
1722+data CardinalityAggregation = CardinalityAggregation { cardinalityField :: FieldName,
1723+ precisionThreshold :: Maybe Int
1724+ } deriving (Eq, Read, Show, Generic, Typeable)
1725+
1726+data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1727+ , dateInterval :: Interval
1728+ , dateFormat :: Maybe Text
1729+ -- pre and post deprecated in 1.5
1730+ , datePreZone :: Maybe Text
1731+ , datePostZone :: Maybe Text
1732+ , datePreOffset :: Maybe Text
1733+ , datePostOffset :: Maybe Text
1734+ , dateAggs :: Maybe Aggregations
1735+ } deriving (Eq, Read, Show, Generic, Typeable)
1736+
1737+
1738+data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1739+ , draFormat :: Maybe Text
1740+ , draRanges :: NonEmpty DateRangeAggRange
1741+ } deriving (Eq, Read, Show, Generic, Typeable)
1742+
1743+data DateRangeAggRange = DateRangeFrom DateMathExpr
1744+ | DateRangeTo DateMathExpr
1745+ | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1746+
1747+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1748+data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1749+
1750+
1751+-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1752+data DateMathAnchor = DMNow
1753+ | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1754+
1755+data DateMathModifier = AddTime Int DateMathUnit
1756+ | SubtractTime Int DateMathUnit
1757+ | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1758+
1759+data DateMathUnit = DMYear
1760+ | DMMonth
1761+ | DMWeek
1762+ | DMDay
1763+ | DMHour
1764+ | DMMinute
1765+ | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1766+
1767+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1768+data ValueCountAggregation = FieldValueCount FieldName
1769+ | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1770+
1771+-- | 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.
1772+data FilterAggregation = FilterAggregation { faFilter :: Filter
1773+ , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1774+
1775+mkTermsAggregation :: Text -> TermsAggregation
1776+mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1777+
1778+mkTermsScriptAggregation :: Text -> TermsAggregation
1779+mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1780+
1781+mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1782+mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1783+
1784+mkCardinalityAggregation :: FieldName -> CardinalityAggregation
1785+mkCardinalityAggregation t = CardinalityAggregation t Nothing
1786+
1787+instance ToJSON Version where
1788+ toJSON Version {..} = object ["number" .= number
1789+ ,"build_hash" .= build_hash
1790+ ,"build_timestamp" .= build_timestamp
1791+ ,"build_snapshot" .= build_snapshot
1792+ ,"lucene_version" .= lucene_version]
1793+
1794+instance FromJSON Version where
1795+ parseJSON = withObject "Version" parse
1796+ where parse o = Version
1797+ <$> o .: "number"
1798+ <*> o .: "build_hash"
1799+ <*> o .: "build_timestamp"
1800+ <*> o .: "build_snapshot"
1801+ <*> o .: "lucene_version"
1802+
1803+instance ToJSON VersionNumber where
1804+ toJSON = toJSON . Vers.showVersion . versionNumber
1805+
1806+instance FromJSON VersionNumber where
1807+ parseJSON = withText "VersionNumber" (parse . T.unpack)
1808+ where
1809+ parse s = case filter (null . snd)(RP.readP_to_S Vers.parseVersion s) of
1810+ [(v, _)] -> pure (VersionNumber v)
1811+ [] -> fail ("Invalid version string " ++ s)
1812+ xs -> fail ("Ambiguous version string " ++ s ++ " (" ++ intercalate ", " (Vers.showVersion . fst <$> xs) ++ ")")
1813+
1814+instance ToJSON TermOrder where
1815+ toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1816+
1817+instance ToJSON TermInclusion where
1818+ toJSON (TermInclusion x) = toJSON x
1819+ toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1820+ "flags" .= flags]
1821+
1822+instance ToJSON CollectionMode where
1823+ toJSON BreadthFirst = "breadth_first"
1824+ toJSON DepthFirst = "depth_first"
1825+
1826+instance ToJSON ExecutionHint where
1827+ toJSON Ordinals = "ordinals"
1828+ toJSON GlobalOrdinals = "global_ordinals"
1829+ toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1830+ toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1831+ toJSON Map = "map"
1832+
1833+instance ToJSON Interval where
1834+ toJSON Year = "year"
1835+ toJSON Quarter = "quarter"
1836+ toJSON Month = "month"
1837+ toJSON Week = "week"
1838+ toJSON Day = "day"
1839+ toJSON Hour = "hour"
1840+ toJSON Minute = "minute"
1841+ toJSON Second = "second"
1842+ toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1843+
1844+instance Show TimeInterval where
1845+ show Weeks = "w"
1846+ show Days = "d"
1847+ show Hours = "h"
1848+ show Minutes = "m"
1849+ show Seconds = "s"
1850+
1851+instance Read TimeInterval where
1852+ readPrec = f =<< TR.get
1853+ where
1854+ f 'w' = return Weeks
1855+ f 'd' = return Days
1856+ f 'h' = return Hours
1857+ f 'm' = return Minutes
1858+ f 's' = return Seconds
1859+ f _ = fail "TimeInterval expected one of w, d, h, m, s"
1860+
1861+instance ToJSON Aggregation where
1862+ toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1863+ omitNulls ["terms" .= omitNulls [ toJSON' term,
1864+ "include" .= include,
1865+ "exclude" .= exclude,
1866+ "order" .= order,
1867+ "min_doc_count" .= minDocCount,
1868+ "size" .= size,
1869+ "shard_size" .= shardSize,
1870+ "collect_mode" .= collectMode,
1871+ "execution_hint" .= executionHint
1872+ ],
1873+ "aggs" .= termAggs ]
1874+ where
1875+ toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1876+
1877+ toJSON (CardinalityAgg (CardinalityAggregation field precisionThreshold)) =
1878+ object ["cardinality" .= omitNulls [ "field" .= field,
1879+ "precisionThreshold" .= precisionThreshold
1880+ ]
1881+ ]
1882+
1883+ toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1884+ omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1885+ "interval" .= interval,
1886+ "format" .= format,
1887+ "pre_zone" .= preZone,
1888+ "post_zone" .= postZone,
1889+ "pre_offset" .= preOffset,
1890+ "post_offset" .= postOffset
1891+ ],
1892+ "aggs" .= dateHistoAggs ]
1893+ toJSON (ValueCountAgg a) = object ["value_count" .= v]
1894+ where v = case a of
1895+ (FieldValueCount (FieldName n)) -> object ["field" .= n]
1896+ (ScriptValueCount (Script s)) -> object ["script" .= s]
1897+ toJSON (FilterAgg (FilterAggregation filt ags)) =
1898+ omitNulls [ "filter" .= filt
1899+ , "aggs" .= ags]
1900+ toJSON (DateRangeAgg a) = object [ "date_range" .= a
1901+ ]
1902+ toJSON (MissingAgg (MissingAggregation{..})) =
1903+ object ["missing" .= object ["field" .= maField]]
1904+
1905+instance ToJSON DateRangeAggregation where
1906+ toJSON DateRangeAggregation {..} =
1907+ omitNulls [ "field" .= draField
1908+ , "format" .= draFormat
1909+ , "ranges" .= toList draRanges
1910+ ]
1911+
1912+instance ToJSON DateRangeAggRange where
1913+ toJSON (DateRangeFrom e) = object [ "from" .= e ]
1914+ toJSON (DateRangeTo e) = object [ "to" .= e ]
1915+ toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1916+
1917+instance ToJSON DateMathExpr where
1918+ toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1919+ where fmtA DMNow = "now"
1920+ fmtA (DMDate date) = case toGregorian date of
1921+ (y,m,d) -> showText y <> "-" <>
1922+ showText m <> "-" <>
1923+ showText d <> "||"
1924+ fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1925+ fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1926+ fmtMod (RoundDownTo u) = "/" <> fmtU u
1927+ fmtU DMYear = "y"
1928+ fmtU DMMonth = "M"
1929+ fmtU DMWeek = "w"
1930+ fmtU DMDay = "d"
1931+ fmtU DMHour = "h"
1932+ fmtU DMMinute = "m"
1933+ fmtU DMSecond = "s"
1934+
1935+
1936+type AggregationResults = M.Map Text Value
1937+
1938+class BucketAggregation a where
1939+ key :: a -> BucketValue
1940+ docCount :: a -> Int
1941+ aggs :: a -> Maybe AggregationResults
1942+
1943+
1944+data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1945+
1946+data BucketValue = TextValue Text
1947+ | ScientificValue Scientific
1948+ | BoolValue Bool deriving (Read, Show)
1949+
1950+data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1951+
1952+data TermsResult = TermsResult { termKey :: BucketValue
1953+ , termsDocCount :: Int
1954+ , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1955+
1956+data DateHistogramResult = DateHistogramResult { dateKey :: Int
1957+ , dateKeyStr :: Maybe Text
1958+ , dateDocCount :: Int
1959+ , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1960+
1961+data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1962+ , dateRangeFrom :: Maybe UTCTime
1963+ , dateRangeFromAsString :: Maybe Text
1964+ , dateRangeTo :: Maybe UTCTime
1965+ , dateRangeToAsString :: Maybe Text
1966+ , dateRangeDocCount :: Int
1967+ , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1968+
1969+toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1970+toTerms = toAggResult
1971+
1972+toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1973+toDateHistogram = toAggResult
1974+
1975+toMissing :: Text -> AggregationResults -> Maybe MissingResult
1976+toMissing = toAggResult
1977+
1978+toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1979+toAggResult t a = M.lookup t a >>= deserialize
1980+ where deserialize = parseMaybe parseJSON
1981+
1982+instance BucketAggregation TermsResult where
1983+ key = termKey
1984+ docCount = termsDocCount
1985+ aggs = termsAggs
1986+
1987+instance BucketAggregation DateHistogramResult where
1988+ key = TextValue . showText . dateKey
1989+ docCount = dateDocCount
1990+ aggs = dateHistogramAggs
1991+
1992+instance BucketAggregation DateRangeResult where
1993+ key = TextValue . dateRangeKey
1994+ docCount = dateRangeDocCount
1995+ aggs = dateRangeAggs
1996+
1997+instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1998+ parseJSON (Object v) = Bucket <$>
1999+ v .: "buckets"
2000+ parseJSON _ = mempty
2001+
2002+instance FromJSON BucketValue where
2003+ parseJSON (String t) = return $ TextValue t
2004+ parseJSON (Number s) = return $ ScientificValue s
2005+ parseJSON (Bool b) = return $ BoolValue b
2006+ parseJSON _ = mempty
2007+
2008+instance FromJSON MissingResult where
2009+ parseJSON = withObject "MissingResult" parse
2010+ where parse v = MissingResult <$> v .: "doc_count"
2011+
2012+instance FromJSON TermsResult where
2013+ parseJSON (Object v) = TermsResult <$>
2014+ v .: "key" <*>
2015+ v .: "doc_count" <*>
2016+ v .:? "aggregations"
2017+ parseJSON _ = mempty
2018+
2019+instance FromJSON DateHistogramResult where
2020+ parseJSON (Object v) = DateHistogramResult <$>
2021+ v .: "key" <*>
2022+ v .:? "key_as_string" <*>
2023+ v .: "doc_count" <*>
2024+ v .:? "aggregations"
2025+ parseJSON _ = mempty
2026+
2027+instance FromJSON DateRangeResult where
2028+ parseJSON = withObject "DateRangeResult" parse
2029+ where parse v = DateRangeResult <$>
2030+ v .: "key" <*>
2031+ (fmap posixMS <$> v .:? "from") <*>
2032+ v .:? "from_as_string" <*>
2033+ (fmap posixMS <$> v .:? "to") <*>
2034+ v .:? "to_as_string" <*>
2035+ v .: "doc_count" <*>
2036+ v .:? "aggregations"
2037+
2038+instance FromJSON POSIXMS where
2039+ parseJSON = withScientific "POSIXMS" (return . parse)
2040+ where parse n = let n' = truncate n :: Integer
2041+ in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
2042+
2043+instance Monoid Filter where
2044+ mempty = IdentityFilter
2045+ mappend a b = AndFilter [a, b] defaultCache
2046+
2047+instance Seminearring Filter where
2048+ a <||> b = OrFilter [a, b] defaultCache
2049+
2050+instance ToJSON Filter where
2051+ toJSON (AndFilter filters cache) =
2052+ object ["and" .=
2053+ object [ "filters" .= fmap toJSON filters
2054+ , "_cache" .= cache]]
2055+
2056+ toJSON (OrFilter filters cache) =
2057+ object ["or" .=
2058+ object [ "filters" .= fmap toJSON filters
2059+ , "_cache" .= cache]]
2060+
2061+ toJSON (NotFilter notFilter cache) =
2062+ object ["not" .=
2063+ object ["filter" .= notFilter
2064+ , "_cache" .= cache]]
2065+
2066+ toJSON (IdentityFilter) =
2067+ object ["match_all" .= object []]
2068+
2069+ toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
2070+ object ["term" .= object base]
2071+ where base = [termFilterField .= termFilterValue,
2072+ "_cache" .= cache]
2073+
2074+ toJSON (ExistsFilter (FieldName fieldName)) =
2075+ object ["exists" .= object
2076+ ["field" .= fieldName]]
2077+
2078+ toJSON (BoolFilter boolMatch) =
2079+ object ["bool" .= boolMatch]
2080+
2081+ toJSON (GeoBoundingBoxFilter bbConstraint) =
2082+ object ["geo_bounding_box" .= bbConstraint]
2083+
2084+ toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2085+ distance distanceType optimizeBbox cache) =
2086+ object ["geo_distance" .=
2087+ object ["distance" .= distance
2088+ , "distance_type" .= distanceType
2089+ , "optimize_bbox" .= optimizeBbox
2090+ , distanceGeoField .= geoDistLatLon
2091+ , "_cache" .= cache]]
2092+
2093+ toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2094+ (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2095+ object ["geo_distance_range" .=
2096+ object ["from" .= geoDistRangeDistFrom
2097+ , "to" .= drDistanceTo
2098+ , gddrField .= drLatLon]]
2099+
2100+ toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2101+ object ["geo_polygon" .=
2102+ object [geoPolygonFilterField .=
2103+ object ["points" .= fmap toJSON latLons]]]
2104+
2105+ toJSON (IdsFilter (MappingName mappingName) values) =
2106+ object ["ids" .=
2107+ object ["type" .= mappingName
2108+ , "values" .= fmap unpackId values]]
2109+
2110+ toJSON (LimitFilter limit) =
2111+ object ["limit" .= object ["value" .= limit]]
2112+
2113+ toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2114+ object ["missing" .=
2115+ object ["field" .= fieldName
2116+ , "existence" .= existence
2117+ , "null_value" .= nullValue]]
2118+
2119+ toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2120+ object ["prefix" .=
2121+ object [fieldName .= fieldValue
2122+ , "_cache" .= cache]]
2123+
2124+ toJSON (QueryFilter query False) =
2125+ object ["query" .= toJSON query ]
2126+ toJSON (QueryFilter query True) =
2127+ object ["fquery" .=
2128+ object [ "query" .= toJSON query
2129+ , "_cache" .= True ]]
2130+
2131+ toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2132+ object ["range" .=
2133+ object [ fieldName .= object (rangeValueToPair rangeValue)
2134+ , "execution" .= rangeExecution
2135+ , "_cache" .= cache]]
2136+
2137+ toJSON (RegexpFilter (FieldName fieldName)
2138+ (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2139+ object ["regexp" .=
2140+ object [fieldName .=
2141+ object ["value" .= regexText
2142+ , "flags" .= flags]
2143+ , "_name" .= cacheName
2144+ , "_cache" .= cache
2145+ , "_cache_key" .= cacheKey]]
2146+
2147+instance FromJSON Filter where
2148+ parseJSON = withObject "Filter" parse
2149+ where parse o = andFilter `taggedWith` "and"
2150+ <|> orFilter `taggedWith` "or"
2151+ <|> notFilter `taggedWith` "not"
2152+ <|> identityFilter `taggedWith` "match_all"
2153+ <|> boolFilter `taggedWith` "bool"
2154+ <|> existsFilter `taggedWith` "exists"
2155+ <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2156+ <|> geoDistanceFilter `taggedWith` "geo_distance"
2157+ <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2158+ <|> geoPolygonFilter `taggedWith` "geo_polygon"
2159+ <|> idsFilter `taggedWith` "ids"
2160+ <|> limitFilter `taggedWith` "limit"
2161+ <|> missingFilter `taggedWith` "missing"
2162+ <|> prefixFilter `taggedWith` "prefix"
2163+ <|> queryFilter `taggedWith` "query"
2164+ <|> fqueryFilter `taggedWith` "fquery"
2165+ <|> rangeFilter `taggedWith` "range"
2166+ <|> regexpFilter `taggedWith` "regexp"
2167+ <|> termFilter `taggedWith` "term"
2168+ where taggedWith parser k = parser =<< o .: k
2169+ andFilter o = AndFilter <$> o .: "filters"
2170+ <*> o .:? "_cache" .!= defaultCache
2171+ orFilter o = OrFilter <$> o .: "filters"
2172+ <*> o .:? "_cache" .!= defaultCache
2173+ notFilter o = NotFilter <$> o .: "filter"
2174+ <*> o .: "_cache" .!= defaultCache
2175+ identityFilter :: Object -> Parser Filter
2176+ identityFilter m
2177+ | HM.null m = pure IdentityFilter
2178+ | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2179+ boolFilter = pure . BoolFilter
2180+ existsFilter o = ExistsFilter <$> o .: "field"
2181+ geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2182+ geoDistanceFilter o = do
2183+ case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2184+ [(fn, v)] -> do
2185+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
2186+ GeoDistanceFilter gp <$> o .: "distance"
2187+ <*> o .: "distance_type"
2188+ <*> o .: "optimize_bbox"
2189+ <*> o .:? "_cache" .!= defaultCache
2190+ _ -> fail "Could not find GeoDistanceFilter field name"
2191+ geoDistanceRangeFilter o = do
2192+ case HM.toList (deleteSeveral ["from", "to"] o) of
2193+ [(fn, v)] -> do
2194+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
2195+ rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2196+ return (GeoDistanceRangeFilter gp rng)
2197+ _ -> fail "Could not find GeoDistanceRangeFilter field name"
2198+ geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2199+ idsFilter o = IdsFilter <$> o .: "type"
2200+ <*> o .: "values"
2201+ limitFilter o = LimitFilter <$> o .: "value"
2202+ missingFilter o = MissingFilter <$> o .: "field"
2203+ <*> o .: "existence"
2204+ <*> o .: "null_value"
2205+ prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2206+ [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2207+ _ -> fail "Could not parse PrefixFilter"
2208+
2209+ queryFilter q = pure (QueryFilter q False)
2210+ fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2211+ rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2212+ [(fn, v)] -> RangeFilter (FieldName fn)
2213+ <$> parseJSON v
2214+ <*> o .: "execution"
2215+ <*> o .:? "_cache" .!= defaultCache
2216+ _ -> fail "Could not find field name for RangeFilter"
2217+ regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2218+ [(fn, Object o')] -> RegexpFilter (FieldName fn)
2219+ <$> o' .: "value"
2220+ <*> o' .: "flags"
2221+ <*> o .: "_name"
2222+ <*> o .:? "_cache" .!= defaultCache
2223+ <*> o .: "_cache_key"
2224+ _ -> fail "Could not find field name for RegexpFilter"
2225+ termFilter o = case HM.toList (HM.delete "_cache" o) of
2226+ [(termField, String termVal)] -> TermFilter (Term termField termVal)
2227+ <$> o .:? "_cache" .!= defaultCache
2228+ _ -> fail "Could not find term field for TermFilter"
2229+
2230+fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2231+fieldTagged f o = case HM.toList o of
2232+ [(k, Object o')] -> f (FieldName k) o'
2233+ _ -> fail "Expected object with 1 field-named key"
2234+
2235+instance ToJSON GeoPoint where
2236+ toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2237+ object [ geoPointField .= geoPointLatLon ]
2238+
2239+
2240+instance ToJSON Query where
2241+ toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2242+ object [ "term" .=
2243+ object [termQueryField .= object merged]]
2244+ where
2245+ base = [ "value" .= termQueryValue ]
2246+ boosted = maybe [] (return . ("boost" .=)) boost
2247+ merged = mappend base boosted
2248+
2249+ toJSON (TermsQuery fieldName terms) =
2250+ object [ "terms" .= object conjoined ]
2251+ where conjoined = [fieldName .= terms]
2252+
2253+ toJSON (IdsQuery idsQueryMappingName docIds) =
2254+ object [ "ids" .= object conjoined ]
2255+ where conjoined = [ "type" .= idsQueryMappingName
2256+ , "values" .= fmap toJSON docIds ]
2257+
2258+ toJSON (QueryQueryStringQuery qQueryStringQuery) =
2259+ object [ "query_string" .= qQueryStringQuery ]
2260+
2261+ toJSON (QueryMatchQuery matchQuery) =
2262+ object [ "match" .= matchQuery ]
2263+
2264+ toJSON (QueryMultiMatchQuery multiMatchQuery) =
2265+ toJSON multiMatchQuery
2266+
2267+ toJSON (QueryBoolQuery boolQuery) =
2268+ object [ "bool" .= boolQuery ]
2269+
2270+ toJSON (QueryBoostingQuery boostingQuery) =
2271+ object [ "boosting" .= boostingQuery ]
2272+
2273+ toJSON (QueryCommonTermsQuery commonTermsQuery) =
2274+ object [ "common" .= commonTermsQuery ]
2275+
2276+ toJSON (ConstantScoreFilter csFilter boost) =
2277+ object ["constant_score" .= object ["filter" .= csFilter
2278+ , "boost" .= boost]]
2279+
2280+ toJSON (ConstantScoreQuery query boost) =
2281+ object ["constant_score" .= object ["query" .= query
2282+ , "boost" .= boost]]
2283+
2284+ toJSON (QueryDisMaxQuery disMaxQuery) =
2285+ object [ "dis_max" .= disMaxQuery ]
2286+
2287+ toJSON (QueryFilteredQuery qFilteredQuery) =
2288+ object [ "filtered" .= qFilteredQuery ]
2289+
2290+ toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2291+ object [ "fuzzy_like_this" .= fuzzyQuery ]
2292+
2293+ toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2294+ object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2295+
2296+ toJSON (QueryFuzzyQuery fuzzyQuery) =
2297+ object [ "fuzzy" .= fuzzyQuery ]
2298+
2299+ toJSON (QueryHasChildQuery childQuery) =
2300+ object [ "has_child" .= childQuery ]
2301+
2302+ toJSON (QueryHasParentQuery parentQuery) =
2303+ object [ "has_parent" .= parentQuery ]
2304+
2305+ toJSON (QueryIndicesQuery qIndicesQuery) =
2306+ object [ "indices" .= qIndicesQuery ]
2307+
2308+ toJSON (MatchAllQuery boost) =
2309+ object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2310+
2311+ toJSON (QueryMoreLikeThisQuery query) =
2312+ object [ "more_like_this" .= query ]
2313+
2314+ toJSON (QueryMoreLikeThisFieldQuery query) =
2315+ object [ "more_like_this_field" .= query ]
2316+
2317+ toJSON (QueryNestedQuery query) =
2318+ object [ "nested" .= query ]
2319+
2320+ toJSON (QueryPrefixQuery query) =
2321+ object [ "prefix" .= query ]
2322+
2323+ toJSON (QueryRangeQuery query) =
2324+ object [ "range" .= query ]
2325+
2326+ toJSON (QueryRegexpQuery query) =
2327+ object [ "regexp" .= query ]
2328+
2329+ toJSON (QuerySimpleQueryStringQuery query) =
2330+ object [ "simple_query_string" .= query ]
2331+
2332+instance FromJSON Query where
2333+ parseJSON v = withObject "Query" parse v
2334+ where parse o = termQuery `taggedWith` "term"
2335+ <|> termsQuery `taggedWith` "terms"
2336+ <|> idsQuery `taggedWith` "ids"
2337+ <|> queryQueryStringQuery `taggedWith` "query_string"
2338+ <|> queryMatchQuery `taggedWith` "match"
2339+ <|> queryMultiMatchQuery
2340+ <|> queryBoolQuery `taggedWith` "bool"
2341+ <|> queryBoostingQuery `taggedWith` "boosting"
2342+ <|> queryCommonTermsQuery `taggedWith` "common"
2343+ <|> constantScoreFilter `taggedWith` "constant_score"
2344+ <|> constantScoreQuery `taggedWith` "constant_score"
2345+ <|> queryDisMaxQuery `taggedWith` "dis_max"
2346+ <|> queryFilteredQuery `taggedWith` "filtered"
2347+ <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2348+ <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2349+ <|> queryFuzzyQuery `taggedWith` "fuzzy"
2350+ <|> queryHasChildQuery `taggedWith` "has_child"
2351+ <|> queryHasParentQuery `taggedWith` "has_parent"
2352+ <|> queryIndicesQuery `taggedWith` "indices"
2353+ <|> matchAllQuery `taggedWith` "match_all"
2354+ <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2355+ <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2356+ <|> queryNestedQuery `taggedWith` "nested"
2357+ <|> queryPrefixQuery `taggedWith` "prefix"
2358+ <|> queryRangeQuery `taggedWith` "range"
2359+ <|> queryRegexpQuery `taggedWith` "regexp"
2360+ <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2361+ where taggedWith parser k = parser =<< o .: k
2362+ termQuery = fieldTagged $ \(FieldName fn) o ->
2363+ TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2364+ termsQuery o = case HM.toList o of
2365+ [(fn, vs)] -> do vals <- parseJSON vs
2366+ case vals of
2367+ x:xs -> return (TermsQuery fn (x :| xs))
2368+ _ -> fail "Expected non empty list of values"
2369+ _ -> fail "Expected object with 1 field-named key"
2370+ idsQuery o = IdsQuery <$> o .: "type"
2371+ <*> o .: "values"
2372+ queryQueryStringQuery = pure . QueryQueryStringQuery
2373+ queryMatchQuery = pure . QueryMatchQuery
2374+ queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2375+ queryBoolQuery = pure . QueryBoolQuery
2376+ queryBoostingQuery = pure . QueryBoostingQuery
2377+ queryCommonTermsQuery = pure . QueryCommonTermsQuery
2378+ constantScoreFilter o = case HM.lookup "filter" o of
2379+ Just x -> ConstantScoreFilter <$> parseJSON x
2380+ <*> o .: "boost"
2381+ _ -> fail "Does not appear to be a ConstantScoreFilter"
2382+ constantScoreQuery o = case HM.lookup "query" o of
2383+ Just x -> ConstantScoreQuery <$> parseJSON x
2384+ <*> o .: "boost"
2385+ _ -> fail "Does not appear to be a ConstantScoreQuery"
2386+ queryDisMaxQuery = pure . QueryDisMaxQuery
2387+ queryFilteredQuery = pure . QueryFilteredQuery
2388+ queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2389+ queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2390+ queryFuzzyQuery = pure . QueryFuzzyQuery
2391+ queryHasChildQuery = pure . QueryHasChildQuery
2392+ queryHasParentQuery = pure . QueryHasParentQuery
2393+ queryIndicesQuery = pure . QueryIndicesQuery
2394+ matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2395+ queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2396+ queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2397+ queryNestedQuery = pure . QueryNestedQuery
2398+ queryPrefixQuery = pure . QueryPrefixQuery
2399+ queryRangeQuery = pure . QueryRangeQuery
2400+ queryRegexpQuery = pure . QueryRegexpQuery
2401+ querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2402+
2403+
2404+omitNulls :: [(Text, Value)] -> Value
2405+omitNulls = object . filter notNull where
2406+ notNull (_, Null) = False
2407+ notNull (_, Array a) = (not . V.null) a
2408+ notNull _ = True
2409+
2410+
2411+instance ToJSON SimpleQueryStringQuery where
2412+ toJSON SimpleQueryStringQuery {..} =
2413+ omitNulls (base ++ maybeAdd)
2414+ where base = [ "query" .= simpleQueryStringQuery ]
2415+ maybeAdd = [ "fields" .= simpleQueryStringField
2416+ , "default_operator" .= simpleQueryStringOperator
2417+ , "analyzer" .= simpleQueryStringAnalyzer
2418+ , "flags" .= simpleQueryStringFlags
2419+ , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2420+ , "locale" .= simpleQueryStringLocale ]
2421+
2422+instance FromJSON SimpleQueryStringQuery where
2423+ parseJSON = withObject "SimpleQueryStringQuery" parse
2424+ where parse o = SimpleQueryStringQuery <$> o .: "query"
2425+ <*> o .:? "fields"
2426+ <*> o .:? "default_operator"
2427+ <*> o .:? "analyzer"
2428+ <*> (parseFlags <$> o .:? "flags")
2429+ <*> o .:? "lowercase_expanded_terms"
2430+ <*> o .:? "locale"
2431+ parseFlags (Just (x:xs)) = Just (x :| xs)
2432+ parseFlags _ = Nothing
2433+
2434+instance ToJSON FieldOrFields where
2435+ toJSON (FofField fieldName) =
2436+ toJSON fieldName
2437+ toJSON (FofFields fieldNames) =
2438+ toJSON fieldNames
2439+
2440+instance FromJSON FieldOrFields where
2441+ parseJSON v = FofField <$> parseJSON v
2442+ <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2443+
2444+instance ToJSON SimpleQueryFlag where
2445+ toJSON SimpleQueryAll = "ALL"
2446+ toJSON SimpleQueryNone = "NONE"
2447+ toJSON SimpleQueryAnd = "AND"
2448+ toJSON SimpleQueryOr = "OR"
2449+ toJSON SimpleQueryPrefix = "PREFIX"
2450+ toJSON SimpleQueryPhrase = "PHRASE"
2451+ toJSON SimpleQueryPrecedence = "PRECEDENCE"
2452+ toJSON SimpleQueryEscape = "ESCAPE"
2453+ toJSON SimpleQueryWhitespace = "WHITESPACE"
2454+ toJSON SimpleQueryFuzzy = "FUZZY"
2455+ toJSON SimpleQueryNear = "NEAR"
2456+ toJSON SimpleQuerySlop = "SLOP"
2457+
2458+instance FromJSON SimpleQueryFlag where
2459+ parseJSON = withText "SimpleQueryFlag" parse
2460+ where parse "ALL" = pure SimpleQueryAll
2461+ parse "NONE" = pure SimpleQueryNone
2462+ parse "AND" = pure SimpleQueryAnd
2463+ parse "OR" = pure SimpleQueryOr
2464+ parse "PREFIX" = pure SimpleQueryPrefix
2465+ parse "PHRASE" = pure SimpleQueryPhrase
2466+ parse "PRECEDENCE" = pure SimpleQueryPrecedence
2467+ parse "ESCAPE" = pure SimpleQueryEscape
2468+ parse "WHITESPACE" = pure SimpleQueryWhitespace
2469+ parse "FUZZY" = pure SimpleQueryFuzzy
2470+ parse "NEAR" = pure SimpleQueryNear
2471+ parse "SLOP" = pure SimpleQuerySlop
2472+ parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2473+
2474+instance ToJSON RegexpQuery where
2475+ toJSON (RegexpQuery (FieldName rqQueryField)
2476+ (Regexp regexpQueryQuery) rqQueryFlags
2477+ rqQueryBoost) =
2478+ object [ rqQueryField .= omitNulls base ]
2479+ where base = [ "value" .= regexpQueryQuery
2480+ , "flags" .= rqQueryFlags
2481+ , "boost" .= rqQueryBoost ]
2482+
2483+instance FromJSON RegexpQuery where
2484+ parseJSON = withObject "RegexpQuery" parse
2485+ where parse = fieldTagged $ \fn o ->
2486+ RegexpQuery fn
2487+ <$> o .: "value"
2488+ <*> o .: "flags"
2489+ <*> o .:? "boost"
2490+
2491+instance ToJSON QueryStringQuery where
2492+ toJSON (QueryStringQuery qsQueryString
2493+ qsDefaultField qsOperator
2494+ qsAnalyzer qsAllowWildcard
2495+ qsLowercaseExpanded qsEnablePositionIncrements
2496+ qsFuzzyMaxExpansions qsFuzziness
2497+ qsFuzzyPrefixLength qsPhraseSlop
2498+ qsBoost qsAnalyzeWildcard
2499+ qsGeneratePhraseQueries qsMinimumShouldMatch
2500+ qsLenient qsLocale) =
2501+ omitNulls base
2502+ where
2503+ base = [ "query" .= qsQueryString
2504+ , "default_field" .= qsDefaultField
2505+ , "default_operator" .= qsOperator
2506+ , "analyzer" .= qsAnalyzer
2507+ , "allow_leading_wildcard" .= qsAllowWildcard
2508+ , "lowercase_expanded_terms" .= qsLowercaseExpanded
2509+ , "enable_position_increments" .= qsEnablePositionIncrements
2510+ , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2511+ , "fuzziness" .= qsFuzziness
2512+ , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2513+ , "phrase_slop" .= qsPhraseSlop
2514+ , "boost" .= qsBoost
2515+ , "analyze_wildcard" .= qsAnalyzeWildcard
2516+ , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2517+ , "minimum_should_match" .= qsMinimumShouldMatch
2518+ , "lenient" .= qsLenient
2519+ , "locale" .= qsLocale ]
2520+
2521+instance FromJSON QueryStringQuery where
2522+ parseJSON = withObject "QueryStringQuery" parse
2523+ where parse o = QueryStringQuery
2524+ <$> o .: "query"
2525+ <*> o .:? "default_field"
2526+ <*> o .:? "default_operator"
2527+ <*> o .:? "analyzer"
2528+ <*> o .:? "allow_leading_wildcard"
2529+ <*> o .:? "lowercase_expanded_terms"
2530+ <*> o .:? "enable_position_increments"
2531+ <*> o .:? "fuzzy_max_expansions"
2532+ <*> o .:? "fuzziness"
2533+ <*> o .:? "fuzzy_prefix_length"
2534+ <*> o .:? "phrase_slop"
2535+ <*> o .:? "boost"
2536+ <*> o .:? "analyze_wildcard"
2537+ <*> o .:? "auto_generate_phrase_queries"
2538+ <*> o .:? "minimum_should_match"
2539+ <*> o .:? "lenient"
2540+ <*> o .:? "locale"
2541+
2542+instance ToJSON RangeQuery where
2543+ toJSON (RangeQuery (FieldName fieldName) range boost) =
2544+ object [ fieldName .= object conjoined ]
2545+ where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2546+
2547+instance FromJSON RangeQuery where
2548+ parseJSON = withObject "RangeQuery" parse
2549+ where parse = fieldTagged $ \fn o ->
2550+ RangeQuery fn
2551+ <$> parseJSON (Object o)
2552+ <*> o .: "boost"
2553+
2554+instance FromJSON RangeValue where
2555+ parseJSON = withObject "RangeValue" parse
2556+ where parse o = parseDate o
2557+ <|> parseDouble o
2558+ parseDate o = do lt <- o .:? "lt"
2559+ lte <- o .:? "lte"
2560+ gt <- o .:? "gt"
2561+ gte <- o .:? "gte"
2562+ case (lt, lte, gt, gte) of
2563+ (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2564+ (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2565+ (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2566+ (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2567+ (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2568+ (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2569+ (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2570+ (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2571+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2572+ parseDouble o = do lt <- o .:? "lt"
2573+ lte <- o .:? "lte"
2574+ gt <- o .:? "gt"
2575+ gte <- o .:? "gte"
2576+ case (lt, lte, gt, gte) of
2577+ (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2578+ (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2579+ (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2580+ (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2581+ (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2582+ (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2583+ (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2584+ (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2585+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2586+
2587+instance ToJSON PrefixQuery where
2588+ toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2589+ object [ fieldName .= omitNulls base ]
2590+ where base = [ "value" .= queryValue
2591+ , "boost" .= boost ]
2592+
2593+instance FromJSON PrefixQuery where
2594+ parseJSON = withObject "PrefixQuery" parse
2595+ where parse = fieldTagged $ \fn o ->
2596+ PrefixQuery fn
2597+ <$> o .: "value"
2598+ <*> o .:? "boost"
2599+
2600+instance ToJSON NestedQuery where
2601+ toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2602+ object [ "path" .= nqPath
2603+ , "score_mode" .= nqScoreType
2604+ , "query" .= nqQuery ]
2605+
2606+instance FromJSON NestedQuery where
2607+ parseJSON = withObject "NestedQuery" parse
2608+ where parse o = NestedQuery
2609+ <$> o .: "path"
2610+ <*> o .: "score_mode"
2611+ <*> o .: "query"
2612+
2613+instance ToJSON MoreLikeThisFieldQuery where
2614+ toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2615+ percent mtf mqt stopwords mindf maxdf
2616+ minwl maxwl boostTerms boost analyzer) =
2617+ object [ fieldName .= omitNulls base ]
2618+ where base = [ "like_text" .= text
2619+ , "percent_terms_to_match" .= percent
2620+ , "min_term_freq" .= mtf
2621+ , "max_query_terms" .= mqt
2622+ , "stop_words" .= stopwords
2623+ , "min_doc_freq" .= mindf
2624+ , "max_doc_freq" .= maxdf
2625+ , "min_word_length" .= minwl
2626+ , "max_word_length" .= maxwl
2627+ , "boost_terms" .= boostTerms
2628+ , "boost" .= boost
2629+ , "analyzer" .= analyzer ]
2630+
2631+instance FromJSON MoreLikeThisFieldQuery where
2632+ parseJSON = withObject "MoreLikeThisFieldQuery" parse
2633+ where parse = fieldTagged $ \fn o ->
2634+ MoreLikeThisFieldQuery
2635+ <$> o .: "like_text"
2636+ <*> pure fn
2637+ <*> o .:? "percent_terms_to_match"
2638+ <*> o .:? "min_term_freq"
2639+ <*> o .:? "max_query_terms"
2640+ -- <*> (optionalNE =<< o .:? "stop_words")
2641+ <*> o .:? "stop_words"
2642+ <*> o .:? "min_doc_freq"
2643+ <*> o .:? "max_doc_freq"
2644+ <*> o .:? "min_word_length"
2645+ <*> o .:? "max_word_length"
2646+ <*> o .:? "boost_terms"
2647+ <*> o .:? "boost"
2648+ <*> o .:? "analyzer"
2649+ -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2650+
2651+instance ToJSON MoreLikeThisQuery where
2652+ toJSON (MoreLikeThisQuery text fields percent
2653+ mtf mqt stopwords mindf maxdf
2654+ minwl maxwl boostTerms boost analyzer) =
2655+ omitNulls base
2656+ where base = [ "like_text" .= text
2657+ , "fields" .= fields
2658+ , "percent_terms_to_match" .= percent
2659+ , "min_term_freq" .= mtf
2660+ , "max_query_terms" .= mqt
2661+ , "stop_words" .= stopwords
2662+ , "min_doc_freq" .= mindf
2663+ , "max_doc_freq" .= maxdf
2664+ , "min_word_length" .= minwl
2665+ , "max_word_length" .= maxwl
2666+ , "boost_terms" .= boostTerms
2667+ , "boost" .= boost
2668+ , "analyzer" .= analyzer ]
2669+
2670+instance FromJSON MoreLikeThisQuery where
2671+ parseJSON = withObject "MoreLikeThisQuery" parse
2672+ where parse o = MoreLikeThisQuery
2673+ <$> o .: "like_text"
2674+ -- <*> (optionalNE =<< o .:? "fields")
2675+ <*> o .:? "fields"
2676+ <*> o .:? "percent_terms_to_match"
2677+ <*> o .:? "min_term_freq"
2678+ <*> o .:? "max_query_terms"
2679+ -- <*> (optionalNE =<< o .:? "stop_words")
2680+ <*> o .:? "stop_words"
2681+ <*> o .:? "min_doc_freq"
2682+ <*> o .:? "max_doc_freq"
2683+ <*> o .:? "min_word_length"
2684+ <*> o .:? "max_word_length"
2685+ <*> o .:? "boost_terms"
2686+ <*> o .:? "boost"
2687+ <*> o .:? "analyzer"
2688+ -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2689+
2690+instance ToJSON IndicesQuery where
2691+ toJSON (IndicesQuery indices query noMatch) =
2692+ omitNulls [ "indices" .= indices
2693+ , "no_match_query" .= noMatch
2694+ , "query" .= query ]
2695+
2696+instance FromJSON IndicesQuery where
2697+ parseJSON = withObject "IndicesQuery" parse
2698+ where parse o = IndicesQuery
2699+ <$> o .:? "indices" .!= []
2700+ <*> o .: "query"
2701+ <*> o .:? "no_match_query"
2702+
2703+instance ToJSON HasParentQuery where
2704+ toJSON (HasParentQuery queryType query scoreType) =
2705+ omitNulls [ "parent_type" .= queryType
2706+ , "score_type" .= scoreType
2707+ , "query" .= query ]
2708+
2709+instance FromJSON HasParentQuery where
2710+ parseJSON = withObject "HasParentQuery" parse
2711+ where parse o = HasParentQuery
2712+ <$> o .: "parent_type"
2713+ <*> o .: "query"
2714+ <*> o .:? "score_type"
2715+
2716+instance ToJSON HasChildQuery where
2717+ toJSON (HasChildQuery queryType query scoreType) =
2718+ omitNulls [ "query" .= query
2719+ , "score_type" .= scoreType
2720+ , "type" .= queryType ]
2721+
2722+instance FromJSON HasChildQuery where
2723+ parseJSON = withObject "HasChildQuery" parse
2724+ where parse o = HasChildQuery
2725+ <$> o .: "type"
2726+ <*> o .: "query"
2727+ <*> o .:? "score_type"
2728+
2729+instance ToJSON FuzzyQuery where
2730+ toJSON (FuzzyQuery (FieldName fieldName) queryText
2731+ prefixLength maxEx fuzziness boost) =
2732+ object [ fieldName .= omitNulls base ]
2733+ where base = [ "value" .= queryText
2734+ , "fuzziness" .= fuzziness
2735+ , "prefix_length" .= prefixLength
2736+ , "boost" .= boost
2737+ , "max_expansions" .= maxEx ]
2738+
2739+instance FromJSON FuzzyQuery where
2740+ parseJSON = withObject "FuzzyQuery" parse
2741+ where parse = fieldTagged $ \fn o ->
2742+ FuzzyQuery fn
2743+ <$> o .: "value"
2744+ <*> o .: "prefix_length"
2745+ <*> o .: "max_expansions"
2746+ <*> o .: "fuzziness"
2747+ <*> o .:? "boost"
2748+
2749+instance ToJSON FuzzyLikeFieldQuery where
2750+ toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2751+ fieldText maxTerms ignoreFreq fuzziness prefixLength
2752+ boost analyzer) =
2753+ object [ fieldName .=
2754+ omitNulls [ "like_text" .= fieldText
2755+ , "max_query_terms" .= maxTerms
2756+ , "ignore_tf" .= ignoreFreq
2757+ , "fuzziness" .= fuzziness
2758+ , "prefix_length" .= prefixLength
2759+ , "analyzer" .= analyzer
2760+ , "boost" .= boost ]]
2761+
2762+instance FromJSON FuzzyLikeFieldQuery where
2763+ parseJSON = withObject "FuzzyLikeFieldQuery" parse
2764+ where parse = fieldTagged $ \fn o ->
2765+ FuzzyLikeFieldQuery fn
2766+ <$> o .: "like_text"
2767+ <*> o .: "max_query_terms"
2768+ <*> o .: "ignore_tf"
2769+ <*> o .: "fuzziness"
2770+ <*> o .: "prefix_length"
2771+ <*> o .: "boost"
2772+ <*> o .:? "analyzer"
2773+
2774+instance ToJSON FuzzyLikeThisQuery where
2775+ toJSON (FuzzyLikeThisQuery fields text maxTerms
2776+ ignoreFreq fuzziness prefixLength boost analyzer) =
2777+ omitNulls base
2778+ where base = [ "fields" .= fields
2779+ , "like_text" .= text
2780+ , "max_query_terms" .= maxTerms
2781+ , "ignore_tf" .= ignoreFreq
2782+ , "fuzziness" .= fuzziness
2783+ , "prefix_length" .= prefixLength
2784+ , "analyzer" .= analyzer
2785+ , "boost" .= boost ]
2786+
2787+instance FromJSON FuzzyLikeThisQuery where
2788+ parseJSON = withObject "FuzzyLikeThisQuery" parse
2789+ where parse o = FuzzyLikeThisQuery
2790+ <$> o .:? "fields" .!= []
2791+ <*> o .: "like_text"
2792+ <*> o .: "max_query_terms"
2793+ <*> o .: "ignore_tf"
2794+ <*> o .: "fuzziness"
2795+ <*> o .: "prefix_length"
2796+ <*> o .: "boost"
2797+ <*> o .:? "analyzer"
2798+
2799+instance ToJSON FilteredQuery where
2800+ toJSON (FilteredQuery query fFilter) =
2801+ object [ "query" .= query
2802+ , "filter" .= fFilter ]
2803+
2804+instance FromJSON FilteredQuery where
2805+ parseJSON = withObject "FilteredQuery" parse
2806+ where parse o = FilteredQuery
2807+ <$> o .: "query"
2808+ <*> o .: "filter"
2809+
2810+instance ToJSON DisMaxQuery where
2811+ toJSON (DisMaxQuery queries tiebreaker boost) =
2812+ omitNulls base
2813+ where base = [ "queries" .= queries
2814+ , "boost" .= boost
2815+ , "tie_breaker" .= tiebreaker ]
2816+
2817+instance FromJSON DisMaxQuery where
2818+ parseJSON = withObject "DisMaxQuery" parse
2819+ where parse o = DisMaxQuery
2820+ <$> o .:? "queries" .!= []
2821+ <*> o .: "tie_breaker"
2822+ <*> o .:? "boost"
2823+
2824+instance ToJSON CommonTermsQuery where
2825+ toJSON (CommonTermsQuery (FieldName fieldName)
2826+ (QueryString query) cf lfo hfo msm
2827+ boost analyzer disableCoord) =
2828+ object [fieldName .= omitNulls base ]
2829+ where base = [ "query" .= query
2830+ , "cutoff_frequency" .= cf
2831+ , "low_freq_operator" .= lfo
2832+ , "minimum_should_match" .= msm
2833+ , "boost" .= boost
2834+ , "analyzer" .= analyzer
2835+ , "disable_coord" .= disableCoord
2836+ , "high_freq_operator" .= hfo ]
2837+
2838+instance FromJSON CommonTermsQuery where
2839+ parseJSON = withObject "CommonTermsQuery" parse
2840+ where parse = fieldTagged $ \fn o ->
2841+ CommonTermsQuery fn
2842+ <$> o .: "query"
2843+ <*> o .: "cutoff_frequency"
2844+ <*> o .: "low_freq_operator"
2845+ <*> o .: "high_freq_operator"
2846+ <*> o .:? "minimum_should_match"
2847+ <*> o .:? "boost"
2848+ <*> o .:? "analyzer"
2849+ <*> o .:? "disable_coord"
2850+
2851+instance ToJSON CommonMinimumMatch where
2852+ toJSON (CommonMinimumMatch mm) = toJSON mm
2853+ toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2854+ object [ "low_freq" .= lowF
2855+ , "high_freq" .= highF ]
2856+
2857+instance FromJSON CommonMinimumMatch where
2858+ parseJSON v = parseMinimum v
2859+ <|> parseMinimumHighLow v
2860+ where parseMinimum = fmap CommonMinimumMatch . parseJSON
2861+ parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2862+ MinimumMatchHighLow
2863+ <$> o .: "low_freq"
2864+ <*> o .: "high_freq")
2865+
2866+
2867+instance ToJSON BoostingQuery where
2868+ toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2869+ object [ "positive" .= bqPositiveQuery
2870+ , "negative" .= bqNegativeQuery
2871+ , "negative_boost" .= bqNegativeBoost ]
2872+
2873+instance FromJSON BoostingQuery where
2874+ parseJSON = withObject "BoostingQuery" parse
2875+ where parse o = BoostingQuery
2876+ <$> o .: "positive"
2877+ <*> o .: "negative"
2878+ <*> o .: "negative_boost"
2879+
2880+instance ToJSON BoolQuery where
2881+ toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2882+ omitNulls base
2883+ where base = [ "must" .= mustM
2884+ , "must_not" .= notM
2885+ , "should" .= shouldM
2886+ , "minimum_should_match" .= bqMin
2887+ , "boost" .= boost
2888+ , "disable_coord" .= disableCoord ]
2889+
2890+instance FromJSON BoolQuery where
2891+ parseJSON = withObject "BoolQuery" parse
2892+ where parse o = BoolQuery
2893+ <$> o .:? "must" .!= []
2894+ <*> o .:? "must_not" .!= []
2895+ <*> o .:? "should" .!= []
2896+ <*> o .:? "minimum_should_match"
2897+ <*> o .:? "boost"
2898+ <*> o .:? "disable_coord"
2899+
2900+instance ToJSON MatchQuery where
2901+ toJSON (MatchQuery (FieldName fieldName)
2902+ (QueryString mqQueryString) booleanOperator
2903+ zeroTermsQuery cutoffFrequency matchQueryType
2904+ analyzer maxExpansions lenient boost) =
2905+ object [ fieldName .= omitNulls base ]
2906+ where base = [ "query" .= mqQueryString
2907+ , "operator" .= booleanOperator
2908+ , "zero_terms_query" .= zeroTermsQuery
2909+ , "cutoff_frequency" .= cutoffFrequency
2910+ , "type" .= matchQueryType
2911+ , "analyzer" .= analyzer
2912+ , "max_expansions" .= maxExpansions
2913+ , "lenient" .= lenient
2914+ , "boost" .= boost ]
2915+
2916+instance FromJSON MatchQuery where
2917+ parseJSON = withObject "MatchQuery" parse
2918+ where parse = fieldTagged $ \fn o ->
2919+ MatchQuery fn
2920+ <$> o .: "query"
2921+ <*> o .: "operator"
2922+ <*> o .: "zero_terms_query"
2923+ <*> o .:? "cutoff_frequency"
2924+ <*> o .:? "type"
2925+ <*> o .:? "analyzer"
2926+ <*> o .:? "max_expansions"
2927+ <*> o .:? "lenient"
2928+ <*> o .:? "boost"
2929+
2930+instance ToJSON MultiMatchQuery where
2931+ toJSON (MultiMatchQuery fields (QueryString query) boolOp
2932+ ztQ tb mmqt cf analyzer maxEx lenient) =
2933+ object ["multi_match" .= omitNulls base]
2934+ where base = [ "fields" .= fmap toJSON fields
2935+ , "query" .= query
2936+ , "operator" .= boolOp
2937+ , "zero_terms_query" .= ztQ
2938+ , "tiebreaker" .= tb
2939+ , "type" .= mmqt
2940+ , "cutoff_frequency" .= cf
2941+ , "analyzer" .= analyzer
2942+ , "max_expansions" .= maxEx
2943+ , "lenient" .= lenient ]
2944+
2945+instance FromJSON MultiMatchQuery where
2946+ parseJSON = withObject "MultiMatchQuery" parse
2947+ where parse raw = do o <- raw .: "multi_match"
2948+ MultiMatchQuery
2949+ <$> o .:? "fields" .!= []
2950+ <*> o .: "query"
2951+ <*> o .: "operator"
2952+ <*> o .: "zero_terms_query"
2953+ <*> o .:? "tiebreaker"
2954+ <*> o .:? "type"
2955+ <*> o .:? "cutoff_frequency"
2956+ <*> o .:? "analyzer"
2957+ <*> o .:? "max_expansions"
2958+ <*> o .:? "lenient"
2959+
2960+instance ToJSON MultiMatchQueryType where
2961+ toJSON MultiMatchBestFields = "best_fields"
2962+ toJSON MultiMatchMostFields = "most_fields"
2963+ toJSON MultiMatchCrossFields = "cross_fields"
2964+ toJSON MultiMatchPhrase = "phrase"
2965+ toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2966+
2967+instance FromJSON MultiMatchQueryType where
2968+ parseJSON = withText "MultiMatchPhrasePrefix" parse
2969+ where parse "best_fields" = pure MultiMatchBestFields
2970+ parse "most_fields" = pure MultiMatchMostFields
2971+ parse "cross_fields" = pure MultiMatchCrossFields
2972+ parse "phrase" = pure MultiMatchPhrase
2973+ parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2974+ parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2975+
2976+instance ToJSON BooleanOperator where
2977+ toJSON And = String "and"
2978+ toJSON Or = String "or"
2979+
2980+instance FromJSON BooleanOperator where
2981+ parseJSON = withText "BooleanOperator" parse
2982+ where parse "and" = pure And
2983+ parse "or" = pure Or
2984+ parse o = fail ("Unexpected BooleanOperator: " <> show o)
2985+
2986+instance ToJSON ZeroTermsQuery where
2987+ toJSON ZeroTermsNone = String "none"
2988+ toJSON ZeroTermsAll = String "all"
2989+
2990+instance FromJSON ZeroTermsQuery where
2991+ parseJSON = withText "ZeroTermsQuery" parse
2992+ where parse "none" = pure ZeroTermsNone
2993+ parse "all" = pure ZeroTermsAll
2994+ parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2995+
2996+instance ToJSON MatchQueryType where
2997+ toJSON MatchPhrase = "phrase"
2998+ toJSON MatchPhrasePrefix = "phrase_prefix"
2999+
3000+instance FromJSON MatchQueryType where
3001+ parseJSON = withText "MatchQueryType" parse
3002+ where parse "phrase" = pure MatchPhrase
3003+ parse "phrase_prefix" = pure MatchPhrasePrefix
3004+ parse t = fail ("Unexpected MatchQueryType: " <> show t)
3005+
3006+instance FromJSON Status where
3007+ parseJSON (Object v) = Status <$>
3008+ v .:? "ok" <*>
3009+ v .: "status" <*>
3010+ v .: "name" <*>
3011+ v .: "version" <*>
3012+ v .: "tagline"
3013+ parseJSON _ = empty
3014+
3015+
3016+instance ToJSON IndexSettings where
3017+ toJSON (IndexSettings s r) = object ["settings" .=
3018+ object ["index" .=
3019+ object ["number_of_shards" .= s, "number_of_replicas" .= r]
3020+ ]
3021+ ]
3022+
3023+instance FromJSON IndexSettings where
3024+ parseJSON = withObject "IndexSettings" parse
3025+ where parse o = do s <- o .: "settings"
3026+ i <- s .: "index"
3027+ IndexSettings <$> i .: "number_of_shards"
3028+ <*> i .: "number_of_replicas"
3029+
3030+instance ToJSON UpdatableIndexSetting where
3031+ toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
3032+ toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
3033+ toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
3034+ toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
3035+ toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
3036+ toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
3037+ toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
3038+ toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
3039+ toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
3040+ toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
3041+ toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
3042+ toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
3043+ toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
3044+ toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
3045+ toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
3046+ toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
3047+ toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
3048+ toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
3049+ toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
3050+ toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
3051+ toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
3052+ toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
3053+ toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
3054+ toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
3055+ toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
3056+ toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
3057+ toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
3058+ toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
3059+
3060+instance FromJSON UpdatableIndexSetting where
3061+ parseJSON = withObject "UpdatableIndexSetting" parse
3062+ where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
3063+ <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
3064+ <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
3065+ <|> indexConcurrency `taggedAt` ["index", "concurrency"]
3066+ <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
3067+ <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
3068+ <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
3069+ <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
3070+ <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
3071+ <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
3072+ <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
3073+ <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
3074+ <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
3075+ <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
3076+ <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
3077+ <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
3078+ <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
3079+ <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
3080+ <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
3081+ <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
3082+ <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
3083+ <|> compoundFormat `taggedAt` ["index", "compound_format"]
3084+ <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3085+ <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3086+ <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3087+ <|> blocksRead `taggedAt` ["blocks", "read"]
3088+ <|> blocksWrite `taggedAt` ["blocks", "write"]
3089+ <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3090+ where taggedAt f ks = taggedAt' f (Object o) ks
3091+ taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3092+ taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3093+ taggedAt' f v' ks) v
3094+ numberOfReplicas = pure . NumberOfReplicas
3095+ autoExpandReplicas = pure . AutoExpandReplicas
3096+ refreshInterval = pure . RefreshInterval . ndtJSON
3097+ indexConcurrency = pure . IndexConcurrency
3098+ failOnMergeFailure = pure . FailOnMergeFailure
3099+ translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3100+ translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3101+ translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3102+ translogDisableFlush = pure . TranslogDisableFlush
3103+ cacheFilterMaxSize = pure . CacheFilterMaxSize
3104+ cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3105+ gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3106+ routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3107+ routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3108+ routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3109+ routingAllocationEnable = pure . RoutingAllocationEnable
3110+ routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3111+ recoveryInitialShards = pure . RecoveryInitialShards
3112+ gcDeletes = pure . GCDeletes . ndtJSON
3113+ ttlDisablePurge = pure . TTLDisablePurge
3114+ translogFSType = pure . TranslogFSType
3115+ compoundFormat = pure . IndexCompoundFormat
3116+ compoundOnFlush = pure . IndexCompoundOnFlush
3117+ warmerEnabled = pure . WarmerEnabled
3118+ blocksReadOnly = pure . BlocksReadOnly
3119+ blocksRead = pure . BlocksRead
3120+ blocksWrite = pure . BlocksWrite
3121+ blocksMetaData = pure . BlocksMetaData
3122+
3123+instance FromJSON IndexSettingsSummary where
3124+ parseJSON = withObject "IndexSettingsSummary" parse
3125+ where parse o = case HM.toList o of
3126+ [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3127+ <$> parseJSON v
3128+ <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3129+ _ -> fail "Expected single-key object with index name"
3130+ redundant (NumberOfReplicas _) = True
3131+ redundant _ = False
3132+
3133+-- | For some reason in several settings APIs, all leaf values get returned
3134+-- as strings. This function attepmts to recover from this for all
3135+-- non-recursive JSON types. If nothing can be done, the value is left alone.
3136+unStringlyTypeJSON :: Value -> Value
3137+unStringlyTypeJSON (String "true") = Bool True
3138+unStringlyTypeJSON (String "false") = Bool False
3139+unStringlyTypeJSON (String "null") = Null
3140+unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3141+ Just n -> Number n
3142+ Nothing -> v
3143+unStringlyTypeJSON v = v
3144+
3145+
3146+parseSettings :: Object -> Parser [UpdatableIndexSetting]
3147+parseSettings o = do
3148+ o' <- o .: "index"
3149+ -- slice the index object into singleton hashmaps and try to parse each
3150+ parses <- forM (HM.toList o') $ \(k, v) -> do
3151+ -- blocks are now nested into the "index" key, which is not how they're serialized
3152+ let atRoot = Object (HM.singleton k v)
3153+ let atIndex = Object (HM.singleton "index" atRoot)
3154+ optional (parseJSON atRoot <|> parseJSON atIndex)
3155+ return (catMaybes parses)
3156+
3157+oPath :: ToJSON a => NonEmpty Text -> a -> Value
3158+oPath (k :| []) v = object [k .= v]
3159+oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3160+
3161+attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3162+attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3163+ | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3164+
3165+parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3166+parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3167+ where parse o = case HM.toList o of
3168+ [] -> fail "Expected non-empty list of NodeAttrFilters"
3169+ x:xs -> DT.mapM (uncurry parse') (x :| xs)
3170+ parse' n = withText "Text" $ \t ->
3171+ case T.splitOn "," t of
3172+ fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3173+ [] -> fail "Expected non-empty list of filter values"
3174+
3175+instance ToJSON ReplicaBounds where
3176+ toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3177+ toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3178+ toJSON ReplicasUnbounded = Bool False
3179+
3180+instance FromJSON ReplicaBounds where
3181+ parseJSON v = withText "ReplicaBounds" parseText v
3182+ <|> withBool "ReplicaBounds" parseBool v
3183+ where parseText t = case T.splitOn "-" t of
3184+ [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3185+ [a, b] -> ReplicasBounded <$> parseReadText a
3186+ <*> parseReadText b
3187+ _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3188+ parseBool False = pure ReplicasUnbounded
3189+ parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3190+
3191+instance ToJSON AllocationPolicy where
3192+ toJSON AllocAll = String "all"
3193+ toJSON AllocPrimaries = String "primaries"
3194+ toJSON AllocNewPrimaries = String "new_primaries"
3195+ toJSON AllocNone = String "none"
3196+
3197+instance FromJSON AllocationPolicy where
3198+ parseJSON = withText "AllocationPolicy" parse
3199+ where parse "all" = pure AllocAll
3200+ parse "primaries" = pure AllocPrimaries
3201+ parse "new_primaries" = pure AllocNewPrimaries
3202+ parse "none" = pure AllocNone
3203+ parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3204+
3205+instance ToJSON InitialShardCount where
3206+ toJSON QuorumShards = String "quorum"
3207+ toJSON QuorumMinus1Shards = String "quorum-1"
3208+ toJSON FullShards = String "full"
3209+ toJSON FullMinus1Shards = String "full-1"
3210+ toJSON (ExplicitShards x) = toJSON x
3211+
3212+instance FromJSON InitialShardCount where
3213+ parseJSON v = withText "InitialShardCount" parseText v
3214+ <|> ExplicitShards <$> parseJSON v
3215+ where parseText "quorum" = pure QuorumShards
3216+ parseText "quorum-1" = pure QuorumMinus1Shards
3217+ parseText "full" = pure FullShards
3218+ parseText "full-1" = pure FullMinus1Shards
3219+ parseText _ = mzero
3220+
3221+instance ToJSON FSType where
3222+ toJSON FSSimple = "simple"
3223+ toJSON FSBuffered = "buffered"
3224+
3225+instance FromJSON FSType where
3226+ parseJSON = withText "FSType" parse
3227+ where parse "simple" = pure FSSimple
3228+ parse "buffered" = pure FSBuffered
3229+ parse t = fail ("Invalid FSType: " <> show t)
3230+
3231+instance ToJSON CompoundFormat where
3232+ toJSON (CompoundFileFormat x) = Bool x
3233+ toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3234+
3235+instance FromJSON CompoundFormat where
3236+ parseJSON v = CompoundFileFormat <$> parseJSON v
3237+ <|> MergeSegmentVsTotalIndex <$> parseJSON v
3238+
3239+instance ToJSON NominalDiffTimeJSON where
3240+ toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3241+
3242+instance FromJSON NominalDiffTimeJSON where
3243+ parseJSON = withText "NominalDiffTime" parse
3244+ where parse t = case T.takeEnd 1 t of
3245+ "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3246+ _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3247+
3248+instance ToJSON IndexTemplate where
3249+ toJSON (IndexTemplate p s m) = merge
3250+ (object [ "template" .= p
3251+ , "mappings" .= foldl' merge (object []) m
3252+ ])
3253+ (toJSON s)
3254+ where
3255+ merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3256+ merge o Null = o
3257+ merge _ _ = undefined
3258+
3259+instance (FromJSON a) => FromJSON (EsResult a) where
3260+ parseJSON jsonVal@(Object v) = do
3261+ found <- v .:? "found" .!= False
3262+ fr <- if found
3263+ then parseJSON jsonVal
3264+ else return Nothing
3265+ EsResult <$> v .: "_index" <*>
3266+ v .: "_type" <*>
3267+ v .: "_id" <*>
3268+ pure fr
3269+ parseJSON _ = empty
3270+
3271+instance (FromJSON a) => FromJSON (EsResultFound a) where
3272+ parseJSON (Object v) = EsResultFound <$>
3273+ v .: "_version" <*>
3274+ v .: "_source"
3275+ parseJSON _ = empty
3276+
3277+instance FromJSON EsError where
3278+ parseJSON (Object v) = EsError <$>
3279+ v .: "status" <*>
3280+ v .: "error"
3281+ parseJSON _ = empty
3282+
3283+instance FromJSON IndexAliasesSummary where
3284+ parseJSON = withObject "IndexAliasesSummary" parse
3285+ where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3286+ go ixn = withObject "index aliases" $ \ia -> do
3287+ aliases <- ia .:? "aliases" .!= mempty
3288+ forM (HM.toList aliases) $ \(aName, v) -> do
3289+ let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3290+ IndexAliasSummary indexAlias <$> parseJSON v
3291+
3292+
3293+instance ToJSON IndexAliasAction where
3294+ toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3295+ where Object iaObj = toJSON ia
3296+ Object optsObj = toJSON opts
3297+ toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3298+ where Object iaObj = toJSON ia
3299+
3300+instance ToJSON IndexAlias where
3301+ toJSON IndexAlias {..} = object ["index" .= srcIndex
3302+ , "alias" .= indexAlias
3303+ ]
3304+
3305+instance ToJSON IndexAliasCreate where
3306+ toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3307+ where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3308+ Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3309+
3310+instance ToJSON AliasRouting where
3311+ toJSON (AllAliasRouting v) = object ["routing" .= v]
3312+ toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3313+ where prs = [("search_routing" .=) <$> srch
3314+ ,("index_routing" .=) <$> idx]
3315+
3316+instance FromJSON AliasRouting where
3317+ parseJSON = withObject "AliasRouting" parse
3318+ where parse o = parseAll o <|> parseGranular o
3319+ parseAll o = AllAliasRouting <$> o .: "routing"
3320+ parseGranular o = do
3321+ sr <- o .:? "search_routing"
3322+ ir <- o .:? "index_routing"
3323+ if isNothing sr && isNothing ir
3324+ then fail "Both search_routing and index_routing can't be blank"
3325+ else return (GranularAliasRouting sr ir)
3326+
3327+instance FromJSON IndexAliasCreate where
3328+ parseJSON v = withObject "IndexAliasCreate" parse v
3329+ where parse o = IndexAliasCreate <$> optional (parseJSON v)
3330+ <*> o .:? "filter"
3331+
3332+instance ToJSON SearchAliasRouting where
3333+ toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3334+
3335+instance FromJSON SearchAliasRouting where
3336+ parseJSON = withText "SearchAliasRouting" parse
3337+ where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3338+
3339+instance ToJSON Search where
3340+ toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3341+ omitNulls [ "query" .= query
3342+ , "filter" .= sFilter
3343+ , "sort" .= sort
3344+ , "aggregations" .= searchAggs
3345+ , "highlight" .= highlight
3346+ , "from" .= sFrom
3347+ , "size" .= sSize
3348+ , "track_scores" .= sTrackSortScores
3349+ , "fields" .= sFields
3350+ , "_source" .= sSource]
3351+
3352+
3353+instance ToJSON Source where
3354+ toJSON NoSource = toJSON False
3355+ toJSON (SourcePatterns patterns) = toJSON patterns
3356+ toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3357+
3358+instance ToJSON PatternOrPatterns where
3359+ toJSON (PopPattern pattern) = toJSON pattern
3360+ toJSON (PopPatterns patterns) = toJSON patterns
3361+
3362+instance ToJSON Include where
3363+ toJSON (Include patterns) = toJSON patterns
3364+
3365+instance ToJSON Exclude where
3366+ toJSON (Exclude patterns) = toJSON patterns
3367+
3368+instance ToJSON Pattern where
3369+ toJSON (Pattern pattern) = toJSON pattern
3370+
3371+
3372+instance ToJSON FieldHighlight where
3373+ toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3374+ object [ fName .= fSettings ]
3375+ toJSON (FieldHighlight (FieldName fName) Nothing) =
3376+ object [ fName .= emptyObject ]
3377+
3378+instance ToJSON Highlights where
3379+ toJSON (Highlights global fields) =
3380+ omitNulls (("fields" .= fields)
3381+ : highlightSettingsPairs global)
3382+
3383+instance ToJSON HighlightSettings where
3384+ toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3385+
3386+highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3387+highlightSettingsPairs Nothing = []
3388+highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3389+highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3390+highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3391+
3392+
3393+plainHighPairs :: Maybe PlainHighlight -> [Pair]
3394+plainHighPairs Nothing = []
3395+plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3396+ [ "type" .= String "plain"]
3397+ ++ commonHighlightPairs plCom
3398+ ++ nonPostingsToPairs plNonPost
3399+
3400+postHighPairs :: Maybe PostingsHighlight -> [Pair]
3401+postHighPairs Nothing = []
3402+postHighPairs (Just (PostingsHighlight pCom)) =
3403+ ("type" .= String "postings")
3404+ : commonHighlightPairs pCom
3405+
3406+fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3407+fastVectorHighPairs Nothing = []
3408+fastVectorHighPairs (Just
3409+ (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3410+ fvBoundMaxScan fvFragOff fvMatchedFields
3411+ fvPhraseLim)) =
3412+ [ "type" .= String "fvh"
3413+ , "boundary_chars" .= fvBoundChars
3414+ , "boundary_max_scan" .= fvBoundMaxScan
3415+ , "fragment_offset" .= fvFragOff
3416+ , "matched_fields" .= fvMatchedFields
3417+ , "phraseLimit" .= fvPhraseLim]
3418+ ++ commonHighlightPairs fvCom
3419+ ++ nonPostingsToPairs fvNonPostSettings
3420+
3421+deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3422+deleteSeveral ks hm = foldr HM.delete hm ks
3423+
3424+commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3425+commonHighlightPairs Nothing = []
3426+commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3427+ chNoMatchSize chHighlightQuery
3428+ chRequireFieldMatch)) =
3429+ [ "order" .= chScore
3430+ , "force_source" .= chForceSource
3431+ , "encoder" .= chEncoder
3432+ , "no_match_size" .= chNoMatchSize
3433+ , "highlight_query" .= chHighlightQuery
3434+ , "require_fieldMatch" .= chRequireFieldMatch]
3435+ ++ highlightTagToPairs chTag
3436+
3437+
3438+nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3439+nonPostingsToPairs Nothing = []
3440+nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3441+ [ "fragment_size" .= npFragSize
3442+ , "number_of_fragments" .= npNumOfFrags]
3443+
3444+parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3445+parseNEJSON [] = fail "Expected non-empty list"
3446+parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3447+
3448+
3449+instance ToJSON HighlightEncoder where
3450+ toJSON DefaultEncoder = String "default"
3451+ toJSON HTMLEncoder = String "html"
3452+
3453+highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3454+highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3455+highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3456+ , "post_tags" .= post]
3457+highlightTagToPairs Nothing = []
3458+
3459+instance ToJSON SortSpec where
3460+ toJSON (DefaultSortSpec
3461+ (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3462+ dsSortMode dsMissingSort dsNestedFilter)) =
3463+ object [dsSortFieldName .= omitNulls base] where
3464+ base = [ "order" .= dsSortOrder
3465+ , "ignore_unmapped" .= dsIgnoreUnmapped
3466+ , "mode" .= dsSortMode
3467+ , "missing" .= dsMissingSort
3468+ , "nested_filter" .= dsNestedFilter ]
3469+
3470+ toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3471+ object [ "unit" .= units
3472+ , field .= gdsLatLon
3473+ , "order" .= gdsSortOrder ]
3474+
3475+
3476+instance ToJSON SortOrder where
3477+ toJSON Ascending = String "asc"
3478+ toJSON Descending = String "desc"
3479+
3480+
3481+instance ToJSON SortMode where
3482+ toJSON SortMin = String "min"
3483+ toJSON SortMax = String "max"
3484+ toJSON SortSum = String "sum"
3485+ toJSON SortAvg = String "avg"
3486+
3487+
3488+instance ToJSON Missing where
3489+ toJSON LastMissing = String "_last"
3490+ toJSON FirstMissing = String "_first"
3491+ toJSON (CustomMissing txt) = String txt
3492+
3493+
3494+instance ToJSON ScoreType where
3495+ toJSON ScoreTypeMax = "max"
3496+ toJSON ScoreTypeAvg = "avg"
3497+ toJSON ScoreTypeSum = "sum"
3498+ toJSON ScoreTypeNone = "none"
3499+
3500+instance FromJSON ScoreType where
3501+ parseJSON = withText "ScoreType" parse
3502+ where parse "max" = pure ScoreTypeMax
3503+ parse "avg" = pure ScoreTypeAvg
3504+ parse "sum" = pure ScoreTypeSum
3505+ parse "none" = pure ScoreTypeNone
3506+ parse t = fail ("Unexpected ScoreType: " <> show t)
3507+
3508+instance ToJSON Distance where
3509+ toJSON (Distance dCoefficient dUnit) =
3510+ String boltedTogether where
3511+ coefText = showText dCoefficient
3512+ (String unitText) = toJSON dUnit
3513+ boltedTogether = mappend coefText unitText
3514+
3515+instance FromJSON Distance where
3516+ parseJSON = withText "Distance" parse
3517+ where parse t = Distance <$> parseCoeff nT
3518+ <*> parseJSON (String unitT)
3519+ where (nT, unitT) = T.span validForNumber t
3520+ -- may be a better way to do this
3521+ validForNumber '-' = True
3522+ validForNumber '.' = True
3523+ validForNumber 'e' = True
3524+ validForNumber c = isNumber c
3525+ parseCoeff "" = fail "Empty string cannot be parsed as number"
3526+ parseCoeff s = return (read (T.unpack s))
3527+
3528+instance ToJSON DistanceUnit where
3529+ toJSON Miles = String "mi"
3530+ toJSON Yards = String "yd"
3531+ toJSON Feet = String "ft"
3532+ toJSON Inches = String "in"
3533+ toJSON Kilometers = String "km"
3534+ toJSON Meters = String "m"
3535+ toJSON Centimeters = String "cm"
3536+ toJSON Millimeters = String "mm"
3537+ toJSON NauticalMiles = String "nmi"
3538+
3539+
3540+instance FromJSON DistanceUnit where
3541+ parseJSON = withText "DistanceUnit" parse
3542+ where parse "mi" = pure Miles
3543+ parse "yd" = pure Yards
3544+ parse "ft" = pure Feet
3545+ parse "in" = pure Inches
3546+ parse "km" = pure Kilometers
3547+ parse "m" = pure Meters
3548+ parse "cm" = pure Centimeters
3549+ parse "mm" = pure Millimeters
3550+ parse "nmi" = pure NauticalMiles
3551+ parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3552+
3553+instance ToJSON DistanceType where
3554+ toJSON Arc = String "arc"
3555+ toJSON SloppyArc = String "sloppy_arc"
3556+ toJSON Plane = String "plane"
3557+
3558+instance FromJSON DistanceType where
3559+ parseJSON = withText "DistanceType" parse
3560+ where parse "arc" = pure Arc
3561+ parse "sloppy_arc" = pure SloppyArc
3562+ parse "plane" = pure Plane
3563+ parse t = fail ("Unrecognized DistanceType: " <> show t)
3564+
3565+
3566+instance ToJSON OptimizeBbox where
3567+ toJSON NoOptimizeBbox = String "none"
3568+ toJSON (OptimizeGeoFilterType gft) = toJSON gft
3569+
3570+instance FromJSON OptimizeBbox where
3571+ parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3572+ <|> parseOptimize v
3573+ where parseNoOptimize "none" = pure NoOptimizeBbox
3574+ parseNoOptimize _ = mzero
3575+ parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3576+
3577+instance ToJSON GeoBoundingBoxConstraint where
3578+ toJSON (GeoBoundingBoxConstraint
3579+ (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3580+ object [gbbcGeoBBField .= gbbcConstraintBox
3581+ , "_cache" .= cache
3582+ , "type" .= type']
3583+
3584+instance FromJSON GeoBoundingBoxConstraint where
3585+ parseJSON = withObject "GeoBoundingBoxConstraint" parse
3586+ where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3587+ [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3588+ <$> parseJSON v
3589+ <*> o .:? "_cache" .!= defaultCache
3590+ <*> o .: "type"
3591+ _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3592+
3593+instance ToJSON GeoFilterType where
3594+ toJSON GeoFilterMemory = String "memory"
3595+ toJSON GeoFilterIndexed = String "indexed"
3596+
3597+instance FromJSON GeoFilterType where
3598+ parseJSON = withText "GeoFilterType" parse
3599+ where parse "memory" = pure GeoFilterMemory
3600+ parse "indexed" = pure GeoFilterIndexed
3601+ parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3602+
3603+instance ToJSON GeoBoundingBox where
3604+ toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3605+ object ["top_left" .= gbbTopLeft
3606+ , "bottom_right" .= gbbBottomRight]
3607+
3608+instance FromJSON GeoBoundingBox where
3609+ parseJSON = withObject "GeoBoundingBox" parse
3610+ where parse o = GeoBoundingBox
3611+ <$> o .: "top_left"
3612+ <*> o .: "bottom_right"
3613+
3614+instance ToJSON LatLon where
3615+ toJSON (LatLon lLat lLon) =
3616+ object ["lat" .= lLat
3617+ , "lon" .= lLon]
3618+
3619+instance FromJSON LatLon where
3620+ parseJSON = withObject "LatLon" parse
3621+ where parse o = LatLon <$> o .: "lat"
3622+ <*> o .: "lon"
3623+
3624+-- index for smaller ranges, fielddata for longer ranges
3625+instance ToJSON RangeExecution where
3626+ toJSON RangeExecutionIndex = "index"
3627+ toJSON RangeExecutionFielddata = "fielddata"
3628+
3629+
3630+instance FromJSON RangeExecution where
3631+ parseJSON = withText "RangeExecution" parse
3632+ where parse "index" = pure RangeExecutionIndex
3633+ parse "fielddata" = pure RangeExecutionFielddata
3634+ parse t = error ("Unrecognized RangeExecution " <> show t)
3635+
3636+instance ToJSON RegexpFlags where
3637+ toJSON AllRegexpFlags = String "ALL"
3638+ toJSON NoRegexpFlags = String "NONE"
3639+ toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3640+ where flagStrs = map flagStr . nub $ h:fs
3641+ flagStr AnyString = "ANYSTRING"
3642+ flagStr Automaton = "AUTOMATON"
3643+ flagStr Complement = "COMPLEMENT"
3644+ flagStr Empty = "EMPTY"
3645+ flagStr Intersection = "INTERSECTION"
3646+ flagStr Interval = "INTERVAL"
3647+
3648+instance FromJSON RegexpFlags where
3649+ parseJSON = withText "RegexpFlags" parse
3650+ where parse "ALL" = pure AllRegexpFlags
3651+ parse "NONE" = pure NoRegexpFlags
3652+ parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3653+
3654+instance FromJSON RegexpFlag where
3655+ parseJSON = withText "RegexpFlag" parse
3656+ where parse "ANYSTRING" = pure AnyString
3657+ parse "AUTOMATON" = pure Automaton
3658+ parse "COMPLEMENT" = pure Complement
3659+ parse "EMPTY" = pure Empty
3660+ parse "INTERSECTION" = pure Intersection
3661+ parse "INTERVAL" = pure Interval
3662+ parse f = fail ("Unknown RegexpFlag: " <> show f)
3663+
3664+instance ToJSON Term where
3665+ toJSON (Term field value) = object ["term" .= object
3666+ [field .= value]]
3667+
3668+instance FromJSON Term where
3669+ parseJSON = withObject "Term" parse
3670+ where parse o = do termObj <- o .: "term"
3671+ case HM.toList termObj of
3672+ [(fn, v)] -> Term fn <$> parseJSON v
3673+ _ -> fail "Expected object with 1 field-named key"
3674+
3675+instance ToJSON BoolMatch where
3676+ toJSON (MustMatch term cache) = object ["must" .= term,
3677+ "_cache" .= cache]
3678+ toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3679+ "_cache" .= cache]
3680+ toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3681+ "_cache" .= cache]
3682+
3683+instance FromJSON BoolMatch where
3684+ parseJSON = withObject "BoolMatch" parse
3685+ where parse o = mustMatch `taggedWith` "must"
3686+ <|> mustNotMatch `taggedWith` "must_not"
3687+ <|> shouldMatch `taggedWith` "should"
3688+ where taggedWith parser k = parser =<< o .: k
3689+ mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3690+ mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3691+ shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3692+
3693+instance (FromJSON a) => FromJSON (SearchResult a) where
3694+ parseJSON (Object v) = SearchResult <$>
3695+ v .: "took" <*>
3696+ v .: "timed_out" <*>
3697+ v .: "_shards" <*>
5343698 v .: "hits" <*>
5353699 v .:? "aggregations" <*>
536− v .:? "_scroll_id" <*>
537− v .:? "suggest"
3700+ v .:? "_scroll_id"
3701+ parseJSON _ = empty
3702+
3703+instance (FromJSON a) => FromJSON (SearchHits a) where
3704+ parseJSON (Object v) = SearchHits <$>
3705+ v .: "total" <*>
3706+ v .: "max_score" <*>
3707+ v .: "hits"
3708+ parseJSON _ = empty
3709+
3710+instance (FromJSON a) => FromJSON (Hit a) where
3711+ parseJSON (Object v) = Hit <$>
3712+ v .: "_index" <*>
3713+ v .: "_type" <*>
3714+ v .: "_id" <*>
3715+ v .: "_score" <*>
3716+ v .:? "_source" <*>
3717+ v .:? "highlight"
5383718 parseJSON _ = empty
5393719
540−newtype ScrollId =
541− ScrollId Text
542− deriving (Eq, Show, Ord, ToJSON, FromJSON)
3720+instance FromJSON ShardResult where
3721+ parseJSON (Object v) = ShardResult <$>
3722+ v .: "total" <*>
3723+ v .: "successful" <*>
3724+ v .: "failed"
3725+ parseJSON _ = empty
3726+
3727+
3728+instance FromJSON DocVersion where
3729+ parseJSON v = do
3730+ i <- parseJSON v
3731+ maybe (fail "DocVersion out of range") return $ mkDocVersion i
3732+
3733+-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3734+instance FromJSON ReplicaCount where
3735+ parseJSON v = parseAsInt v
3736+ <|> parseAsString v
3737+ where parseAsInt = fmap ReplicaCount . parseJSON
3738+ parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3739+
3740+instance FromJSON ShardCount where
3741+ parseJSON v = parseAsInt v
3742+ <|> parseAsString v
3743+ where parseAsInt = fmap ShardCount . parseJSON
3744+ parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3745+
3746+instance Bounded DocVersion where
3747+ minBound = DocVersion 1
3748+ maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3749+
3750+instance Enum DocVersion where
3751+ succ x
3752+ | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3753+ | otherwise = succError "DocVersion"
3754+ pred x
3755+ | x /= minBound = DocVersion (pred $ docVersionNumber x)
3756+ | otherwise = predError "DocVersion"
3757+ toEnum i =
3758+ fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3759+ fromEnum = docVersionNumber
3760+ enumFrom = boundedEnumFrom
3761+ enumFromThen = boundedEnumFromThen
3762+
3763+-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3764+newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3765+
3766+-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3767+newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3768+
3769+
3770+data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3771+ | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3772+
3773+
3774+-- | Either specifies an exact repo name or one with globs in it,
3775+-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3776+data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3777+ | RepoPattern Text
3778+ deriving (Eq, Generic, Show, Typeable)
3779+
3780+-- | The unique name of a snapshot repository.
3781+newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3782+ deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3783+
3784+
3785+-- | A generic representation of a snapshot repo. This is what gets
3786+-- sent to and parsed from the server. For repo types enabled by
3787+-- plugins that aren't exported by this library, consider making a
3788+-- custom type which implements 'SnapshotRepo'. If it is a common repo
3789+-- type, consider submitting a pull request to have it included in the
3790+-- library proper
3791+data GenericSnapshotRepo = GenericSnapshotRepo {
3792+ gSnapshotRepoName :: SnapshotRepoName
3793+ , gSnapshotRepoType :: SnapshotRepoType
3794+ , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3795+ } deriving (Eq, Generic, Show, Typeable)
3796+
3797+
3798+instance SnapshotRepo GenericSnapshotRepo where
3799+ toGSnapshotRepo = id
3800+ fromGSnapshotRepo = Right
3801+
3802+
3803+newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3804+ deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3805+
3806+
3807+-- | Opaque representation of snapshot repo settings. Instances of
3808+-- 'SnapshotRepo' will produce this.
3809+newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3810+ deriving (Eq, Generic, Show, Typeable, ToJSON)
3811+
3812+
3813+ -- Regardless of whether you send strongly typed json, my version of
3814+ -- ES sends back stringly typed json in the settings, e.g. booleans
3815+ -- as strings, so we'll try to convert them.
3816+instance FromJSON GenericSnapshotRepoSettings where
3817+ parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3818+
3819+-- | The result of running 'verifySnapshotRepo'.
3820+newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3821+ deriving (Eq, Generic, Show, Typeable)
3822+
3823+
3824+instance FromJSON SnapshotVerification where
3825+ parseJSON = withObject "SnapshotVerification" parse
3826+ where
3827+ parse o = do
3828+ o2 <- o .: "nodes"
3829+ SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3830+ parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3831+ SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3832+
3833+
3834+-- | A node that has verified a snapshot
3835+data SnapshotNodeVerification = SnapshotNodeVerification {
3836+ snvFullId :: FullNodeId
3837+ , snvNodeName :: NodeName
3838+ } deriving (Eq, Generic, Show, Typeable)
3839+
3840+
3841+-- | Unique, automatically-generated name assigned to nodes that are
3842+-- usually returned in node-oriented APIs.
3843+newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3844+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3845+
3846+
3847+-- | A human-readable node name that is supplied by the user in the
3848+-- node config or automatically generated by ElasticSearch.
3849+newtype NodeName = NodeName { nodeName :: Text }
3850+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3851+
3852+newtype ClusterName = ClusterName { clusterName :: Text }
3853+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3854+
3855+data NodesInfo = NodesInfo {
3856+ nodesInfo :: [NodeInfo]
3857+ , nodesClusterName :: ClusterName
3858+ } deriving (Eq, Show, Generic, Typeable)
3859+
3860+-- | A quirky address format used throughout ElasticSearch. An example
3861+-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
3862+-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
3863+newtype EsAddress = EsAddress { esAddress :: Text }
3864+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3865+
3866+-- | Typically a 7 character hex string.
3867+newtype BuildHash = BuildHash { buildHash :: Text }
3868+ deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
3869+
3870+newtype PluginName = PluginName { pluginName :: Text }
3871+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3872+
3873+data NodeInfo = NodeInfo {
3874+ nodeInfoHTTPAddress :: EsAddress
3875+ , nodeInfoBuild :: BuildHash
3876+ , nodeInfoESVersion :: VersionNumber
3877+ , nodeInfoIP :: Server
3878+ , nodeInfoHost :: Server
3879+ , nodeInfoTransportAddress :: EsAddress
3880+ , nodeInfoName :: NodeName
3881+ , nodeInfoFullId :: FullNodeId
3882+ , nodeInfoPlugins :: [NodePluginInfo]
3883+ , nodeInfoHTTP :: NodeHTTPInfo
3884+ , nodeInfoTransport :: NodeTransportInfo
3885+ , nodeInfoNetwork :: NodeNetworkInfo
3886+ , nodeInfoThreadPool :: NodeThreadPoolsInfo
3887+ , nodeInfoJVM :: NodeJVMInfo
3888+ , nodeInfoProcess :: NodeProcessInfo
3889+ , nodeInfoOS :: NodeOSInfo
3890+ , nodeInfoSettings :: Object
3891+ -- ^ The members of the settings objects are not consistent,
3892+ -- dependent on plugins, etc.
3893+ } deriving (Eq, Show, Generic, Typeable)
3894+
3895+data NodePluginInfo = NodePluginInfo {
3896+ nodePluginSite :: Bool
3897+ -- ^ Is this a site plugin?
3898+ , nodePluginJVM :: Bool
3899+ -- ^ Is this plugin running on the JVM
3900+ , nodePluginDescription :: Text
3901+ , nodePluginVersion :: VersionNumber
3902+ , nodePluginName :: PluginName
3903+ } deriving (Eq, Show, Generic, Typeable)
3904+
3905+data NodeHTTPInfo = NodeHTTPInfo {
3906+ nodeHTTPMaxContentLength :: Bytes
3907+ , nodeHTTPTransportAddress :: BoundTransportAddress
3908+ } deriving (Eq, Show, Generic, Typeable)
3909+
3910+data NodeTransportInfo = NodeTransportInfo {
3911+ nodeTransportProfiles :: [BoundTransportAddress]
3912+ , nodeTransportAddress :: BoundTransportAddress
3913+ } deriving (Eq, Show, Generic, Typeable)
3914+
3915+data BoundTransportAddress = BoundTransportAddress {
3916+ publishAddress :: EsAddress
3917+ , boundAddress :: EsAddress
3918+ } deriving (Eq, Show, Generic, Typeable)
3919+
3920+data NodeNetworkInfo = NodeNetworkInfo {
3921+ nodeNetworkPrimaryInterface :: NodeNetworkInterface
3922+ , nodeNetworkRefreshInterval :: NominalDiffTime
3923+ } deriving (Eq, Show, Generic, Typeable)
3924+
3925+newtype MacAddress = MacAddress { macAddress :: Text }
3926+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3927+
3928+newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
3929+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3930+
3931+data NodeNetworkInterface = NodeNetworkInterface {
3932+ nodeNetIfaceMacAddress :: MacAddress
3933+ , nodeNetIfaceName :: NetworkInterfaceName
3934+ , nodeNetIfaceAddress :: Server
3935+ } deriving (Eq, Show, Generic, Typeable)
3936+
3937+data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
3938+ nodeThreadPoolsRefresh :: NodeThreadPoolInfo
3939+ , nodeThreadPoolsManagement :: NodeThreadPoolInfo
3940+ , nodeThreadPoolsPercolate :: NodeThreadPoolInfo
3941+ , nodeThreadPoolsListener :: Maybe NodeThreadPoolInfo
3942+ , nodeThreadPoolsFetchShardStarted :: Maybe NodeThreadPoolInfo
3943+ , nodeThreadPoolsSearch :: NodeThreadPoolInfo
3944+ , nodeThreadPoolsFlush :: NodeThreadPoolInfo
3945+ , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
3946+ , nodeThreadPoolsOptimize :: NodeThreadPoolInfo
3947+ , nodeThreadPoolsBulk :: NodeThreadPoolInfo
3948+ , nodeThreadPoolsSuggest :: NodeThreadPoolInfo
3949+ , nodeThreadPoolsMerge :: NodeThreadPoolInfo
3950+ , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
3951+ , nodeThreadPoolsGet :: NodeThreadPoolInfo
3952+ , nodeThreadPoolsFetchShardStore :: Maybe NodeThreadPoolInfo
3953+ , nodeThreadPoolsIndex :: NodeThreadPoolInfo
3954+ , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
3955+ } deriving (Eq, Show, Generic, Typeable)
3956+
3957+data NodeThreadPoolInfo = NodeThreadPoolInfo {
3958+ nodeThreadPoolQueueSize :: ThreadPoolSize
3959+ , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
3960+ , nodeThreadPoolMin :: Maybe Int
3961+ , nodeThreadPoolMax :: Maybe Int
3962+ , nodeThreadPoolType :: ThreadPoolType
3963+ } deriving (Eq, Show, Generic, Typeable)
3964+
3965+data ThreadPoolSize = ThreadPoolBounded Int
3966+ | ThreadPoolUnbounded
3967+ deriving (Eq, Show, Generic, Typeable)
3968+
3969+data ThreadPoolType = ThreadPoolScaling
3970+ | ThreadPoolFixed
3971+ | ThreadPoolCached
3972+ deriving (Eq, Show, Generic, Typeable)
3973+
3974+data NodeJVMInfo = NodeJVMInfo {
3975+ nodeJVMInfoMemoryPools :: [JVMMemoryPool]
3976+ , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
3977+ , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
3978+ , nodeJVMInfoStartTime :: UTCTime
3979+ , nodeJVMInfoVMVendor :: Text
3980+ , nodeJVMVMVersion :: VersionNumber
3981+ -- ^ JVM doesn't seme to follow normal version conventions
3982+ , nodeJVMVMName :: Text
3983+ , nodeJVMVersion :: VersionNumber
3984+ , nodeJVMPID :: PID
3985+ } deriving (Eq, Show, Generic, Typeable)
3986+
3987+-- | Handles quirks in the way JVM versions are rendered (1.7.0_101 -> 1.7.0.101)
3988+newtype JVMVersion = JVMVersion { unJVMVersion :: VersionNumber }
3989+
3990+data JVMMemoryInfo = JVMMemoryInfo {
3991+ jvmMemoryInfoDirectMax :: Bytes
3992+ , jvmMemoryInfoNonHeapMax :: Bytes
3993+ , jvmMemoryInfoNonHeapInit :: Bytes
3994+ , jvmMemoryInfoHeapMax :: Bytes
3995+ , jvmMemoryInfoHeapInit :: Bytes
3996+ } deriving (Eq, Show, Generic, Typeable)
3997+
3998+newtype JVMMemoryPool = JVMMemoryPool {
3999+ jvmMemoryPool :: Text
4000+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4001+
4002+newtype JVMGCCollector = JVMGCCollector {
4003+ jvmGCCollector :: Text
4004+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4005+
4006+newtype PID = PID {
4007+ pid :: Int
4008+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4009+
4010+data NodeOSInfo = NodeOSInfo {
4011+ nodeOSSwap :: Bytes
4012+ , nodeOSMem :: Bytes
4013+ , nodeOSCPUInfo :: CPUInfo
4014+ , nodeOSAvailableProcessors :: Int
4015+ , nodeOSRefreshInterval :: NominalDiffTime
4016+ } deriving (Eq, Show, Generic, Typeable)
4017+
4018+data CPUInfo = CPUInfo {
4019+ cpuCacheSize :: Bytes
4020+ , cpuCoresPerSocket :: Int
4021+ , cpuTotalSockets :: Int
4022+ , cpuTotalCores :: Int
4023+ , cpuMHZ :: Int
4024+ , cpuModel :: Text
4025+ , cpuVendor :: Text
4026+ } deriving (Eq, Show, Generic, Typeable)
4027+
4028+data NodeProcessInfo = NodeProcessInfo {
4029+ nodeProcessMLockAll :: Bool
4030+ -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
4031+ , nodeProcessMaxFileDescriptors :: Int
4032+ , nodeProcessId :: PID
4033+ , nodeProcessRefreshInterval :: NominalDiffTime
4034+ } deriving (Eq, Show, Generic, Typeable)
4035+
4036+data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
4037+ repoUpdateVerify :: Bool
4038+ -- ^ After creation/update, synchronously check that nodes can
4039+ -- write to this repo. Defaults to True. You may use False if you
4040+ -- need a faster response and plan on verifying manually later
4041+ -- with 'verifySnapshotRepo'.
4042+ } deriving (Eq, Show, Generic, Typeable)
4043+
4044+
4045+-- | Reasonable defaults for repo creation/update
4046+--
4047+-- * repoUpdateVerify True
4048+defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4049+defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4050+
4051+
4052+-- | A filesystem-based snapshot repo that ships with
4053+-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4054+-- used with 'updateSnapshotRepo'
4055+data FsSnapshotRepo = FsSnapshotRepo {
4056+ fsrName :: SnapshotRepoName
4057+ , fsrLocation :: FilePath
4058+ , fsrCompressMetadata :: Bool
4059+ , fsrChunkSize :: Maybe Bytes
4060+ -- ^ Size by which to split large files during snapshotting.
4061+ , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4062+ -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4063+ , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4064+ -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4065+ } deriving (Eq, Generic, Show, Typeable)
4066+
4067+
4068+instance SnapshotRepo FsSnapshotRepo where
4069+ toGSnapshotRepo FsSnapshotRepo {..} =
4070+ GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4071+ where
4072+ Object settings = object $ [ "location" .= fsrLocation
4073+ , "compress" .= fsrCompressMetadata
4074+ ] ++ optionalPairs
4075+ optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4076+ , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4077+ , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4078+ ]
4079+ fromGSnapshotRepo GenericSnapshotRepo {..}
4080+ | gSnapshotRepoType == fsRepoType = do
4081+ let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4082+ parseRepo $ do
4083+ FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4084+ <*> o .:? "compress" .!= False
4085+ <*> o .:? "chunk_size"
4086+ <*> o .:? "max_restore_bytes_per_sec"
4087+ <*> o .:? "max_snapshot_bytes_per_sec"
4088+ | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4089+
4090+
4091+parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4092+parseRepo parser = case parseEither (const parser) () of
4093+ Left e -> Left (OtherRepoConversionError (T.pack e))
4094+ Right a -> Right a
4095+
4096+
4097+fsRepoType :: SnapshotRepoType
4098+fsRepoType = SnapshotRepoType "fs"
4099+
4100+-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4101+class SnapshotRepo r where
4102+ toGSnapshotRepo :: r -> GenericSnapshotRepo
4103+ fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4104+
4105+
4106+data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4107+ -- ^ Expected type and actual type
4108+ | OtherRepoConversionError Text
4109+ deriving (Show, Eq, Generic, Typeable)
4110+
4111+
4112+instance Exception SnapshotRepoConversionError
4113+
4114+
4115+data SnapshotCreateSettings = SnapshotCreateSettings {
4116+ snapWaitForCompletion :: Bool
4117+ -- ^ Should the API call return immediately after initializing
4118+ -- the snapshot or wait until completed? Note that if this is
4119+ -- enabled it could wait a long time, so you should adjust your
4120+ -- 'ManagerSettings' accordingly to set long timeouts or
4121+ -- explicitly handle timeouts.
4122+ , snapIndices :: Maybe IndexSelection
4123+ -- ^ Nothing will snapshot all indices. Just [] is permissable and
4124+ -- will essentially be a no-op snapshot.
4125+ , snapIgnoreUnavailable :: Bool
4126+ -- ^ If set to True, any matched indices that don't exist will be
4127+ -- ignored. Otherwise it will be an error and fail.
4128+ , snapIncludeGlobalState :: Bool
4129+ , snapPartial :: Bool
4130+ -- ^ If some indices failed to snapshot (e.g. if not all primary
4131+ -- shards are available), should the process proceed?
4132+ } deriving (Eq, Generic, Show, Typeable)
4133+
4134+
4135+-- | Reasonable defaults for snapshot creation
4136+--
4137+-- * snapWaitForCompletion False
4138+-- * snapIndices Nothing
4139+-- * snapIgnoreUnavailable False
4140+-- * snapIncludeGlobalState True
4141+-- * snapPartial False
4142+defaultSnapshotCreateSettings :: SnapshotCreateSettings
4143+defaultSnapshotCreateSettings = SnapshotCreateSettings {
4144+ snapWaitForCompletion = False
4145+ , snapIndices = Nothing
4146+ , snapIgnoreUnavailable = False
4147+ , snapIncludeGlobalState = True
4148+ , snapPartial = False
4149+ }
4150+
4151+
4152+data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4153+ | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4154+
4155+
4156+-- | Either specifies an exact snapshot name or one with globs in it,
4157+-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4158+-- ES < 1.7
4159+data SnapshotPattern = ExactSnap SnapshotName
4160+ | SnapPattern Text
4161+ deriving (Eq, Generic, Show, Typeable)
4162+
4163+
4164+-- | General information about the state of a snapshot. Has some
4165+-- redundancies with 'SnapshotStatus'
4166+data SnapshotInfo = SnapshotInfo {
4167+ snapInfoShards :: ShardResult
4168+ , snapInfoFailures :: [SnapshotShardFailure]
4169+ , snapInfoDuration :: NominalDiffTime
4170+ , snapInfoEndTime :: UTCTime
4171+ , snapInfoStartTime :: UTCTime
4172+ , snapInfoState :: SnapshotState
4173+ , snapInfoIndices :: [IndexName]
4174+ , snapInfoName :: SnapshotName
4175+ } deriving (Eq, Generic, Show, Typeable)
4176+
4177+
4178+instance FromJSON SnapshotInfo where
4179+ parseJSON = withObject "SnapshotInfo" parse
4180+ where
4181+ parse o = SnapshotInfo <$> o .: "shards"
4182+ <*> o .: "failures"
4183+ <*> (unMS <$> o .: "duration_in_millis")
4184+ <*> (posixMS <$> o .: "end_time_in_millis")
4185+ <*> (posixMS <$> o .: "start_time_in_millis")
4186+ <*> o .: "state"
4187+ <*> o .: "indices"
4188+ <*> o .: "snapshot"
4189+
4190+data SnapshotShardFailure = SnapshotShardFailure {
4191+ snapShardFailureIndex :: IndexName
4192+ , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4193+ , snapShardFailureReason :: Text
4194+ , snapShardFailureShardId :: ShardId
4195+ } deriving (Eq, Show, Generic, Typeable)
4196+
4197+
4198+instance FromJSON SnapshotShardFailure where
4199+ parseJSON = withObject "SnapshotShardFailure" parse
4200+ where
4201+ parse o = SnapshotShardFailure <$> o .: "index"
4202+ <*> o .:? "node_id"
4203+ <*> o .: "reason"
4204+ <*> o .: "shard_id"
4205+
4206+
4207+newtype ShardId = ShardId { shardId :: Int }
4208+ deriving (Eq, Show, Generic, Typeable, FromJSON)
4209+
4210+-- | Milliseconds
4211+newtype MS = MS NominalDiffTime
4212+
4213+
4214+-- keeps the unexported constructor warnings at bay
4215+unMS :: MS -> NominalDiffTime
4216+unMS (MS t) = t
4217+
4218+
4219+instance FromJSON MS where
4220+ parseJSON = withScientific "MS" (return . MS . parse)
4221+ where
4222+ parse n = fromInteger ((truncate n) * 1000)
4223+
4224+
4225+data SnapshotState = SnapshotInit
4226+ | SnapshotStarted
4227+ | SnapshotSuccess
4228+ | SnapshotFailed
4229+ | SnapshotAborted
4230+ | SnapshotMissing
4231+ | SnapshotWaiting
4232+ deriving (Show, Eq, Generic, Typeable)
4233+
4234+instance FromJSON SnapshotState where
4235+ parseJSON = withText "SnapshotState" parse
4236+ where
4237+ parse "INIT" = return SnapshotInit
4238+ parse "STARTED" = return SnapshotStarted
4239+ parse "SUCCESS" = return SnapshotSuccess
4240+ parse "FAILED" = return SnapshotFailed
4241+ parse "ABORTED" = return SnapshotAborted
4242+ parse "MISSING" = return SnapshotMissing
4243+ parse "WAITING" = return SnapshotWaiting
4244+ parse t = fail ("Invalid snapshot state " <> T.unpack t)
4245+
4246+
4247+newtype SnapshotName = SnapshotName { snapshotName :: Text }
4248+ deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4249+
4250+
4251+data SnapshotRestoreSettings = SnapshotRestoreSettings {
4252+ snapRestoreWaitForCompletion :: Bool
4253+ -- ^ Should the API call return immediately after initializing
4254+ -- the restore or wait until completed? Note that if this is
4255+ -- enabled, it could wait a long time, so you should adjust your
4256+ -- 'ManagerSettings' accordingly to set long timeouts or
4257+ -- explicitly handle timeouts.
4258+ , snapRestoreIndices :: Maybe IndexSelection
4259+ -- ^ Nothing will restore all indices in the snapshot. Just [] is
4260+ -- permissable and will essentially be a no-op restore.
4261+ , snapRestoreIgnoreUnavailable :: Bool
4262+ -- ^ If set to True, any indices that do not exist will be ignored
4263+ -- during snapshot rather than failing the restore.
4264+ , snapRestoreIncludeGlobalState :: Bool
4265+ -- ^ If set to false, will ignore any global state in the snapshot
4266+ -- and will not restore it.
4267+ , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4268+ -- ^ A regex pattern for matching indices. Used with
4269+ -- 'snapRestoreRenameReplacement', the restore can reference the
4270+ -- matched index and create a new index name upon restore.
4271+ , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4272+ -- ^ Expression of how index renames should be constructed.
4273+ , snapRestorePartial :: Bool
4274+ -- ^ If some indices fail to restore, should the process proceed?
4275+ , snapRestoreIncludeAliases :: Bool
4276+ -- ^ Should the restore also restore the aliases captured in the
4277+ -- snapshot.
4278+ , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4279+ -- ^ Settings to apply during the restore process. __NOTE:__ This
4280+ -- option is not supported in ES < 1.5 and should be set to
4281+ -- Nothing in that case.
4282+ , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4283+ -- ^ This type could be more rich but it isn't clear which
4284+ -- settings are allowed to be ignored during restore, so we're
4285+ -- going with including this feature in a basic form rather than
4286+ -- omitting it. One example here would be
4287+ -- "index.refresh_interval". Any setting specified here will
4288+ -- revert back to the server default during the restore process.
4289+ } deriving (Eq, Generic, Show, Typeable)
4290+
4291+-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4292+newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4293+ deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4294+
4295+
4296+-- | A single token in a index renaming scheme for a restore. These
4297+-- are concatenated into a string before being sent to
4298+-- ElasticSearch. Check out these Java
4299+-- <https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html docs> to find out more if you're into that sort of thing.
4300+data RestoreRenameToken = RRTLit Text
4301+ -- ^ Just a literal string of characters
4302+ | RRSubWholeMatch
4303+ -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4304+ | RRSubGroup RRGroupRefNum
4305+ -- ^ A specific reference to a group number
4306+ deriving (Show, Eq, Generic, Typeable)
4307+
4308+
4309+-- | A group number for regex matching. Only values from 1-9 are
4310+-- supported. Construct with 'mkRRGroupRefNum'
4311+newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4312+ deriving (Show, Eq, Generic, Typeable, Ord)
4313+
4314+instance Bounded RRGroupRefNum where
4315+ minBound = RRGroupRefNum 1
4316+ maxBound = RRGroupRefNum 9
4317+
4318+
4319+-- | Only allows valid group number references (1-9).
4320+mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4321+mkRRGroupRefNum i
4322+ | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4323+ Just $ RRGroupRefNum i
4324+ | otherwise = Nothing
4325+
4326+
4327+-- | Reasonable defaults for snapshot restores
4328+--
4329+-- * snapRestoreWaitForCompletion False
4330+-- * snapRestoreIndices Nothing
4331+-- * snapRestoreIgnoreUnavailable False
4332+-- * snapRestoreIncludeGlobalState True
4333+-- * snapRestoreRenamePattern Nothing
4334+-- * snapRestoreRenameReplacement Nothing
4335+-- * snapRestorePartial False
4336+-- * snapRestoreIncludeAliases True
4337+-- * snapRestoreIndexSettingsOverrides Nothing
4338+-- * snapRestoreIgnoreIndexSettings Nothing
4339+defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4340+defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4341+ snapRestoreWaitForCompletion = False
4342+ , snapRestoreIndices = Nothing
4343+ , snapRestoreIgnoreUnavailable = False
4344+ , snapRestoreIncludeGlobalState = True
4345+ , snapRestoreRenamePattern = Nothing
4346+ , snapRestoreRenameReplacement = Nothing
4347+ , snapRestorePartial = False
4348+ , snapRestoreIncludeAliases = True
4349+ , snapRestoreIndexSettingsOverrides = Nothing
4350+ , snapRestoreIgnoreIndexSettings = Nothing
4351+ }
4352+
4353+
4354+-- | Index settings that can be overridden. The docs only mention you
4355+-- can update number of replicas, but there may be more. You
4356+-- definitely cannot override shard count.
4357+data RestoreIndexSettings = RestoreIndexSettings {
4358+ restoreOverrideReplicas :: Maybe ReplicaCount
4359+ } deriving (Show, Eq, Generic, Typeable)
4360+
4361+
4362+instance ToJSON RestoreIndexSettings where
4363+ toJSON RestoreIndexSettings {..} = object prs
4364+ where
4365+ prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
4366+
4367+
4368+instance FromJSON NodesInfo where
4369+ parseJSON = withObject "NodesInfo" parse
4370+ where
4371+ parse o = do
4372+ nodes <- o .: "nodes"
4373+ infos <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4374+ node <- parseJSON v
4375+ parseNodeInfo (FullNodeId fullNID) node
4376+ cn <- o .: "cluster_name"
4377+ return (NodesInfo infos cn)
4378+
4379+
4380+parseNodeInfo :: FullNodeId -> Object -> Parser NodeInfo
4381+parseNodeInfo nid o =
4382+ NodeInfo <$> o .: "http_address"
4383+ <*> o .: "build"
4384+ <*> o .: "version"
4385+ <*> o .: "ip"
4386+ <*> o .: "host"
4387+ <*> o .: "transport_address"
4388+ <*> o .: "name"
4389+ <*> pure nid
4390+ <*> o .: "plugins"
4391+ <*> o .: "http"
4392+ <*> o .: "transport"
4393+ <*> o .: "network"
4394+ <*> o .: "thread_pool"
4395+ <*> o .: "jvm"
4396+ <*> o .: "process"
4397+ <*> o .: "os"
4398+ <*> o .: "settings"
4399+
4400+instance FromJSON NodePluginInfo where
4401+ parseJSON = withObject "NodePluginInfo" parse
4402+ where
4403+ parse o = NodePluginInfo <$> o .: "site"
4404+ <*> o .: "jvm"
4405+ <*> o .: "description"
4406+ <*> o .: "version"
4407+ <*> o .: "name"
4408+
4409+instance FromJSON NodeHTTPInfo where
4410+ parseJSON = withObject "NodeHTTPInfo" parse
4411+ where
4412+ parse o = NodeHTTPInfo <$> o .: "max_content_length_in_bytes"
4413+ <*> parseJSON (Object o)
4414+
4415+instance FromJSON BoundTransportAddress where
4416+ parseJSON = withObject "BoundTransportAddress" parse
4417+ where
4418+ parse o = BoundTransportAddress <$> o .: "publish_address"
4419+ <*> o .: "bound_address"
4420+
4421+instance FromJSON NodeOSInfo where
4422+ parseJSON = withObject "NodeOSInfo" parse
4423+ where
4424+ parse o = do
4425+ swap <- o .: "swap"
4426+ mem <- o .: "mem"
4427+ NodeOSInfo <$> swap .: "total_in_bytes"
4428+ <*> mem .: "total_in_bytes"
4429+ <*> o .: "cpu"
4430+ <*> o .: "available_processors"
4431+ <*> (unMS <$> o .: "refresh_interval_in_millis")
4432+
4433+
4434+instance FromJSON CPUInfo where
4435+ parseJSON = withObject "CPUInfo" parse
4436+ where
4437+ parse o = CPUInfo <$> o .: "cache_size_in_bytes"
4438+ <*> o .: "cores_per_socket"
4439+ <*> o .: "total_sockets"
4440+ <*> o .: "total_cores"
4441+ <*> o .: "mhz"
4442+ <*> o .: "model"
4443+ <*> o .: "vendor"
4444+
4445+instance FromJSON NodeProcessInfo where
4446+ parseJSON = withObject "NodeProcessInfo" parse
4447+ where
4448+ parse o = NodeProcessInfo <$> o .: "mlockall"
4449+ <*> o .: "max_file_descriptors"
4450+ <*> o .: "id"
4451+ <*> (unMS <$> o .: "refresh_interval_in_millis")
4452+
4453+instance FromJSON NodeJVMInfo where
4454+ parseJSON = withObject "NodeJVMInfo" parse
4455+ where
4456+ parse o = NodeJVMInfo <$> o .: "memory_pools"
4457+ <*> o .: "gc_collectors"
4458+ <*> o .: "mem"
4459+ <*> (posixMS <$> o .: "start_time_in_millis")
4460+ <*> o .: "vm_vendor"
4461+ <*> o .: "vm_version"
4462+ <*> o .: "vm_name"
4463+ <*> (unJVMVersion <$> o .: "version")
4464+ <*> o .: "pid"
4465+
4466+instance FromJSON JVMVersion where
4467+ parseJSON (String t) =
4468+ JVMVersion <$> parseJSON (String (T.replace "_" "." t))
4469+ parseJSON v = JVMVersion <$> parseJSON v
4470+
4471+instance FromJSON JVMMemoryInfo where
4472+ parseJSON = withObject "JVMMemoryInfo" parse
4473+ where
4474+ parse o = JVMMemoryInfo <$> o .: "direct_max_in_bytes"
4475+ <*> o .: "non_heap_max_in_bytes"
4476+ <*> o .: "non_heap_init_in_bytes"
4477+ <*> o .: "heap_max_in_bytes"
4478+ <*> o .: "heap_init_in_bytes"
4479+
4480+instance FromJSON NodeThreadPoolsInfo where
4481+ parseJSON = withObject "NodeThreadPoolsInfo" parse
4482+ where
4483+ parse o = NodeThreadPoolsInfo <$> o .: "refresh"
4484+ <*> o .: "management"
4485+ <*> o .: "percolate"
4486+ <*> o .:? "listener"
4487+ <*> o .:? "fetch_shard_started"
4488+ <*> o .: "search"
4489+ <*> o .: "flush"
4490+ <*> o .: "warmer"
4491+ <*> o .: "optimize"
4492+ <*> o .: "bulk"
4493+ <*> o .: "suggest"
4494+ <*> o .: "merge"
4495+ <*> o .: "snapshot"
4496+ <*> o .: "get"
4497+ <*> o .:? "fetch_shard_store"
4498+ <*> o .: "index"
4499+ <*> o .: "generic"
4500+
4501+instance FromJSON NodeThreadPoolInfo where
4502+ parseJSON = withObject "NodeThreadPoolInfo" parse
4503+ where
4504+ parse o = do
4505+ ka <- maybe (return Nothing) (fmap Just . parseStringInterval) =<< o .:? "keep_alive"
4506+ NodeThreadPoolInfo <$> (parseJSON . unStringlyTypeJSON =<< o .: "queue_size")
4507+ <*> pure ka
4508+ <*> o .:? "min"
4509+ <*> o .:? "max"
4510+ <*> o .: "type"
4511+
4512+parseStringInterval :: (Monad m) => String -> m NominalDiffTime
4513+parseStringInterval s = case span isNumber s of
4514+ ("", _) -> fail "Invalid interval"
4515+ (nS, unitS) -> case (readMay nS, readMay unitS) of
4516+ (Just n, Just unit) -> return (fromInteger (n * unitNDT unit))
4517+ (Nothing, _) -> fail "Invalid interval number"
4518+ (_, Nothing) -> fail "Invalid interval unit"
4519+ where
4520+ unitNDT Seconds = 1
4521+ unitNDT Minutes = 60
4522+ unitNDT Hours = 60 * 60
4523+ unitNDT Days = 24 * 60 * 60
4524+ unitNDT Weeks = 7 * 24 * 60 * 60
4525+
4526+instance FromJSON ThreadPoolSize where
4527+ parseJSON v = parseAsNumber v <|> parseAsString v
4528+ where
4529+ parseAsNumber = parseAsInt <=< parseJSON
4530+ parseAsInt (-1) = return ThreadPoolUnbounded
4531+ parseAsInt n
4532+ | n >= 0 = return (ThreadPoolBounded n)
4533+ | otherwise = fail "Thread pool size must be >= -1."
4534+ parseAsString = withText "ThreadPoolSize" $ \t ->
4535+ case first (readMay . T.unpack) (T.span isNumber t) of
4536+ (Just n, "k") -> return (ThreadPoolBounded (n * 1000))
4537+ (Just n, "") -> return (ThreadPoolBounded n)
4538+ _ -> fail ("Invalid thread pool size " <> T.unpack t)
4539+
4540+instance FromJSON ThreadPoolType where
4541+ parseJSON = withText "ThreadPoolType" parse
4542+ where
4543+ parse "scaling" = return ThreadPoolScaling
4544+ parse "fixed" = return ThreadPoolFixed
4545+ parse "cached" = return ThreadPoolCached
4546+ parse e = fail ("Unexpected thread pool type" <> T.unpack e)
4547+
4548+instance FromJSON NodeTransportInfo where
4549+ parseJSON = withObject "NodeTransportInfo" parse
4550+ where
4551+ parse o = NodeTransportInfo <$> (maybe (return mempty) parseProfiles =<< o .:? "profiles")
4552+ <*> parseJSON (Object o)
4553+ parseProfiles (Object o) | HM.null o = return []
4554+ parseProfiles v@(Array _) = parseJSON v
4555+ parseProfiles Null = return []
4556+ parseProfiles _ = fail "Could not parse profiles"
4557+
4558+instance FromJSON NodeNetworkInfo where
4559+ parseJSON = withObject "NodeNetworkInfo" parse
4560+ where
4561+ parse o = NodeNetworkInfo <$> o .: "primary_interface"
4562+ <*> (unMS <$> o .: "refresh_interval_in_millis")
4563+
4564+
4565+instance FromJSON NodeNetworkInterface where
4566+ parseJSON = withObject "NodeNetworkInterface" parse
4567+ where
4568+ parse o = NodeNetworkInterface <$> o .: "mac_address"
4569+ <*> o .: "name"
4570+ <*> o .: "address"