@@ -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,2956 @@ 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) = (T.pack $ showGregorian date) <> "||"
1921+ fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1922+ fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1923+ fmtMod (RoundDownTo u) = "/" <> fmtU u
1924+ fmtU DMYear = "y"
1925+ fmtU DMMonth = "M"
1926+ fmtU DMWeek = "w"
1927+ fmtU DMDay = "d"
1928+ fmtU DMHour = "h"
1929+ fmtU DMMinute = "m"
1930+ fmtU DMSecond = "s"
1931+
1932+
1933+type AggregationResults = M.Map Text Value
1934+
1935+class BucketAggregation a where
1936+ key :: a -> BucketValue
1937+ docCount :: a -> Int
1938+ aggs :: a -> Maybe AggregationResults
1939+
1940+
1941+data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1942+
1943+data BucketValue = TextValue Text
1944+ | ScientificValue Scientific
1945+ | BoolValue Bool deriving (Read, Show)
1946+
1947+data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1948+
1949+data TermsResult = TermsResult { termKey :: BucketValue
1950+ , termsDocCount :: Int
1951+ , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1952+
1953+data DateHistogramResult = DateHistogramResult { dateKey :: Int
1954+ , dateKeyStr :: Maybe Text
1955+ , dateDocCount :: Int
1956+ , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1957+
1958+data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1959+ , dateRangeFrom :: Maybe UTCTime
1960+ , dateRangeFromAsString :: Maybe Text
1961+ , dateRangeTo :: Maybe UTCTime
1962+ , dateRangeToAsString :: Maybe Text
1963+ , dateRangeDocCount :: Int
1964+ , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1965+
1966+toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1967+toTerms = toAggResult
1968+
1969+toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1970+toDateHistogram = toAggResult
1971+
1972+toMissing :: Text -> AggregationResults -> Maybe MissingResult
1973+toMissing = toAggResult
1974+
1975+toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1976+toAggResult t a = M.lookup t a >>= deserialize
1977+ where deserialize = parseMaybe parseJSON
1978+
1979+instance BucketAggregation TermsResult where
1980+ key = termKey
1981+ docCount = termsDocCount
1982+ aggs = termsAggs
1983+
1984+instance BucketAggregation DateHistogramResult where
1985+ key = TextValue . showText . dateKey
1986+ docCount = dateDocCount
1987+ aggs = dateHistogramAggs
1988+
1989+instance BucketAggregation DateRangeResult where
1990+ key = TextValue . dateRangeKey
1991+ docCount = dateRangeDocCount
1992+ aggs = dateRangeAggs
1993+
1994+instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1995+ parseJSON (Object v) = Bucket <$>
1996+ v .: "buckets"
1997+ parseJSON _ = mempty
1998+
1999+instance FromJSON BucketValue where
2000+ parseJSON (String t) = return $ TextValue t
2001+ parseJSON (Number s) = return $ ScientificValue s
2002+ parseJSON (Bool b) = return $ BoolValue b
2003+ parseJSON _ = mempty
2004+
2005+instance FromJSON MissingResult where
2006+ parseJSON = withObject "MissingResult" parse
2007+ where parse v = MissingResult <$> v .: "doc_count"
2008+
2009+instance FromJSON TermsResult where
2010+ parseJSON (Object v) = TermsResult <$>
2011+ v .: "key" <*>
2012+ v .: "doc_count" <*>
2013+ v .:? "aggregations"
2014+ parseJSON _ = mempty
2015+
2016+instance FromJSON DateHistogramResult where
2017+ parseJSON (Object v) = DateHistogramResult <$>
2018+ v .: "key" <*>
2019+ v .:? "key_as_string" <*>
2020+ v .: "doc_count" <*>
2021+ v .:? "aggregations"
2022+ parseJSON _ = mempty
2023+
2024+instance FromJSON DateRangeResult where
2025+ parseJSON = withObject "DateRangeResult" parse
2026+ where parse v = DateRangeResult <$>
2027+ v .: "key" <*>
2028+ (fmap posixMS <$> v .:? "from") <*>
2029+ v .:? "from_as_string" <*>
2030+ (fmap posixMS <$> v .:? "to") <*>
2031+ v .:? "to_as_string" <*>
2032+ v .: "doc_count" <*>
2033+ v .:? "aggregations"
2034+
2035+instance FromJSON POSIXMS where
2036+ parseJSON = withScientific "POSIXMS" (return . parse)
2037+ where parse n = let n' = truncate n :: Integer
2038+ in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
2039+
2040+instance Monoid Filter where
2041+ mempty = IdentityFilter
2042+ mappend a b = AndFilter [a, b] defaultCache
2043+
2044+instance Seminearring Filter where
2045+ a <||> b = OrFilter [a, b] defaultCache
2046+
2047+instance ToJSON Filter where
2048+ toJSON (AndFilter filters cache) =
2049+ object ["and" .=
2050+ object [ "filters" .= fmap toJSON filters
2051+ , "_cache" .= cache]]
2052+
2053+ toJSON (OrFilter filters cache) =
2054+ object ["or" .=
2055+ object [ "filters" .= fmap toJSON filters
2056+ , "_cache" .= cache]]
2057+
2058+ toJSON (NotFilter notFilter cache) =
2059+ object ["not" .=
2060+ object ["filter" .= notFilter
2061+ , "_cache" .= cache]]
2062+
2063+ toJSON (IdentityFilter) =
2064+ object ["match_all" .= object []]
2065+
2066+ toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
2067+ object ["term" .= object base]
2068+ where base = [termFilterField .= termFilterValue,
2069+ "_cache" .= cache]
2070+
2071+ toJSON (ExistsFilter (FieldName fieldName)) =
2072+ object ["exists" .= object
2073+ ["field" .= fieldName]]
2074+
2075+ toJSON (BoolFilter boolMatch) =
2076+ object ["bool" .= boolMatch]
2077+
2078+ toJSON (GeoBoundingBoxFilter bbConstraint) =
2079+ object ["geo_bounding_box" .= bbConstraint]
2080+
2081+ toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2082+ distance distanceType optimizeBbox cache) =
2083+ object ["geo_distance" .=
2084+ object ["distance" .= distance
2085+ , "distance_type" .= distanceType
2086+ , "optimize_bbox" .= optimizeBbox
2087+ , distanceGeoField .= geoDistLatLon
2088+ , "_cache" .= cache]]
2089+
2090+ toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2091+ (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2092+ object ["geo_distance_range" .=
2093+ object ["from" .= geoDistRangeDistFrom
2094+ , "to" .= drDistanceTo
2095+ , gddrField .= drLatLon]]
2096+
2097+ toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2098+ object ["geo_polygon" .=
2099+ object [geoPolygonFilterField .=
2100+ object ["points" .= fmap toJSON latLons]]]
2101+
2102+ toJSON (IdsFilter (MappingName mappingName) values) =
2103+ object ["ids" .=
2104+ object ["type" .= mappingName
2105+ , "values" .= fmap unpackId values]]
2106+
2107+ toJSON (LimitFilter limit) =
2108+ object ["limit" .= object ["value" .= limit]]
2109+
2110+ toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2111+ object ["missing" .=
2112+ object ["field" .= fieldName
2113+ , "existence" .= existence
2114+ , "null_value" .= nullValue]]
2115+
2116+ toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2117+ object ["prefix" .=
2118+ object [fieldName .= fieldValue
2119+ , "_cache" .= cache]]
2120+
2121+ toJSON (QueryFilter query False) =
2122+ object ["query" .= toJSON query ]
2123+ toJSON (QueryFilter query True) =
2124+ object ["fquery" .=
2125+ object [ "query" .= toJSON query
2126+ , "_cache" .= True ]]
2127+
2128+ toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2129+ object ["range" .=
2130+ object [ fieldName .= object (rangeValueToPair rangeValue)
2131+ , "execution" .= rangeExecution
2132+ , "_cache" .= cache]]
2133+
2134+ toJSON (RegexpFilter (FieldName fieldName)
2135+ (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2136+ object ["regexp" .=
2137+ object [fieldName .=
2138+ object ["value" .= regexText
2139+ , "flags" .= flags]
2140+ , "_name" .= cacheName
2141+ , "_cache" .= cache
2142+ , "_cache_key" .= cacheKey]]
2143+
2144+instance FromJSON Filter where
2145+ parseJSON = withObject "Filter" parse
2146+ where parse o = andFilter `taggedWith` "and"
2147+ <|> orFilter `taggedWith` "or"
2148+ <|> notFilter `taggedWith` "not"
2149+ <|> identityFilter `taggedWith` "match_all"
2150+ <|> boolFilter `taggedWith` "bool"
2151+ <|> existsFilter `taggedWith` "exists"
2152+ <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2153+ <|> geoDistanceFilter `taggedWith` "geo_distance"
2154+ <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2155+ <|> geoPolygonFilter `taggedWith` "geo_polygon"
2156+ <|> idsFilter `taggedWith` "ids"
2157+ <|> limitFilter `taggedWith` "limit"
2158+ <|> missingFilter `taggedWith` "missing"
2159+ <|> prefixFilter `taggedWith` "prefix"
2160+ <|> queryFilter `taggedWith` "query"
2161+ <|> fqueryFilter `taggedWith` "fquery"
2162+ <|> rangeFilter `taggedWith` "range"
2163+ <|> regexpFilter `taggedWith` "regexp"
2164+ <|> termFilter `taggedWith` "term"
2165+ where taggedWith parser k = parser =<< o .: k
2166+ andFilter o = AndFilter <$> o .: "filters"
2167+ <*> o .:? "_cache" .!= defaultCache
2168+ orFilter o = OrFilter <$> o .: "filters"
2169+ <*> o .:? "_cache" .!= defaultCache
2170+ notFilter o = NotFilter <$> o .: "filter"
2171+ <*> o .: "_cache" .!= defaultCache
2172+ identityFilter :: Object -> Parser Filter
2173+ identityFilter m
2174+ | HM.null m = pure IdentityFilter
2175+ | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2176+ boolFilter = pure . BoolFilter
2177+ existsFilter o = ExistsFilter <$> o .: "field"
2178+ geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2179+ geoDistanceFilter o = do
2180+ case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2181+ [(fn, v)] -> do
2182+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
2183+ GeoDistanceFilter gp <$> o .: "distance"
2184+ <*> o .: "distance_type"
2185+ <*> o .: "optimize_bbox"
2186+ <*> o .:? "_cache" .!= defaultCache
2187+ _ -> fail "Could not find GeoDistanceFilter field name"
2188+ geoDistanceRangeFilter o = do
2189+ case HM.toList (deleteSeveral ["from", "to"] o) of
2190+ [(fn, v)] -> do
2191+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
2192+ rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2193+ return (GeoDistanceRangeFilter gp rng)
2194+ _ -> fail "Could not find GeoDistanceRangeFilter field name"
2195+ geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2196+ idsFilter o = IdsFilter <$> o .: "type"
2197+ <*> o .: "values"
2198+ limitFilter o = LimitFilter <$> o .: "value"
2199+ missingFilter o = MissingFilter <$> o .: "field"
2200+ <*> o .: "existence"
2201+ <*> o .: "null_value"
2202+ prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2203+ [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2204+ _ -> fail "Could not parse PrefixFilter"
2205+
2206+ queryFilter q = pure (QueryFilter q False)
2207+ fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2208+ rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2209+ [(fn, v)] -> RangeFilter (FieldName fn)
2210+ <$> parseJSON v
2211+ <*> o .: "execution"
2212+ <*> o .:? "_cache" .!= defaultCache
2213+ _ -> fail "Could not find field name for RangeFilter"
2214+ regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2215+ [(fn, Object o')] -> RegexpFilter (FieldName fn)
2216+ <$> o' .: "value"
2217+ <*> o' .: "flags"
2218+ <*> o .: "_name"
2219+ <*> o .:? "_cache" .!= defaultCache
2220+ <*> o .: "_cache_key"
2221+ _ -> fail "Could not find field name for RegexpFilter"
2222+ termFilter o = case HM.toList (HM.delete "_cache" o) of
2223+ [(termField, String termVal)] -> TermFilter (Term termField termVal)
2224+ <$> o .:? "_cache" .!= defaultCache
2225+ _ -> fail "Could not find term field for TermFilter"
2226+
2227+fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2228+fieldTagged f o = case HM.toList o of
2229+ [(k, Object o')] -> f (FieldName k) o'
2230+ _ -> fail "Expected object with 1 field-named key"
2231+
2232+instance ToJSON GeoPoint where
2233+ toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2234+ object [ geoPointField .= geoPointLatLon ]
2235+
2236+
2237+instance ToJSON Query where
2238+ toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2239+ object [ "term" .=
2240+ object [termQueryField .= object merged]]
2241+ where
2242+ base = [ "value" .= termQueryValue ]
2243+ boosted = maybe [] (return . ("boost" .=)) boost
2244+ merged = mappend base boosted
2245+
2246+ toJSON (TermsQuery fieldName terms) =
2247+ object [ "terms" .= object conjoined ]
2248+ where conjoined = [fieldName .= terms]
2249+
2250+ toJSON (IdsQuery idsQueryMappingName docIds) =
2251+ object [ "ids" .= object conjoined ]
2252+ where conjoined = [ "type" .= idsQueryMappingName
2253+ , "values" .= fmap toJSON docIds ]
2254+
2255+ toJSON (QueryQueryStringQuery qQueryStringQuery) =
2256+ object [ "query_string" .= qQueryStringQuery ]
2257+
2258+ toJSON (QueryMatchQuery matchQuery) =
2259+ object [ "match" .= matchQuery ]
2260+
2261+ toJSON (QueryMultiMatchQuery multiMatchQuery) =
2262+ toJSON multiMatchQuery
2263+
2264+ toJSON (QueryBoolQuery boolQuery) =
2265+ object [ "bool" .= boolQuery ]
2266+
2267+ toJSON (QueryBoostingQuery boostingQuery) =
2268+ object [ "boosting" .= boostingQuery ]
2269+
2270+ toJSON (QueryCommonTermsQuery commonTermsQuery) =
2271+ object [ "common" .= commonTermsQuery ]
2272+
2273+ toJSON (ConstantScoreFilter csFilter boost) =
2274+ object ["constant_score" .= object ["filter" .= csFilter
2275+ , "boost" .= boost]]
2276+
2277+ toJSON (ConstantScoreQuery query boost) =
2278+ object ["constant_score" .= object ["query" .= query
2279+ , "boost" .= boost]]
2280+
2281+ toJSON (QueryDisMaxQuery disMaxQuery) =
2282+ object [ "dis_max" .= disMaxQuery ]
2283+
2284+ toJSON (QueryFilteredQuery qFilteredQuery) =
2285+ object [ "filtered" .= qFilteredQuery ]
2286+
2287+ toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2288+ object [ "fuzzy_like_this" .= fuzzyQuery ]
2289+
2290+ toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2291+ object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2292+
2293+ toJSON (QueryFuzzyQuery fuzzyQuery) =
2294+ object [ "fuzzy" .= fuzzyQuery ]
2295+
2296+ toJSON (QueryHasChildQuery childQuery) =
2297+ object [ "has_child" .= childQuery ]
2298+
2299+ toJSON (QueryHasParentQuery parentQuery) =
2300+ object [ "has_parent" .= parentQuery ]
2301+
2302+ toJSON (QueryIndicesQuery qIndicesQuery) =
2303+ object [ "indices" .= qIndicesQuery ]
2304+
2305+ toJSON (MatchAllQuery boost) =
2306+ object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2307+
2308+ toJSON (QueryMoreLikeThisQuery query) =
2309+ object [ "more_like_this" .= query ]
2310+
2311+ toJSON (QueryMoreLikeThisFieldQuery query) =
2312+ object [ "more_like_this_field" .= query ]
2313+
2314+ toJSON (QueryNestedQuery query) =
2315+ object [ "nested" .= query ]
2316+
2317+ toJSON (QueryPrefixQuery query) =
2318+ object [ "prefix" .= query ]
2319+
2320+ toJSON (QueryRangeQuery query) =
2321+ object [ "range" .= query ]
2322+
2323+ toJSON (QueryRegexpQuery query) =
2324+ object [ "regexp" .= query ]
2325+
2326+ toJSON (QuerySimpleQueryStringQuery query) =
2327+ object [ "simple_query_string" .= query ]
2328+
2329+instance FromJSON Query where
2330+ parseJSON v = withObject "Query" parse v
2331+ where parse o = termQuery `taggedWith` "term"
2332+ <|> termsQuery `taggedWith` "terms"
2333+ <|> idsQuery `taggedWith` "ids"
2334+ <|> queryQueryStringQuery `taggedWith` "query_string"
2335+ <|> queryMatchQuery `taggedWith` "match"
2336+ <|> queryMultiMatchQuery
2337+ <|> queryBoolQuery `taggedWith` "bool"
2338+ <|> queryBoostingQuery `taggedWith` "boosting"
2339+ <|> queryCommonTermsQuery `taggedWith` "common"
2340+ <|> constantScoreFilter `taggedWith` "constant_score"
2341+ <|> constantScoreQuery `taggedWith` "constant_score"
2342+ <|> queryDisMaxQuery `taggedWith` "dis_max"
2343+ <|> queryFilteredQuery `taggedWith` "filtered"
2344+ <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2345+ <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2346+ <|> queryFuzzyQuery `taggedWith` "fuzzy"
2347+ <|> queryHasChildQuery `taggedWith` "has_child"
2348+ <|> queryHasParentQuery `taggedWith` "has_parent"
2349+ <|> queryIndicesQuery `taggedWith` "indices"
2350+ <|> matchAllQuery `taggedWith` "match_all"
2351+ <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2352+ <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2353+ <|> queryNestedQuery `taggedWith` "nested"
2354+ <|> queryPrefixQuery `taggedWith` "prefix"
2355+ <|> queryRangeQuery `taggedWith` "range"
2356+ <|> queryRegexpQuery `taggedWith` "regexp"
2357+ <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2358+ where taggedWith parser k = parser =<< o .: k
2359+ termQuery = fieldTagged $ \(FieldName fn) o ->
2360+ TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2361+ termsQuery o = case HM.toList o of
2362+ [(fn, vs)] -> do vals <- parseJSON vs
2363+ case vals of
2364+ x:xs -> return (TermsQuery fn (x :| xs))
2365+ _ -> fail "Expected non empty list of values"
2366+ _ -> fail "Expected object with 1 field-named key"
2367+ idsQuery o = IdsQuery <$> o .: "type"
2368+ <*> o .: "values"
2369+ queryQueryStringQuery = pure . QueryQueryStringQuery
2370+ queryMatchQuery = pure . QueryMatchQuery
2371+ queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2372+ queryBoolQuery = pure . QueryBoolQuery
2373+ queryBoostingQuery = pure . QueryBoostingQuery
2374+ queryCommonTermsQuery = pure . QueryCommonTermsQuery
2375+ constantScoreFilter o = case HM.lookup "filter" o of
2376+ Just x -> ConstantScoreFilter <$> parseJSON x
2377+ <*> o .: "boost"
2378+ _ -> fail "Does not appear to be a ConstantScoreFilter"
2379+ constantScoreQuery o = case HM.lookup "query" o of
2380+ Just x -> ConstantScoreQuery <$> parseJSON x
2381+ <*> o .: "boost"
2382+ _ -> fail "Does not appear to be a ConstantScoreQuery"
2383+ queryDisMaxQuery = pure . QueryDisMaxQuery
2384+ queryFilteredQuery = pure . QueryFilteredQuery
2385+ queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2386+ queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2387+ queryFuzzyQuery = pure . QueryFuzzyQuery
2388+ queryHasChildQuery = pure . QueryHasChildQuery
2389+ queryHasParentQuery = pure . QueryHasParentQuery
2390+ queryIndicesQuery = pure . QueryIndicesQuery
2391+ matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2392+ queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2393+ queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2394+ queryNestedQuery = pure . QueryNestedQuery
2395+ queryPrefixQuery = pure . QueryPrefixQuery
2396+ queryRangeQuery = pure . QueryRangeQuery
2397+ queryRegexpQuery = pure . QueryRegexpQuery
2398+ querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2399+
2400+
2401+omitNulls :: [(Text, Value)] -> Value
2402+omitNulls = object . filter notNull where
2403+ notNull (_, Null) = False
2404+ notNull (_, Array a) = (not . V.null) a
2405+ notNull _ = True
2406+
2407+
2408+instance ToJSON SimpleQueryStringQuery where
2409+ toJSON SimpleQueryStringQuery {..} =
2410+ omitNulls (base ++ maybeAdd)
2411+ where base = [ "query" .= simpleQueryStringQuery ]
2412+ maybeAdd = [ "fields" .= simpleQueryStringField
2413+ , "default_operator" .= simpleQueryStringOperator
2414+ , "analyzer" .= simpleQueryStringAnalyzer
2415+ , "flags" .= simpleQueryStringFlags
2416+ , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2417+ , "locale" .= simpleQueryStringLocale ]
2418+
2419+instance FromJSON SimpleQueryStringQuery where
2420+ parseJSON = withObject "SimpleQueryStringQuery" parse
2421+ where parse o = SimpleQueryStringQuery <$> o .: "query"
2422+ <*> o .:? "fields"
2423+ <*> o .:? "default_operator"
2424+ <*> o .:? "analyzer"
2425+ <*> (parseFlags <$> o .:? "flags")
2426+ <*> o .:? "lowercase_expanded_terms"
2427+ <*> o .:? "locale"
2428+ parseFlags (Just (x:xs)) = Just (x :| xs)
2429+ parseFlags _ = Nothing
2430+
2431+instance ToJSON FieldOrFields where
2432+ toJSON (FofField fieldName) =
2433+ toJSON fieldName
2434+ toJSON (FofFields fieldNames) =
2435+ toJSON fieldNames
2436+
2437+instance FromJSON FieldOrFields where
2438+ parseJSON v = FofField <$> parseJSON v
2439+ <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2440+
2441+instance ToJSON SimpleQueryFlag where
2442+ toJSON SimpleQueryAll = "ALL"
2443+ toJSON SimpleQueryNone = "NONE"
2444+ toJSON SimpleQueryAnd = "AND"
2445+ toJSON SimpleQueryOr = "OR"
2446+ toJSON SimpleQueryPrefix = "PREFIX"
2447+ toJSON SimpleQueryPhrase = "PHRASE"
2448+ toJSON SimpleQueryPrecedence = "PRECEDENCE"
2449+ toJSON SimpleQueryEscape = "ESCAPE"
2450+ toJSON SimpleQueryWhitespace = "WHITESPACE"
2451+ toJSON SimpleQueryFuzzy = "FUZZY"
2452+ toJSON SimpleQueryNear = "NEAR"
2453+ toJSON SimpleQuerySlop = "SLOP"
2454+
2455+instance FromJSON SimpleQueryFlag where
2456+ parseJSON = withText "SimpleQueryFlag" parse
2457+ where parse "ALL" = pure SimpleQueryAll
2458+ parse "NONE" = pure SimpleQueryNone
2459+ parse "AND" = pure SimpleQueryAnd
2460+ parse "OR" = pure SimpleQueryOr
2461+ parse "PREFIX" = pure SimpleQueryPrefix
2462+ parse "PHRASE" = pure SimpleQueryPhrase
2463+ parse "PRECEDENCE" = pure SimpleQueryPrecedence
2464+ parse "ESCAPE" = pure SimpleQueryEscape
2465+ parse "WHITESPACE" = pure SimpleQueryWhitespace
2466+ parse "FUZZY" = pure SimpleQueryFuzzy
2467+ parse "NEAR" = pure SimpleQueryNear
2468+ parse "SLOP" = pure SimpleQuerySlop
2469+ parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2470+
2471+instance ToJSON RegexpQuery where
2472+ toJSON (RegexpQuery (FieldName rqQueryField)
2473+ (Regexp regexpQueryQuery) rqQueryFlags
2474+ rqQueryBoost) =
2475+ object [ rqQueryField .= omitNulls base ]
2476+ where base = [ "value" .= regexpQueryQuery
2477+ , "flags" .= rqQueryFlags
2478+ , "boost" .= rqQueryBoost ]
2479+
2480+instance FromJSON RegexpQuery where
2481+ parseJSON = withObject "RegexpQuery" parse
2482+ where parse = fieldTagged $ \fn o ->
2483+ RegexpQuery fn
2484+ <$> o .: "value"
2485+ <*> o .: "flags"
2486+ <*> o .:? "boost"
2487+
2488+instance ToJSON QueryStringQuery where
2489+ toJSON (QueryStringQuery qsQueryString
2490+ qsDefaultField qsOperator
2491+ qsAnalyzer qsAllowWildcard
2492+ qsLowercaseExpanded qsEnablePositionIncrements
2493+ qsFuzzyMaxExpansions qsFuzziness
2494+ qsFuzzyPrefixLength qsPhraseSlop
2495+ qsBoost qsAnalyzeWildcard
2496+ qsGeneratePhraseQueries qsMinimumShouldMatch
2497+ qsLenient qsLocale) =
2498+ omitNulls base
2499+ where
2500+ base = [ "query" .= qsQueryString
2501+ , "default_field" .= qsDefaultField
2502+ , "default_operator" .= qsOperator
2503+ , "analyzer" .= qsAnalyzer
2504+ , "allow_leading_wildcard" .= qsAllowWildcard
2505+ , "lowercase_expanded_terms" .= qsLowercaseExpanded
2506+ , "enable_position_increments" .= qsEnablePositionIncrements
2507+ , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2508+ , "fuzziness" .= qsFuzziness
2509+ , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2510+ , "phrase_slop" .= qsPhraseSlop
2511+ , "boost" .= qsBoost
2512+ , "analyze_wildcard" .= qsAnalyzeWildcard
2513+ , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2514+ , "minimum_should_match" .= qsMinimumShouldMatch
2515+ , "lenient" .= qsLenient
2516+ , "locale" .= qsLocale ]
2517+
2518+instance FromJSON QueryStringQuery where
2519+ parseJSON = withObject "QueryStringQuery" parse
2520+ where parse o = QueryStringQuery
2521+ <$> o .: "query"
2522+ <*> o .:? "default_field"
2523+ <*> o .:? "default_operator"
2524+ <*> o .:? "analyzer"
2525+ <*> o .:? "allow_leading_wildcard"
2526+ <*> o .:? "lowercase_expanded_terms"
2527+ <*> o .:? "enable_position_increments"
2528+ <*> o .:? "fuzzy_max_expansions"
2529+ <*> o .:? "fuzziness"
2530+ <*> o .:? "fuzzy_prefix_length"
2531+ <*> o .:? "phrase_slop"
2532+ <*> o .:? "boost"
2533+ <*> o .:? "analyze_wildcard"
2534+ <*> o .:? "auto_generate_phrase_queries"
2535+ <*> o .:? "minimum_should_match"
2536+ <*> o .:? "lenient"
2537+ <*> o .:? "locale"
2538+
2539+instance ToJSON RangeQuery where
2540+ toJSON (RangeQuery (FieldName fieldName) range boost) =
2541+ object [ fieldName .= object conjoined ]
2542+ where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2543+
2544+instance FromJSON RangeQuery where
2545+ parseJSON = withObject "RangeQuery" parse
2546+ where parse = fieldTagged $ \fn o ->
2547+ RangeQuery fn
2548+ <$> parseJSON (Object o)
2549+ <*> o .: "boost"
2550+
2551+instance FromJSON RangeValue where
2552+ parseJSON = withObject "RangeValue" parse
2553+ where parse o = parseDate o
2554+ <|> parseDouble o
2555+ parseDate o = do lt <- o .:? "lt"
2556+ lte <- o .:? "lte"
2557+ gt <- o .:? "gt"
2558+ gte <- o .:? "gte"
2559+ case (lt, lte, gt, gte) of
2560+ (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2561+ (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2562+ (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2563+ (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2564+ (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2565+ (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2566+ (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2567+ (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2568+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2569+ parseDouble o = do lt <- o .:? "lt"
2570+ lte <- o .:? "lte"
2571+ gt <- o .:? "gt"
2572+ gte <- o .:? "gte"
2573+ case (lt, lte, gt, gte) of
2574+ (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2575+ (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2576+ (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2577+ (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2578+ (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2579+ (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2580+ (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2581+ (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2582+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2583+
2584+instance ToJSON PrefixQuery where
2585+ toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2586+ object [ fieldName .= omitNulls base ]
2587+ where base = [ "value" .= queryValue
2588+ , "boost" .= boost ]
2589+
2590+instance FromJSON PrefixQuery where
2591+ parseJSON = withObject "PrefixQuery" parse
2592+ where parse = fieldTagged $ \fn o ->
2593+ PrefixQuery fn
2594+ <$> o .: "value"
2595+ <*> o .:? "boost"
2596+
2597+instance ToJSON NestedQuery where
2598+ toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2599+ object [ "path" .= nqPath
2600+ , "score_mode" .= nqScoreType
2601+ , "query" .= nqQuery ]
2602+
2603+instance FromJSON NestedQuery where
2604+ parseJSON = withObject "NestedQuery" parse
2605+ where parse o = NestedQuery
2606+ <$> o .: "path"
2607+ <*> o .: "score_mode"
2608+ <*> o .: "query"
2609+
2610+instance ToJSON MoreLikeThisFieldQuery where
2611+ toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2612+ percent mtf mqt stopwords mindf maxdf
2613+ minwl maxwl boostTerms boost analyzer) =
2614+ object [ fieldName .= omitNulls base ]
2615+ where base = [ "like_text" .= text
2616+ , "percent_terms_to_match" .= percent
2617+ , "min_term_freq" .= mtf
2618+ , "max_query_terms" .= mqt
2619+ , "stop_words" .= stopwords
2620+ , "min_doc_freq" .= mindf
2621+ , "max_doc_freq" .= maxdf
2622+ , "min_word_length" .= minwl
2623+ , "max_word_length" .= maxwl
2624+ , "boost_terms" .= boostTerms
2625+ , "boost" .= boost
2626+ , "analyzer" .= analyzer ]
2627+
2628+instance FromJSON MoreLikeThisFieldQuery where
2629+ parseJSON = withObject "MoreLikeThisFieldQuery" parse
2630+ where parse = fieldTagged $ \fn o ->
2631+ MoreLikeThisFieldQuery
2632+ <$> o .: "like_text"
2633+ <*> pure fn
2634+ <*> o .:? "percent_terms_to_match"
2635+ <*> o .:? "min_term_freq"
2636+ <*> o .:? "max_query_terms"
2637+ -- <*> (optionalNE =<< o .:? "stop_words")
2638+ <*> o .:? "stop_words"
2639+ <*> o .:? "min_doc_freq"
2640+ <*> o .:? "max_doc_freq"
2641+ <*> o .:? "min_word_length"
2642+ <*> o .:? "max_word_length"
2643+ <*> o .:? "boost_terms"
2644+ <*> o .:? "boost"
2645+ <*> o .:? "analyzer"
2646+ -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2647+
2648+instance ToJSON MoreLikeThisQuery where
2649+ toJSON (MoreLikeThisQuery text fields percent
2650+ mtf mqt stopwords mindf maxdf
2651+ minwl maxwl boostTerms boost analyzer) =
2652+ omitNulls base
2653+ where base = [ "like_text" .= text
2654+ , "fields" .= fields
2655+ , "percent_terms_to_match" .= percent
2656+ , "min_term_freq" .= mtf
2657+ , "max_query_terms" .= mqt
2658+ , "stop_words" .= stopwords
2659+ , "min_doc_freq" .= mindf
2660+ , "max_doc_freq" .= maxdf
2661+ , "min_word_length" .= minwl
2662+ , "max_word_length" .= maxwl
2663+ , "boost_terms" .= boostTerms
2664+ , "boost" .= boost
2665+ , "analyzer" .= analyzer ]
2666+
2667+instance FromJSON MoreLikeThisQuery where
2668+ parseJSON = withObject "MoreLikeThisQuery" parse
2669+ where parse o = MoreLikeThisQuery
2670+ <$> o .: "like_text"
2671+ -- <*> (optionalNE =<< o .:? "fields")
2672+ <*> o .:? "fields"
2673+ <*> o .:? "percent_terms_to_match"
2674+ <*> o .:? "min_term_freq"
2675+ <*> o .:? "max_query_terms"
2676+ -- <*> (optionalNE =<< o .:? "stop_words")
2677+ <*> o .:? "stop_words"
2678+ <*> o .:? "min_doc_freq"
2679+ <*> o .:? "max_doc_freq"
2680+ <*> o .:? "min_word_length"
2681+ <*> o .:? "max_word_length"
2682+ <*> o .:? "boost_terms"
2683+ <*> o .:? "boost"
2684+ <*> o .:? "analyzer"
2685+ -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2686+
2687+instance ToJSON IndicesQuery where
2688+ toJSON (IndicesQuery indices query noMatch) =
2689+ omitNulls [ "indices" .= indices
2690+ , "no_match_query" .= noMatch
2691+ , "query" .= query ]
2692+
2693+instance FromJSON IndicesQuery where
2694+ parseJSON = withObject "IndicesQuery" parse
2695+ where parse o = IndicesQuery
2696+ <$> o .:? "indices" .!= []
2697+ <*> o .: "query"
2698+ <*> o .:? "no_match_query"
2699+
2700+instance ToJSON HasParentQuery where
2701+ toJSON (HasParentQuery queryType query scoreType) =
2702+ omitNulls [ "parent_type" .= queryType
2703+ , "score_type" .= scoreType
2704+ , "query" .= query ]
2705+
2706+instance FromJSON HasParentQuery where
2707+ parseJSON = withObject "HasParentQuery" parse
2708+ where parse o = HasParentQuery
2709+ <$> o .: "parent_type"
2710+ <*> o .: "query"
2711+ <*> o .:? "score_type"
2712+
2713+instance ToJSON HasChildQuery where
2714+ toJSON (HasChildQuery queryType query scoreType) =
2715+ omitNulls [ "query" .= query
2716+ , "score_type" .= scoreType
2717+ , "type" .= queryType ]
2718+
2719+instance FromJSON HasChildQuery where
2720+ parseJSON = withObject "HasChildQuery" parse
2721+ where parse o = HasChildQuery
2722+ <$> o .: "type"
2723+ <*> o .: "query"
2724+ <*> o .:? "score_type"
2725+
2726+instance ToJSON FuzzyQuery where
2727+ toJSON (FuzzyQuery (FieldName fieldName) queryText
2728+ prefixLength maxEx fuzziness boost) =
2729+ object [ fieldName .= omitNulls base ]
2730+ where base = [ "value" .= queryText
2731+ , "fuzziness" .= fuzziness
2732+ , "prefix_length" .= prefixLength
2733+ , "boost" .= boost
2734+ , "max_expansions" .= maxEx ]
2735+
2736+instance FromJSON FuzzyQuery where
2737+ parseJSON = withObject "FuzzyQuery" parse
2738+ where parse = fieldTagged $ \fn o ->
2739+ FuzzyQuery fn
2740+ <$> o .: "value"
2741+ <*> o .: "prefix_length"
2742+ <*> o .: "max_expansions"
2743+ <*> o .: "fuzziness"
2744+ <*> o .:? "boost"
2745+
2746+instance ToJSON FuzzyLikeFieldQuery where
2747+ toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2748+ fieldText maxTerms ignoreFreq fuzziness prefixLength
2749+ boost analyzer) =
2750+ object [ fieldName .=
2751+ omitNulls [ "like_text" .= fieldText
2752+ , "max_query_terms" .= maxTerms
2753+ , "ignore_tf" .= ignoreFreq
2754+ , "fuzziness" .= fuzziness
2755+ , "prefix_length" .= prefixLength
2756+ , "analyzer" .= analyzer
2757+ , "boost" .= boost ]]
2758+
2759+instance FromJSON FuzzyLikeFieldQuery where
2760+ parseJSON = withObject "FuzzyLikeFieldQuery" parse
2761+ where parse = fieldTagged $ \fn o ->
2762+ FuzzyLikeFieldQuery fn
2763+ <$> o .: "like_text"
2764+ <*> o .: "max_query_terms"
2765+ <*> o .: "ignore_tf"
2766+ <*> o .: "fuzziness"
2767+ <*> o .: "prefix_length"
2768+ <*> o .: "boost"
2769+ <*> o .:? "analyzer"
2770+
2771+instance ToJSON FuzzyLikeThisQuery where
2772+ toJSON (FuzzyLikeThisQuery fields text maxTerms
2773+ ignoreFreq fuzziness prefixLength boost analyzer) =
2774+ omitNulls base
2775+ where base = [ "fields" .= fields
2776+ , "like_text" .= text
2777+ , "max_query_terms" .= maxTerms
2778+ , "ignore_tf" .= ignoreFreq
2779+ , "fuzziness" .= fuzziness
2780+ , "prefix_length" .= prefixLength
2781+ , "analyzer" .= analyzer
2782+ , "boost" .= boost ]
2783+
2784+instance FromJSON FuzzyLikeThisQuery where
2785+ parseJSON = withObject "FuzzyLikeThisQuery" parse
2786+ where parse o = FuzzyLikeThisQuery
2787+ <$> o .:? "fields" .!= []
2788+ <*> o .: "like_text"
2789+ <*> o .: "max_query_terms"
2790+ <*> o .: "ignore_tf"
2791+ <*> o .: "fuzziness"
2792+ <*> o .: "prefix_length"
2793+ <*> o .: "boost"
2794+ <*> o .:? "analyzer"
2795+
2796+instance ToJSON FilteredQuery where
2797+ toJSON (FilteredQuery query fFilter) =
2798+ object [ "query" .= query
2799+ , "filter" .= fFilter ]
2800+
2801+instance FromJSON FilteredQuery where
2802+ parseJSON = withObject "FilteredQuery" parse
2803+ where parse o = FilteredQuery
2804+ <$> o .: "query"
2805+ <*> o .: "filter"
2806+
2807+instance ToJSON DisMaxQuery where
2808+ toJSON (DisMaxQuery queries tiebreaker boost) =
2809+ omitNulls base
2810+ where base = [ "queries" .= queries
2811+ , "boost" .= boost
2812+ , "tie_breaker" .= tiebreaker ]
2813+
2814+instance FromJSON DisMaxQuery where
2815+ parseJSON = withObject "DisMaxQuery" parse
2816+ where parse o = DisMaxQuery
2817+ <$> o .:? "queries" .!= []
2818+ <*> o .: "tie_breaker"
2819+ <*> o .:? "boost"
2820+
2821+instance ToJSON CommonTermsQuery where
2822+ toJSON (CommonTermsQuery (FieldName fieldName)
2823+ (QueryString query) cf lfo hfo msm
2824+ boost analyzer disableCoord) =
2825+ object [fieldName .= omitNulls base ]
2826+ where base = [ "query" .= query
2827+ , "cutoff_frequency" .= cf
2828+ , "low_freq_operator" .= lfo
2829+ , "minimum_should_match" .= msm
2830+ , "boost" .= boost
2831+ , "analyzer" .= analyzer
2832+ , "disable_coord" .= disableCoord
2833+ , "high_freq_operator" .= hfo ]
2834+
2835+instance FromJSON CommonTermsQuery where
2836+ parseJSON = withObject "CommonTermsQuery" parse
2837+ where parse = fieldTagged $ \fn o ->
2838+ CommonTermsQuery fn
2839+ <$> o .: "query"
2840+ <*> o .: "cutoff_frequency"
2841+ <*> o .: "low_freq_operator"
2842+ <*> o .: "high_freq_operator"
2843+ <*> o .:? "minimum_should_match"
2844+ <*> o .:? "boost"
2845+ <*> o .:? "analyzer"
2846+ <*> o .:? "disable_coord"
2847+
2848+instance ToJSON CommonMinimumMatch where
2849+ toJSON (CommonMinimumMatch mm) = toJSON mm
2850+ toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2851+ object [ "low_freq" .= lowF
2852+ , "high_freq" .= highF ]
2853+
2854+instance FromJSON CommonMinimumMatch where
2855+ parseJSON v = parseMinimum v
2856+ <|> parseMinimumHighLow v
2857+ where parseMinimum = fmap CommonMinimumMatch . parseJSON
2858+ parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2859+ MinimumMatchHighLow
2860+ <$> o .: "low_freq"
2861+ <*> o .: "high_freq")
2862+
2863+
2864+instance ToJSON BoostingQuery where
2865+ toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2866+ object [ "positive" .= bqPositiveQuery
2867+ , "negative" .= bqNegativeQuery
2868+ , "negative_boost" .= bqNegativeBoost ]
2869+
2870+instance FromJSON BoostingQuery where
2871+ parseJSON = withObject "BoostingQuery" parse
2872+ where parse o = BoostingQuery
2873+ <$> o .: "positive"
2874+ <*> o .: "negative"
2875+ <*> o .: "negative_boost"
2876+
2877+instance ToJSON BoolQuery where
2878+ toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2879+ omitNulls base
2880+ where base = [ "must" .= mustM
2881+ , "must_not" .= notM
2882+ , "should" .= shouldM
2883+ , "minimum_should_match" .= bqMin
2884+ , "boost" .= boost
2885+ , "disable_coord" .= disableCoord ]
2886+
2887+instance FromJSON BoolQuery where
2888+ parseJSON = withObject "BoolQuery" parse
2889+ where parse o = BoolQuery
2890+ <$> o .:? "must" .!= []
2891+ <*> o .:? "must_not" .!= []
2892+ <*> o .:? "should" .!= []
2893+ <*> o .:? "minimum_should_match"
2894+ <*> o .:? "boost"
2895+ <*> o .:? "disable_coord"
2896+
2897+instance ToJSON MatchQuery where
2898+ toJSON (MatchQuery (FieldName fieldName)
2899+ (QueryString mqQueryString) booleanOperator
2900+ zeroTermsQuery cutoffFrequency matchQueryType
2901+ analyzer maxExpansions lenient boost) =
2902+ object [ fieldName .= omitNulls base ]
2903+ where base = [ "query" .= mqQueryString
2904+ , "operator" .= booleanOperator
2905+ , "zero_terms_query" .= zeroTermsQuery
2906+ , "cutoff_frequency" .= cutoffFrequency
2907+ , "type" .= matchQueryType
2908+ , "analyzer" .= analyzer
2909+ , "max_expansions" .= maxExpansions
2910+ , "lenient" .= lenient
2911+ , "boost" .= boost ]
2912+
2913+instance FromJSON MatchQuery where
2914+ parseJSON = withObject "MatchQuery" parse
2915+ where parse = fieldTagged $ \fn o ->
2916+ MatchQuery fn
2917+ <$> o .: "query"
2918+ <*> o .: "operator"
2919+ <*> o .: "zero_terms_query"
2920+ <*> o .:? "cutoff_frequency"
2921+ <*> o .:? "type"
2922+ <*> o .:? "analyzer"
2923+ <*> o .:? "max_expansions"
2924+ <*> o .:? "lenient"
2925+ <*> o .:? "boost"
2926+
2927+instance ToJSON MultiMatchQuery where
2928+ toJSON (MultiMatchQuery fields (QueryString query) boolOp
2929+ ztQ tb mmqt cf analyzer maxEx lenient) =
2930+ object ["multi_match" .= omitNulls base]
2931+ where base = [ "fields" .= fmap toJSON fields
2932+ , "query" .= query
2933+ , "operator" .= boolOp
2934+ , "zero_terms_query" .= ztQ
2935+ , "tiebreaker" .= tb
2936+ , "type" .= mmqt
2937+ , "cutoff_frequency" .= cf
2938+ , "analyzer" .= analyzer
2939+ , "max_expansions" .= maxEx
2940+ , "lenient" .= lenient ]
2941+
2942+instance FromJSON MultiMatchQuery where
2943+ parseJSON = withObject "MultiMatchQuery" parse
2944+ where parse raw = do o <- raw .: "multi_match"
2945+ MultiMatchQuery
2946+ <$> o .:? "fields" .!= []
2947+ <*> o .: "query"
2948+ <*> o .: "operator"
2949+ <*> o .: "zero_terms_query"
2950+ <*> o .:? "tiebreaker"
2951+ <*> o .:? "type"
2952+ <*> o .:? "cutoff_frequency"
2953+ <*> o .:? "analyzer"
2954+ <*> o .:? "max_expansions"
2955+ <*> o .:? "lenient"
2956+
2957+instance ToJSON MultiMatchQueryType where
2958+ toJSON MultiMatchBestFields = "best_fields"
2959+ toJSON MultiMatchMostFields = "most_fields"
2960+ toJSON MultiMatchCrossFields = "cross_fields"
2961+ toJSON MultiMatchPhrase = "phrase"
2962+ toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2963+
2964+instance FromJSON MultiMatchQueryType where
2965+ parseJSON = withText "MultiMatchPhrasePrefix" parse
2966+ where parse "best_fields" = pure MultiMatchBestFields
2967+ parse "most_fields" = pure MultiMatchMostFields
2968+ parse "cross_fields" = pure MultiMatchCrossFields
2969+ parse "phrase" = pure MultiMatchPhrase
2970+ parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2971+ parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2972+
2973+instance ToJSON BooleanOperator where
2974+ toJSON And = String "and"
2975+ toJSON Or = String "or"
2976+
2977+instance FromJSON BooleanOperator where
2978+ parseJSON = withText "BooleanOperator" parse
2979+ where parse "and" = pure And
2980+ parse "or" = pure Or
2981+ parse o = fail ("Unexpected BooleanOperator: " <> show o)
2982+
2983+instance ToJSON ZeroTermsQuery where
2984+ toJSON ZeroTermsNone = String "none"
2985+ toJSON ZeroTermsAll = String "all"
2986+
2987+instance FromJSON ZeroTermsQuery where
2988+ parseJSON = withText "ZeroTermsQuery" parse
2989+ where parse "none" = pure ZeroTermsNone
2990+ parse "all" = pure ZeroTermsAll
2991+ parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2992+
2993+instance ToJSON MatchQueryType where
2994+ toJSON MatchPhrase = "phrase"
2995+ toJSON MatchPhrasePrefix = "phrase_prefix"
2996+
2997+instance FromJSON MatchQueryType where
2998+ parseJSON = withText "MatchQueryType" parse
2999+ where parse "phrase" = pure MatchPhrase
3000+ parse "phrase_prefix" = pure MatchPhrasePrefix
3001+ parse t = fail ("Unexpected MatchQueryType: " <> show t)
3002+
3003+instance FromJSON Status where
3004+ parseJSON (Object v) = Status <$>
3005+ v .:? "ok" <*>
3006+ (v .:? "status" .!= 200) <*>
3007+ v .: "name" <*>
3008+ v .: "version" <*>
3009+ v .: "tagline"
3010+ parseJSON _ = empty
3011+
3012+
3013+instance ToJSON IndexSettings where
3014+ toJSON (IndexSettings s r) = object ["settings" .=
3015+ object ["index" .=
3016+ object ["number_of_shards" .= s, "number_of_replicas" .= r]
3017+ ]
3018+ ]
3019+
3020+instance FromJSON IndexSettings where
3021+ parseJSON = withObject "IndexSettings" parse
3022+ where parse o = do s <- o .: "settings"
3023+ i <- s .: "index"
3024+ IndexSettings <$> i .: "number_of_shards"
3025+ <*> i .: "number_of_replicas"
3026+
3027+instance ToJSON UpdatableIndexSetting where
3028+ toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
3029+ toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
3030+ toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
3031+ toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
3032+ toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
3033+ toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
3034+ toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
3035+ toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
3036+ toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
3037+ toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
3038+ toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
3039+ toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
3040+ toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
3041+ toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
3042+ toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
3043+ toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
3044+ toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
3045+ toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
3046+ toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
3047+ toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
3048+ toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
3049+ toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
3050+ toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
3051+ toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
3052+ toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
3053+ toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
3054+ toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
3055+ toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
3056+
3057+instance FromJSON UpdatableIndexSetting where
3058+ parseJSON = withObject "UpdatableIndexSetting" parse
3059+ where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
3060+ <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
3061+ <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
3062+ <|> indexConcurrency `taggedAt` ["index", "concurrency"]
3063+ <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
3064+ <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
3065+ <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
3066+ <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
3067+ <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
3068+ <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
3069+ <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
3070+ <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
3071+ <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
3072+ <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
3073+ <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
3074+ <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
3075+ <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
3076+ <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
3077+ <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
3078+ <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
3079+ <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
3080+ <|> compoundFormat `taggedAt` ["index", "compound_format"]
3081+ <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3082+ <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3083+ <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3084+ <|> blocksRead `taggedAt` ["blocks", "read"]
3085+ <|> blocksWrite `taggedAt` ["blocks", "write"]
3086+ <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3087+ where taggedAt f ks = taggedAt' f (Object o) ks
3088+ taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3089+ taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3090+ taggedAt' f v' ks) v
3091+ numberOfReplicas = pure . NumberOfReplicas
3092+ autoExpandReplicas = pure . AutoExpandReplicas
3093+ refreshInterval = pure . RefreshInterval . ndtJSON
3094+ indexConcurrency = pure . IndexConcurrency
3095+ failOnMergeFailure = pure . FailOnMergeFailure
3096+ translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3097+ translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3098+ translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3099+ translogDisableFlush = pure . TranslogDisableFlush
3100+ cacheFilterMaxSize = pure . CacheFilterMaxSize
3101+ cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3102+ gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3103+ routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3104+ routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3105+ routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3106+ routingAllocationEnable = pure . RoutingAllocationEnable
3107+ routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3108+ recoveryInitialShards = pure . RecoveryInitialShards
3109+ gcDeletes = pure . GCDeletes . ndtJSON
3110+ ttlDisablePurge = pure . TTLDisablePurge
3111+ translogFSType = pure . TranslogFSType
3112+ compoundFormat = pure . IndexCompoundFormat
3113+ compoundOnFlush = pure . IndexCompoundOnFlush
3114+ warmerEnabled = pure . WarmerEnabled
3115+ blocksReadOnly = pure . BlocksReadOnly
3116+ blocksRead = pure . BlocksRead
3117+ blocksWrite = pure . BlocksWrite
3118+ blocksMetaData = pure . BlocksMetaData
3119+
3120+instance FromJSON IndexSettingsSummary where
3121+ parseJSON = withObject "IndexSettingsSummary" parse
3122+ where parse o = case HM.toList o of
3123+ [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3124+ <$> parseJSON v
3125+ <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3126+ _ -> fail "Expected single-key object with index name"
3127+ redundant (NumberOfReplicas _) = True
3128+ redundant _ = False
3129+
3130+-- | For some reason in several settings APIs, all leaf values get returned
3131+-- as strings. This function attepmts to recover from this for all
3132+-- non-recursive JSON types. If nothing can be done, the value is left alone.
3133+unStringlyTypeJSON :: Value -> Value
3134+unStringlyTypeJSON (String "true") = Bool True
3135+unStringlyTypeJSON (String "false") = Bool False
3136+unStringlyTypeJSON (String "null") = Null
3137+unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3138+ Just n -> Number n
3139+ Nothing -> v
3140+unStringlyTypeJSON v = v
3141+
3142+
3143+parseSettings :: Object -> Parser [UpdatableIndexSetting]
3144+parseSettings o = do
3145+ o' <- o .: "index"
3146+ -- slice the index object into singleton hashmaps and try to parse each
3147+ parses <- forM (HM.toList o') $ \(k, v) -> do
3148+ -- blocks are now nested into the "index" key, which is not how they're serialized
3149+ let atRoot = Object (HM.singleton k v)
3150+ let atIndex = Object (HM.singleton "index" atRoot)
3151+ optional (parseJSON atRoot <|> parseJSON atIndex)
3152+ return (catMaybes parses)
3153+
3154+oPath :: ToJSON a => NonEmpty Text -> a -> Value
3155+oPath (k :| []) v = object [k .= v]
3156+oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3157+
3158+attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3159+attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3160+ | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3161+
3162+parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3163+parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3164+ where parse o = case HM.toList o of
3165+ [] -> fail "Expected non-empty list of NodeAttrFilters"
3166+ x:xs -> DT.mapM (uncurry parse') (x :| xs)
3167+ parse' n = withText "Text" $ \t ->
3168+ case T.splitOn "," t of
3169+ fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3170+ [] -> fail "Expected non-empty list of filter values"
3171+
3172+instance ToJSON ReplicaBounds where
3173+ toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3174+ toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3175+ toJSON ReplicasUnbounded = Bool False
3176+
3177+instance FromJSON ReplicaBounds where
3178+ parseJSON v = withText "ReplicaBounds" parseText v
3179+ <|> withBool "ReplicaBounds" parseBool v
3180+ where parseText t = case T.splitOn "-" t of
3181+ [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3182+ [a, b] -> ReplicasBounded <$> parseReadText a
3183+ <*> parseReadText b
3184+ _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3185+ parseBool False = pure ReplicasUnbounded
3186+ parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3187+
3188+instance ToJSON AllocationPolicy where
3189+ toJSON AllocAll = String "all"
3190+ toJSON AllocPrimaries = String "primaries"
3191+ toJSON AllocNewPrimaries = String "new_primaries"
3192+ toJSON AllocNone = String "none"
3193+
3194+instance FromJSON AllocationPolicy where
3195+ parseJSON = withText "AllocationPolicy" parse
3196+ where parse "all" = pure AllocAll
3197+ parse "primaries" = pure AllocPrimaries
3198+ parse "new_primaries" = pure AllocNewPrimaries
3199+ parse "none" = pure AllocNone
3200+ parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3201+
3202+instance ToJSON InitialShardCount where
3203+ toJSON QuorumShards = String "quorum"
3204+ toJSON QuorumMinus1Shards = String "quorum-1"
3205+ toJSON FullShards = String "full"
3206+ toJSON FullMinus1Shards = String "full-1"
3207+ toJSON (ExplicitShards x) = toJSON x
3208+
3209+instance FromJSON InitialShardCount where
3210+ parseJSON v = withText "InitialShardCount" parseText v
3211+ <|> ExplicitShards <$> parseJSON v
3212+ where parseText "quorum" = pure QuorumShards
3213+ parseText "quorum-1" = pure QuorumMinus1Shards
3214+ parseText "full" = pure FullShards
3215+ parseText "full-1" = pure FullMinus1Shards
3216+ parseText _ = mzero
3217+
3218+instance ToJSON FSType where
3219+ toJSON FSSimple = "simple"
3220+ toJSON FSBuffered = "buffered"
3221+
3222+instance FromJSON FSType where
3223+ parseJSON = withText "FSType" parse
3224+ where parse "simple" = pure FSSimple
3225+ parse "buffered" = pure FSBuffered
3226+ parse t = fail ("Invalid FSType: " <> show t)
3227+
3228+instance ToJSON CompoundFormat where
3229+ toJSON (CompoundFileFormat x) = Bool x
3230+ toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3231+
3232+instance FromJSON CompoundFormat where
3233+ parseJSON v = CompoundFileFormat <$> parseJSON v
3234+ <|> MergeSegmentVsTotalIndex <$> parseJSON v
3235+
3236+instance ToJSON NominalDiffTimeJSON where
3237+ toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3238+
3239+instance FromJSON NominalDiffTimeJSON where
3240+ parseJSON = withText "NominalDiffTime" parse
3241+ where parse t = case T.takeEnd 1 t of
3242+ "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3243+ _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3244+
3245+instance ToJSON IndexTemplate where
3246+ toJSON (IndexTemplate p s m) = merge
3247+ (object [ "template" .= p
3248+ , "mappings" .= foldl' merge (object []) m
3249+ ])
3250+ (toJSON s)
3251+ where
3252+ merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3253+ merge o Null = o
3254+ merge _ _ = undefined
3255+
3256+instance (FromJSON a) => FromJSON (EsResult a) where
3257+ parseJSON jsonVal@(Object v) = do
3258+ found <- v .:? "found" .!= False
3259+ fr <- if found
3260+ then parseJSON jsonVal
3261+ else return Nothing
3262+ EsResult <$> v .: "_index" <*>
3263+ v .: "_type" <*>
3264+ v .: "_id" <*>
3265+ pure fr
3266+ parseJSON _ = empty
3267+
3268+instance (FromJSON a) => FromJSON (EsResultFound a) where
3269+ parseJSON (Object v) = EsResultFound <$>
3270+ v .: "_version" <*>
3271+ v .: "_source"
3272+ parseJSON _ = empty
3273+
3274+instance FromJSON EsError where
3275+ parseJSON (Object v) = EsError <$>
3276+ v .: "status" <*>
3277+ (v .: "error" <|> (v .: "error" >>= (.: "reason")))
3278+ parseJSON _ = empty
3279+
3280+instance FromJSON IndexAliasesSummary where
3281+ parseJSON = withObject "IndexAliasesSummary" parse
3282+ where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3283+ go ixn = withObject "index aliases" $ \ia -> do
3284+ aliases <- ia .:? "aliases" .!= mempty
3285+ forM (HM.toList aliases) $ \(aName, v) -> do
3286+ let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3287+ IndexAliasSummary indexAlias <$> parseJSON v
3288+
3289+
3290+instance ToJSON IndexAliasAction where
3291+ toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3292+ where Object iaObj = toJSON ia
3293+ Object optsObj = toJSON opts
3294+ toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3295+ where Object iaObj = toJSON ia
3296+
3297+instance ToJSON IndexAlias where
3298+ toJSON IndexAlias {..} = object ["index" .= srcIndex
3299+ , "alias" .= indexAlias
3300+ ]
3301+
3302+instance ToJSON IndexAliasCreate where
3303+ toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3304+ where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3305+ Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3306+
3307+instance ToJSON AliasRouting where
3308+ toJSON (AllAliasRouting v) = object ["routing" .= v]
3309+ toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3310+ where prs = [("search_routing" .=) <$> srch
3311+ ,("index_routing" .=) <$> idx]
3312+
3313+instance FromJSON AliasRouting where
3314+ parseJSON = withObject "AliasRouting" parse
3315+ where parse o = parseAll o <|> parseGranular o
3316+ parseAll o = AllAliasRouting <$> o .: "routing"
3317+ parseGranular o = do
3318+ sr <- o .:? "search_routing"
3319+ ir <- o .:? "index_routing"
3320+ if isNothing sr && isNothing ir
3321+ then fail "Both search_routing and index_routing can't be blank"
3322+ else return (GranularAliasRouting sr ir)
3323+
3324+instance FromJSON IndexAliasCreate where
3325+ parseJSON v = withObject "IndexAliasCreate" parse v
3326+ where parse o = IndexAliasCreate <$> optional (parseJSON v)
3327+ <*> o .:? "filter"
3328+
3329+instance ToJSON SearchAliasRouting where
3330+ toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3331+
3332+instance FromJSON SearchAliasRouting where
3333+ parseJSON = withText "SearchAliasRouting" parse
3334+ where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3335+
3336+instance ToJSON Search where
3337+ toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3338+ omitNulls [ "query" .= query
3339+ , "filter" .= sFilter
3340+ , "sort" .= sort
3341+ , "aggregations" .= searchAggs
3342+ , "highlight" .= highlight
3343+ , "from" .= sFrom
3344+ , "size" .= sSize
3345+ , "track_scores" .= sTrackSortScores
3346+ , "fields" .= sFields
3347+ , "_source" .= sSource]
3348+
3349+
3350+instance ToJSON Source where
3351+ toJSON NoSource = toJSON False
3352+ toJSON (SourcePatterns patterns) = toJSON patterns
3353+ toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3354+
3355+instance ToJSON PatternOrPatterns where
3356+ toJSON (PopPattern pattern) = toJSON pattern
3357+ toJSON (PopPatterns patterns) = toJSON patterns
3358+
3359+instance ToJSON Include where
3360+ toJSON (Include patterns) = toJSON patterns
3361+
3362+instance ToJSON Exclude where
3363+ toJSON (Exclude patterns) = toJSON patterns
3364+
3365+instance ToJSON Pattern where
3366+ toJSON (Pattern pattern) = toJSON pattern
3367+
3368+
3369+instance ToJSON FieldHighlight where
3370+ toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3371+ object [ fName .= fSettings ]
3372+ toJSON (FieldHighlight (FieldName fName) Nothing) =
3373+ object [ fName .= emptyObject ]
3374+
3375+instance ToJSON Highlights where
3376+ toJSON (Highlights global fields) =
3377+ omitNulls (("fields" .= fields)
3378+ : highlightSettingsPairs global)
3379+
3380+instance ToJSON HighlightSettings where
3381+ toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3382+
3383+highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3384+highlightSettingsPairs Nothing = []
3385+highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3386+highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3387+highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3388+
3389+
3390+plainHighPairs :: Maybe PlainHighlight -> [Pair]
3391+plainHighPairs Nothing = []
3392+plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3393+ [ "type" .= String "plain"]
3394+ ++ commonHighlightPairs plCom
3395+ ++ nonPostingsToPairs plNonPost
3396+
3397+postHighPairs :: Maybe PostingsHighlight -> [Pair]
3398+postHighPairs Nothing = []
3399+postHighPairs (Just (PostingsHighlight pCom)) =
3400+ ("type" .= String "postings")
3401+ : commonHighlightPairs pCom
3402+
3403+fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3404+fastVectorHighPairs Nothing = []
3405+fastVectorHighPairs (Just
3406+ (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3407+ fvBoundMaxScan fvFragOff fvMatchedFields
3408+ fvPhraseLim)) =
3409+ [ "type" .= String "fvh"
3410+ , "boundary_chars" .= fvBoundChars
3411+ , "boundary_max_scan" .= fvBoundMaxScan
3412+ , "fragment_offset" .= fvFragOff
3413+ , "matched_fields" .= fvMatchedFields
3414+ , "phraseLimit" .= fvPhraseLim]
3415+ ++ commonHighlightPairs fvCom
3416+ ++ nonPostingsToPairs fvNonPostSettings
3417+
3418+deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3419+deleteSeveral ks hm = foldr HM.delete hm ks
3420+
3421+commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3422+commonHighlightPairs Nothing = []
3423+commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3424+ chNoMatchSize chHighlightQuery
3425+ chRequireFieldMatch)) =
3426+ [ "order" .= chScore
3427+ , "force_source" .= chForceSource
3428+ , "encoder" .= chEncoder
3429+ , "no_match_size" .= chNoMatchSize
3430+ , "highlight_query" .= chHighlightQuery
3431+ , "require_fieldMatch" .= chRequireFieldMatch]
3432+ ++ highlightTagToPairs chTag
3433+
3434+
3435+nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3436+nonPostingsToPairs Nothing = []
3437+nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3438+ [ "fragment_size" .= npFragSize
3439+ , "number_of_fragments" .= npNumOfFrags]
3440+
3441+parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3442+parseNEJSON [] = fail "Expected non-empty list"
3443+parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3444+
3445+
3446+instance ToJSON HighlightEncoder where
3447+ toJSON DefaultEncoder = String "default"
3448+ toJSON HTMLEncoder = String "html"
3449+
3450+highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3451+highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3452+highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3453+ , "post_tags" .= post]
3454+highlightTagToPairs Nothing = []
3455+
3456+instance ToJSON SortSpec where
3457+ toJSON (DefaultSortSpec
3458+ (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3459+ dsSortMode dsMissingSort dsNestedFilter)) =
3460+ object [dsSortFieldName .= omitNulls base] where
3461+ base = [ "order" .= dsSortOrder
3462+ , "ignore_unmapped" .= dsIgnoreUnmapped
3463+ , "mode" .= dsSortMode
3464+ , "missing" .= dsMissingSort
3465+ , "nested_filter" .= dsNestedFilter ]
3466+
3467+ toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3468+ object [ "unit" .= units
3469+ , field .= gdsLatLon
3470+ , "order" .= gdsSortOrder ]
3471+
3472+
3473+instance ToJSON SortOrder where
3474+ toJSON Ascending = String "asc"
3475+ toJSON Descending = String "desc"
3476+
3477+
3478+instance ToJSON SortMode where
3479+ toJSON SortMin = String "min"
3480+ toJSON SortMax = String "max"
3481+ toJSON SortSum = String "sum"
3482+ toJSON SortAvg = String "avg"
3483+
3484+
3485+instance ToJSON Missing where
3486+ toJSON LastMissing = String "_last"
3487+ toJSON FirstMissing = String "_first"
3488+ toJSON (CustomMissing txt) = String txt
3489+
3490+
3491+instance ToJSON ScoreType where
3492+ toJSON ScoreTypeMax = "max"
3493+ toJSON ScoreTypeAvg = "avg"
3494+ toJSON ScoreTypeSum = "sum"
3495+ toJSON ScoreTypeNone = "none"
3496+
3497+instance FromJSON ScoreType where
3498+ parseJSON = withText "ScoreType" parse
3499+ where parse "max" = pure ScoreTypeMax
3500+ parse "avg" = pure ScoreTypeAvg
3501+ parse "sum" = pure ScoreTypeSum
3502+ parse "none" = pure ScoreTypeNone
3503+ parse t = fail ("Unexpected ScoreType: " <> show t)
3504+
3505+instance ToJSON Distance where
3506+ toJSON (Distance dCoefficient dUnit) =
3507+ String boltedTogether where
3508+ coefText = showText dCoefficient
3509+ (String unitText) = toJSON dUnit
3510+ boltedTogether = mappend coefText unitText
3511+
3512+instance FromJSON Distance where
3513+ parseJSON = withText "Distance" parse
3514+ where parse t = Distance <$> parseCoeff nT
3515+ <*> parseJSON (String unitT)
3516+ where (nT, unitT) = T.span validForNumber t
3517+ -- may be a better way to do this
3518+ validForNumber '-' = True
3519+ validForNumber '.' = True
3520+ validForNumber 'e' = True
3521+ validForNumber c = isNumber c
3522+ parseCoeff "" = fail "Empty string cannot be parsed as number"
3523+ parseCoeff s = return (read (T.unpack s))
3524+
3525+instance ToJSON DistanceUnit where
3526+ toJSON Miles = String "mi"
3527+ toJSON Yards = String "yd"
3528+ toJSON Feet = String "ft"
3529+ toJSON Inches = String "in"
3530+ toJSON Kilometers = String "km"
3531+ toJSON Meters = String "m"
3532+ toJSON Centimeters = String "cm"
3533+ toJSON Millimeters = String "mm"
3534+ toJSON NauticalMiles = String "nmi"
3535+
3536+
3537+instance FromJSON DistanceUnit where
3538+ parseJSON = withText "DistanceUnit" parse
3539+ where parse "mi" = pure Miles
3540+ parse "yd" = pure Yards
3541+ parse "ft" = pure Feet
3542+ parse "in" = pure Inches
3543+ parse "km" = pure Kilometers
3544+ parse "m" = pure Meters
3545+ parse "cm" = pure Centimeters
3546+ parse "mm" = pure Millimeters
3547+ parse "nmi" = pure NauticalMiles
3548+ parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3549+
3550+instance ToJSON DistanceType where
3551+ toJSON Arc = String "arc"
3552+ toJSON SloppyArc = String "sloppy_arc"
3553+ toJSON Plane = String "plane"
3554+
3555+instance FromJSON DistanceType where
3556+ parseJSON = withText "DistanceType" parse
3557+ where parse "arc" = pure Arc
3558+ parse "sloppy_arc" = pure SloppyArc
3559+ parse "plane" = pure Plane
3560+ parse t = fail ("Unrecognized DistanceType: " <> show t)
3561+
3562+
3563+instance ToJSON OptimizeBbox where
3564+ toJSON NoOptimizeBbox = String "none"
3565+ toJSON (OptimizeGeoFilterType gft) = toJSON gft
3566+
3567+instance FromJSON OptimizeBbox where
3568+ parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3569+ <|> parseOptimize v
3570+ where parseNoOptimize "none" = pure NoOptimizeBbox
3571+ parseNoOptimize _ = mzero
3572+ parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3573+
3574+instance ToJSON GeoBoundingBoxConstraint where
3575+ toJSON (GeoBoundingBoxConstraint
3576+ (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3577+ object [gbbcGeoBBField .= gbbcConstraintBox
3578+ , "_cache" .= cache
3579+ , "type" .= type']
3580+
3581+instance FromJSON GeoBoundingBoxConstraint where
3582+ parseJSON = withObject "GeoBoundingBoxConstraint" parse
3583+ where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3584+ [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3585+ <$> parseJSON v
3586+ <*> o .:? "_cache" .!= defaultCache
3587+ <*> o .: "type"
3588+ _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3589+
3590+instance ToJSON GeoFilterType where
3591+ toJSON GeoFilterMemory = String "memory"
3592+ toJSON GeoFilterIndexed = String "indexed"
3593+
3594+instance FromJSON GeoFilterType where
3595+ parseJSON = withText "GeoFilterType" parse
3596+ where parse "memory" = pure GeoFilterMemory
3597+ parse "indexed" = pure GeoFilterIndexed
3598+ parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3599+
3600+instance ToJSON GeoBoundingBox where
3601+ toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3602+ object ["top_left" .= gbbTopLeft
3603+ , "bottom_right" .= gbbBottomRight]
3604+
3605+instance FromJSON GeoBoundingBox where
3606+ parseJSON = withObject "GeoBoundingBox" parse
3607+ where parse o = GeoBoundingBox
3608+ <$> o .: "top_left"
3609+ <*> o .: "bottom_right"
3610+
3611+instance ToJSON LatLon where
3612+ toJSON (LatLon lLat lLon) =
3613+ object ["lat" .= lLat
3614+ , "lon" .= lLon]
3615+
3616+instance FromJSON LatLon where
3617+ parseJSON = withObject "LatLon" parse
3618+ where parse o = LatLon <$> o .: "lat"
3619+ <*> o .: "lon"
3620+
3621+-- index for smaller ranges, fielddata for longer ranges
3622+instance ToJSON RangeExecution where
3623+ toJSON RangeExecutionIndex = "index"
3624+ toJSON RangeExecutionFielddata = "fielddata"
3625+
3626+
3627+instance FromJSON RangeExecution where
3628+ parseJSON = withText "RangeExecution" parse
3629+ where parse "index" = pure RangeExecutionIndex
3630+ parse "fielddata" = pure RangeExecutionFielddata
3631+ parse t = error ("Unrecognized RangeExecution " <> show t)
3632+
3633+instance ToJSON RegexpFlags where
3634+ toJSON AllRegexpFlags = String "ALL"
3635+ toJSON NoRegexpFlags = String "NONE"
3636+ toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3637+ where flagStrs = map flagStr . nub $ h:fs
3638+ flagStr AnyString = "ANYSTRING"
3639+ flagStr Automaton = "AUTOMATON"
3640+ flagStr Complement = "COMPLEMENT"
3641+ flagStr Empty = "EMPTY"
3642+ flagStr Intersection = "INTERSECTION"
3643+ flagStr Interval = "INTERVAL"
3644+
3645+instance FromJSON RegexpFlags where
3646+ parseJSON = withText "RegexpFlags" parse
3647+ where parse "ALL" = pure AllRegexpFlags
3648+ parse "NONE" = pure NoRegexpFlags
3649+ parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3650+
3651+instance FromJSON RegexpFlag where
3652+ parseJSON = withText "RegexpFlag" parse
3653+ where parse "ANYSTRING" = pure AnyString
3654+ parse "AUTOMATON" = pure Automaton
3655+ parse "COMPLEMENT" = pure Complement
3656+ parse "EMPTY" = pure Empty
3657+ parse "INTERSECTION" = pure Intersection
3658+ parse "INTERVAL" = pure Interval
3659+ parse f = fail ("Unknown RegexpFlag: " <> show f)
3660+
3661+instance ToJSON Term where
3662+ toJSON (Term field value) = object ["term" .= object
3663+ [field .= value]]
3664+
3665+instance FromJSON Term where
3666+ parseJSON = withObject "Term" parse
3667+ where parse o = do termObj <- o .: "term"
3668+ case HM.toList termObj of
3669+ [(fn, v)] -> Term fn <$> parseJSON v
3670+ _ -> fail "Expected object with 1 field-named key"
3671+
3672+instance ToJSON BoolMatch where
3673+ toJSON (MustMatch term cache) = object ["must" .= term,
3674+ "_cache" .= cache]
3675+ toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3676+ "_cache" .= cache]
3677+ toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3678+ "_cache" .= cache]
3679+
3680+instance FromJSON BoolMatch where
3681+ parseJSON = withObject "BoolMatch" parse
3682+ where parse o = mustMatch `taggedWith` "must"
3683+ <|> mustNotMatch `taggedWith` "must_not"
3684+ <|> shouldMatch `taggedWith` "should"
3685+ where taggedWith parser k = parser =<< o .: k
3686+ mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3687+ mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3688+ shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3689+
3690+instance (FromJSON a) => FromJSON (SearchResult a) where
3691+ parseJSON (Object v) = SearchResult <$>
3692+ v .: "took" <*>
3693+ v .: "timed_out" <*>
3694+ v .: "_shards" <*>
5343695 v .: "hits" <*>
5353696 v .:? "aggregations" <*>
536− v .:? "_scroll_id" <*>
537− v .:? "suggest"
3697+ v .:? "_scroll_id"
3698+ parseJSON _ = empty
3699+
3700+instance (FromJSON a) => FromJSON (SearchHits a) where
3701+ parseJSON (Object v) = SearchHits <$>
3702+ v .: "total" <*>
3703+ v .: "max_score" <*>
3704+ v .: "hits"
3705+ parseJSON _ = empty
3706+
3707+instance (FromJSON a) => FromJSON (Hit a) where
3708+ parseJSON (Object v) = Hit <$>
3709+ v .: "_index" <*>
3710+ v .: "_type" <*>
3711+ v .: "_id" <*>
3712+ v .: "_score" <*>
3713+ v .:? "_source" <*>
3714+ v .:? "highlight"
5383715 parseJSON _ = empty
5393716
540−newtype ScrollId =
541− ScrollId Text
542− deriving (Eq, Show, Ord, ToJSON, FromJSON)
3717+instance FromJSON ShardResult where
3718+ parseJSON (Object v) = ShardResult <$>
3719+ v .: "total" <*>
3720+ v .: "successful" <*>
3721+ v .: "failed"
3722+ parseJSON _ = empty
3723+
3724+
3725+instance FromJSON DocVersion where
3726+ parseJSON v = do
3727+ i <- parseJSON v
3728+ maybe (fail "DocVersion out of range") return $ mkDocVersion i
3729+
3730+-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3731+instance FromJSON ReplicaCount where
3732+ parseJSON v = parseAsInt v
3733+ <|> parseAsString v
3734+ where parseAsInt = fmap ReplicaCount . parseJSON
3735+ parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3736+
3737+instance FromJSON ShardCount where
3738+ parseJSON v = parseAsInt v
3739+ <|> parseAsString v
3740+ where parseAsInt = fmap ShardCount . parseJSON
3741+ parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3742+
3743+instance Bounded DocVersion where
3744+ minBound = DocVersion 1
3745+ maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3746+
3747+instance Enum DocVersion where
3748+ succ x
3749+ | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3750+ | otherwise = succError "DocVersion"
3751+ pred x
3752+ | x /= minBound = DocVersion (pred $ docVersionNumber x)
3753+ | otherwise = predError "DocVersion"
3754+ toEnum i =
3755+ fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3756+ fromEnum = docVersionNumber
3757+ enumFrom = boundedEnumFrom
3758+ enumFromThen = boundedEnumFromThen
3759+
3760+-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3761+newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3762+
3763+-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3764+newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3765+
3766+
3767+data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3768+ | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3769+
3770+
3771+-- | Either specifies an exact repo name or one with globs in it,
3772+-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3773+data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3774+ | RepoPattern Text
3775+ deriving (Eq, Generic, Show, Typeable)
3776+
3777+-- | The unique name of a snapshot repository.
3778+newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3779+ deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3780+
3781+
3782+-- | A generic representation of a snapshot repo. This is what gets
3783+-- sent to and parsed from the server. For repo types enabled by
3784+-- plugins that aren't exported by this library, consider making a
3785+-- custom type which implements 'SnapshotRepo'. If it is a common repo
3786+-- type, consider submitting a pull request to have it included in the
3787+-- library proper
3788+data GenericSnapshotRepo = GenericSnapshotRepo {
3789+ gSnapshotRepoName :: SnapshotRepoName
3790+ , gSnapshotRepoType :: SnapshotRepoType
3791+ , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3792+ } deriving (Eq, Generic, Show, Typeable)
3793+
3794+
3795+instance SnapshotRepo GenericSnapshotRepo where
3796+ toGSnapshotRepo = id
3797+ fromGSnapshotRepo = Right
3798+
3799+
3800+newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3801+ deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3802+
3803+
3804+-- | Opaque representation of snapshot repo settings. Instances of
3805+-- 'SnapshotRepo' will produce this.
3806+newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3807+ deriving (Eq, Generic, Show, Typeable, ToJSON)
3808+
3809+
3810+ -- Regardless of whether you send strongly typed json, my version of
3811+ -- ES sends back stringly typed json in the settings, e.g. booleans
3812+ -- as strings, so we'll try to convert them.
3813+instance FromJSON GenericSnapshotRepoSettings where
3814+ parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3815+
3816+-- | The result of running 'verifySnapshotRepo'.
3817+newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3818+ deriving (Eq, Generic, Show, Typeable)
3819+
3820+
3821+instance FromJSON SnapshotVerification where
3822+ parseJSON = withObject "SnapshotVerification" parse
3823+ where
3824+ parse o = do
3825+ o2 <- o .: "nodes"
3826+ SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3827+ parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3828+ SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3829+
3830+
3831+-- | A node that has verified a snapshot
3832+data SnapshotNodeVerification = SnapshotNodeVerification {
3833+ snvFullId :: FullNodeId
3834+ , snvNodeName :: NodeName
3835+ } deriving (Eq, Generic, Show, Typeable)
3836+
3837+
3838+-- | Unique, automatically-generated name assigned to nodes that are
3839+-- usually returned in node-oriented APIs.
3840+newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3841+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3842+
3843+
3844+-- | A human-readable node name that is supplied by the user in the
3845+-- node config or automatically generated by ElasticSearch.
3846+newtype NodeName = NodeName { nodeName :: Text }
3847+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3848+
3849+newtype ClusterName = ClusterName { clusterName :: Text }
3850+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3851+
3852+data NodesInfo = NodesInfo {
3853+ nodesInfo :: [NodeInfo]
3854+ , nodesClusterName :: ClusterName
3855+ } deriving (Eq, Show, Generic, Typeable)
3856+
3857+-- | A quirky address format used throughout ElasticSearch. An example
3858+-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
3859+-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
3860+newtype EsAddress = EsAddress { esAddress :: Text }
3861+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3862+
3863+-- | Typically a 7 character hex string.
3864+newtype BuildHash = BuildHash { buildHash :: Text }
3865+ deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
3866+
3867+newtype PluginName = PluginName { pluginName :: Text }
3868+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3869+
3870+data NodeInfo = NodeInfo {
3871+ nodeInfoHTTPAddress :: EsAddress
3872+ , nodeInfoBuild :: BuildHash
3873+ , nodeInfoESVersion :: VersionNumber
3874+ , nodeInfoIP :: Server
3875+ , nodeInfoHost :: Server
3876+ , nodeInfoTransportAddress :: EsAddress
3877+ , nodeInfoName :: NodeName
3878+ , nodeInfoFullId :: FullNodeId
3879+ , nodeInfoPlugins :: [NodePluginInfo]
3880+ , nodeInfoHTTP :: NodeHTTPInfo
3881+ , nodeInfoTransport :: NodeTransportInfo
3882+ , nodeInfoNetwork :: NodeNetworkInfo
3883+ , nodeInfoThreadPool :: NodeThreadPoolsInfo
3884+ , nodeInfoJVM :: NodeJVMInfo
3885+ , nodeInfoProcess :: NodeProcessInfo
3886+ , nodeInfoOS :: NodeOSInfo
3887+ , nodeInfoSettings :: Object
3888+ -- ^ The members of the settings objects are not consistent,
3889+ -- dependent on plugins, etc.
3890+ } deriving (Eq, Show, Generic, Typeable)
3891+
3892+data NodePluginInfo = NodePluginInfo {
3893+ nodePluginSite :: Bool
3894+ -- ^ Is this a site plugin?
3895+ , nodePluginJVM :: Bool
3896+ -- ^ Is this plugin running on the JVM
3897+ , nodePluginDescription :: Text
3898+ , nodePluginVersion :: VersionNumber
3899+ , nodePluginName :: PluginName
3900+ } deriving (Eq, Show, Generic, Typeable)
3901+
3902+data NodeHTTPInfo = NodeHTTPInfo {
3903+ nodeHTTPMaxContentLength :: Bytes
3904+ , nodeHTTPTransportAddress :: BoundTransportAddress
3905+ } deriving (Eq, Show, Generic, Typeable)
3906+
3907+data NodeTransportInfo = NodeTransportInfo {
3908+ nodeTransportProfiles :: [BoundTransportAddress]
3909+ , nodeTransportAddress :: BoundTransportAddress
3910+ } deriving (Eq, Show, Generic, Typeable)
3911+
3912+data BoundTransportAddress = BoundTransportAddress {
3913+ publishAddress :: EsAddress
3914+ , boundAddress :: EsAddress
3915+ } deriving (Eq, Show, Generic, Typeable)
3916+
3917+data NodeNetworkInfo = NodeNetworkInfo {
3918+ nodeNetworkPrimaryInterface :: NodeNetworkInterface
3919+ , nodeNetworkRefreshInterval :: NominalDiffTime
3920+ } deriving (Eq, Show, Generic, Typeable)
3921+
3922+newtype MacAddress = MacAddress { macAddress :: Text }
3923+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3924+
3925+newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
3926+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3927+
3928+data NodeNetworkInterface = NodeNetworkInterface {
3929+ nodeNetIfaceMacAddress :: MacAddress
3930+ , nodeNetIfaceName :: NetworkInterfaceName
3931+ , nodeNetIfaceAddress :: Server
3932+ } deriving (Eq, Show, Generic, Typeable)
3933+
3934+data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
3935+ nodeThreadPoolsRefresh :: NodeThreadPoolInfo
3936+ , nodeThreadPoolsManagement :: NodeThreadPoolInfo
3937+ , nodeThreadPoolsPercolate :: NodeThreadPoolInfo
3938+ , nodeThreadPoolsListener :: Maybe NodeThreadPoolInfo
3939+ , nodeThreadPoolsFetchShardStarted :: Maybe NodeThreadPoolInfo
3940+ , nodeThreadPoolsSearch :: NodeThreadPoolInfo
3941+ , nodeThreadPoolsFlush :: NodeThreadPoolInfo
3942+ , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
3943+ , nodeThreadPoolsOptimize :: NodeThreadPoolInfo
3944+ , nodeThreadPoolsBulk :: NodeThreadPoolInfo
3945+ , nodeThreadPoolsSuggest :: NodeThreadPoolInfo
3946+ , nodeThreadPoolsMerge :: NodeThreadPoolInfo
3947+ , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
3948+ , nodeThreadPoolsGet :: NodeThreadPoolInfo
3949+ , nodeThreadPoolsFetchShardStore :: Maybe NodeThreadPoolInfo
3950+ , nodeThreadPoolsIndex :: NodeThreadPoolInfo
3951+ , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
3952+ } deriving (Eq, Show, Generic, Typeable)
3953+
3954+data NodeThreadPoolInfo = NodeThreadPoolInfo {
3955+ nodeThreadPoolQueueSize :: ThreadPoolSize
3956+ , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
3957+ , nodeThreadPoolMin :: Maybe Int
3958+ , nodeThreadPoolMax :: Maybe Int
3959+ , nodeThreadPoolType :: ThreadPoolType
3960+ } deriving (Eq, Show, Generic, Typeable)
3961+
3962+data ThreadPoolSize = ThreadPoolBounded Int
3963+ | ThreadPoolUnbounded
3964+ deriving (Eq, Show, Generic, Typeable)
3965+
3966+data ThreadPoolType = ThreadPoolScaling
3967+ | ThreadPoolFixed
3968+ | ThreadPoolCached
3969+ deriving (Eq, Show, Generic, Typeable)
3970+
3971+data NodeJVMInfo = NodeJVMInfo {
3972+ nodeJVMInfoMemoryPools :: [JVMMemoryPool]
3973+ , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
3974+ , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
3975+ , nodeJVMInfoStartTime :: UTCTime
3976+ , nodeJVMInfoVMVendor :: Text
3977+ , nodeJVMVMVersion :: VersionNumber
3978+ -- ^ JVM doesn't seme to follow normal version conventions
3979+ , nodeJVMVMName :: Text
3980+ , nodeJVMVersion :: VersionNumber
3981+ , nodeJVMPID :: PID
3982+ } deriving (Eq, Show, Generic, Typeable)
3983+
3984+-- | Handles quirks in the way JVM versions are rendered (1.7.0_101 -> 1.7.0.101)
3985+newtype JVMVersion = JVMVersion { unJVMVersion :: VersionNumber }
3986+
3987+data JVMMemoryInfo = JVMMemoryInfo {
3988+ jvmMemoryInfoDirectMax :: Bytes
3989+ , jvmMemoryInfoNonHeapMax :: Bytes
3990+ , jvmMemoryInfoNonHeapInit :: Bytes
3991+ , jvmMemoryInfoHeapMax :: Bytes
3992+ , jvmMemoryInfoHeapInit :: Bytes
3993+ } deriving (Eq, Show, Generic, Typeable)
3994+
3995+newtype JVMMemoryPool = JVMMemoryPool {
3996+ jvmMemoryPool :: Text
3997+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
3998+
3999+newtype JVMGCCollector = JVMGCCollector {
4000+ jvmGCCollector :: Text
4001+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4002+
4003+newtype PID = PID {
4004+ pid :: Int
4005+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4006+
4007+data NodeOSInfo = NodeOSInfo {
4008+ nodeOSSwap :: Bytes
4009+ , nodeOSMem :: Bytes
4010+ , nodeOSCPUInfo :: CPUInfo
4011+ , nodeOSAvailableProcessors :: Int
4012+ , nodeOSRefreshInterval :: NominalDiffTime
4013+ } deriving (Eq, Show, Generic, Typeable)
4014+
4015+data CPUInfo = CPUInfo {
4016+ cpuCacheSize :: Bytes
4017+ , cpuCoresPerSocket :: Int
4018+ , cpuTotalSockets :: Int
4019+ , cpuTotalCores :: Int
4020+ , cpuMHZ :: Int
4021+ , cpuModel :: Text
4022+ , cpuVendor :: Text
4023+ } deriving (Eq, Show, Generic, Typeable)
4024+
4025+data NodeProcessInfo = NodeProcessInfo {
4026+ nodeProcessMLockAll :: Bool
4027+ -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
4028+ , nodeProcessMaxFileDescriptors :: Int
4029+ , nodeProcessId :: PID
4030+ , nodeProcessRefreshInterval :: NominalDiffTime
4031+ } deriving (Eq, Show, Generic, Typeable)
4032+
4033+data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
4034+ repoUpdateVerify :: Bool
4035+ -- ^ After creation/update, synchronously check that nodes can
4036+ -- write to this repo. Defaults to True. You may use False if you
4037+ -- need a faster response and plan on verifying manually later
4038+ -- with 'verifySnapshotRepo'.
4039+ } deriving (Eq, Show, Generic, Typeable)
4040+
4041+
4042+-- | Reasonable defaults for repo creation/update
4043+--
4044+-- * repoUpdateVerify True
4045+defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4046+defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4047+
4048+
4049+-- | A filesystem-based snapshot repo that ships with
4050+-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4051+-- used with 'updateSnapshotRepo'
4052+data FsSnapshotRepo = FsSnapshotRepo {
4053+ fsrName :: SnapshotRepoName
4054+ , fsrLocation :: FilePath
4055+ , fsrCompressMetadata :: Bool
4056+ , fsrChunkSize :: Maybe Bytes
4057+ -- ^ Size by which to split large files during snapshotting.
4058+ , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4059+ -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4060+ , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4061+ -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4062+ } deriving (Eq, Generic, Show, Typeable)
4063+
4064+
4065+instance SnapshotRepo FsSnapshotRepo where
4066+ toGSnapshotRepo FsSnapshotRepo {..} =
4067+ GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4068+ where
4069+ Object settings = object $ [ "location" .= fsrLocation
4070+ , "compress" .= fsrCompressMetadata
4071+ ] ++ optionalPairs
4072+ optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4073+ , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4074+ , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4075+ ]
4076+ fromGSnapshotRepo GenericSnapshotRepo {..}
4077+ | gSnapshotRepoType == fsRepoType = do
4078+ let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4079+ parseRepo $ do
4080+ FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4081+ <*> o .:? "compress" .!= False
4082+ <*> o .:? "chunk_size"
4083+ <*> o .:? "max_restore_bytes_per_sec"
4084+ <*> o .:? "max_snapshot_bytes_per_sec"
4085+ | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4086+
4087+
4088+parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4089+parseRepo parser = case parseEither (const parser) () of
4090+ Left e -> Left (OtherRepoConversionError (T.pack e))
4091+ Right a -> Right a
4092+
4093+
4094+fsRepoType :: SnapshotRepoType
4095+fsRepoType = SnapshotRepoType "fs"
4096+
4097+-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4098+class SnapshotRepo r where
4099+ toGSnapshotRepo :: r -> GenericSnapshotRepo
4100+ fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4101+
4102+
4103+data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4104+ -- ^ Expected type and actual type
4105+ | OtherRepoConversionError Text
4106+ deriving (Show, Eq, Generic, Typeable)
4107+
4108+
4109+instance Exception SnapshotRepoConversionError
4110+
4111+
4112+data SnapshotCreateSettings = SnapshotCreateSettings {
4113+ snapWaitForCompletion :: Bool
4114+ -- ^ Should the API call return immediately after initializing
4115+ -- the snapshot or wait until completed? Note that if this is
4116+ -- enabled it could wait a long time, so you should adjust your
4117+ -- 'ManagerSettings' accordingly to set long timeouts or
4118+ -- explicitly handle timeouts.
4119+ , snapIndices :: Maybe IndexSelection
4120+ -- ^ Nothing will snapshot all indices. Just [] is permissable and
4121+ -- will essentially be a no-op snapshot.
4122+ , snapIgnoreUnavailable :: Bool
4123+ -- ^ If set to True, any matched indices that don't exist will be
4124+ -- ignored. Otherwise it will be an error and fail.
4125+ , snapIncludeGlobalState :: Bool
4126+ , snapPartial :: Bool
4127+ -- ^ If some indices failed to snapshot (e.g. if not all primary
4128+ -- shards are available), should the process proceed?
4129+ } deriving (Eq, Generic, Show, Typeable)
4130+
4131+
4132+-- | Reasonable defaults for snapshot creation
4133+--
4134+-- * snapWaitForCompletion False
4135+-- * snapIndices Nothing
4136+-- * snapIgnoreUnavailable False
4137+-- * snapIncludeGlobalState True
4138+-- * snapPartial False
4139+defaultSnapshotCreateSettings :: SnapshotCreateSettings
4140+defaultSnapshotCreateSettings = SnapshotCreateSettings {
4141+ snapWaitForCompletion = False
4142+ , snapIndices = Nothing
4143+ , snapIgnoreUnavailable = False
4144+ , snapIncludeGlobalState = True
4145+ , snapPartial = False
4146+ }
4147+
4148+
4149+data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4150+ | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4151+
4152+
4153+-- | Either specifies an exact snapshot name or one with globs in it,
4154+-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4155+-- ES < 1.7
4156+data SnapshotPattern = ExactSnap SnapshotName
4157+ | SnapPattern Text
4158+ deriving (Eq, Generic, Show, Typeable)
4159+
4160+
4161+-- | General information about the state of a snapshot. Has some
4162+-- redundancies with 'SnapshotStatus'
4163+data SnapshotInfo = SnapshotInfo {
4164+ snapInfoShards :: ShardResult
4165+ , snapInfoFailures :: [SnapshotShardFailure]
4166+ , snapInfoDuration :: NominalDiffTime
4167+ , snapInfoEndTime :: UTCTime
4168+ , snapInfoStartTime :: UTCTime
4169+ , snapInfoState :: SnapshotState
4170+ , snapInfoIndices :: [IndexName]
4171+ , snapInfoName :: SnapshotName
4172+ } deriving (Eq, Generic, Show, Typeable)
4173+
4174+
4175+instance FromJSON SnapshotInfo where
4176+ parseJSON = withObject "SnapshotInfo" parse
4177+ where
4178+ parse o = SnapshotInfo <$> o .: "shards"
4179+ <*> o .: "failures"
4180+ <*> (unMS <$> o .: "duration_in_millis")
4181+ <*> (posixMS <$> o .: "end_time_in_millis")
4182+ <*> (posixMS <$> o .: "start_time_in_millis")
4183+ <*> o .: "state"
4184+ <*> o .: "indices"
4185+ <*> o .: "snapshot"
4186+
4187+data SnapshotShardFailure = SnapshotShardFailure {
4188+ snapShardFailureIndex :: IndexName
4189+ , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4190+ , snapShardFailureReason :: Text
4191+ , snapShardFailureShardId :: ShardId
4192+ } deriving (Eq, Show, Generic, Typeable)
4193+
4194+
4195+instance FromJSON SnapshotShardFailure where
4196+ parseJSON = withObject "SnapshotShardFailure" parse
4197+ where
4198+ parse o = SnapshotShardFailure <$> o .: "index"
4199+ <*> o .:? "node_id"
4200+ <*> o .: "reason"
4201+ <*> o .: "shard_id"
4202+
4203+
4204+newtype ShardId = ShardId { shardId :: Int }
4205+ deriving (Eq, Show, Generic, Typeable, FromJSON)
4206+
4207+-- | Milliseconds
4208+newtype MS = MS NominalDiffTime
4209+
4210+
4211+-- keeps the unexported constructor warnings at bay
4212+unMS :: MS -> NominalDiffTime
4213+unMS (MS t) = t
4214+
4215+
4216+instance FromJSON MS where
4217+ parseJSON = withScientific "MS" (return . MS . parse)
4218+ where
4219+ parse n = fromInteger ((truncate n) * 1000)
4220+
4221+
4222+data SnapshotState = SnapshotInit
4223+ | SnapshotStarted
4224+ | SnapshotSuccess
4225+ | SnapshotFailed
4226+ | SnapshotAborted
4227+ | SnapshotMissing
4228+ | SnapshotWaiting
4229+ deriving (Show, Eq, Generic, Typeable)
4230+
4231+instance FromJSON SnapshotState where
4232+ parseJSON = withText "SnapshotState" parse
4233+ where
4234+ parse "INIT" = return SnapshotInit
4235+ parse "STARTED" = return SnapshotStarted
4236+ parse "SUCCESS" = return SnapshotSuccess
4237+ parse "FAILED" = return SnapshotFailed
4238+ parse "ABORTED" = return SnapshotAborted
4239+ parse "MISSING" = return SnapshotMissing
4240+ parse "WAITING" = return SnapshotWaiting
4241+ parse t = fail ("Invalid snapshot state " <> T.unpack t)
4242+
4243+
4244+newtype SnapshotName = SnapshotName { snapshotName :: Text }
4245+ deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4246+
4247+
4248+data SnapshotRestoreSettings = SnapshotRestoreSettings {
4249+ snapRestoreWaitForCompletion :: Bool
4250+ -- ^ Should the API call return immediately after initializing
4251+ -- the restore or wait until completed? Note that if this is
4252+ -- enabled, it could wait a long time, so you should adjust your
4253+ -- 'ManagerSettings' accordingly to set long timeouts or
4254+ -- explicitly handle timeouts.
4255+ , snapRestoreIndices :: Maybe IndexSelection
4256+ -- ^ Nothing will restore all indices in the snapshot. Just [] is
4257+ -- permissable and will essentially be a no-op restore.
4258+ , snapRestoreIgnoreUnavailable :: Bool
4259+ -- ^ If set to True, any indices that do not exist will be ignored
4260+ -- during snapshot rather than failing the restore.
4261+ , snapRestoreIncludeGlobalState :: Bool
4262+ -- ^ If set to false, will ignore any global state in the snapshot
4263+ -- and will not restore it.
4264+ , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4265+ -- ^ A regex pattern for matching indices. Used with
4266+ -- 'snapRestoreRenameReplacement', the restore can reference the
4267+ -- matched index and create a new index name upon restore.
4268+ , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4269+ -- ^ Expression of how index renames should be constructed.
4270+ , snapRestorePartial :: Bool
4271+ -- ^ If some indices fail to restore, should the process proceed?
4272+ , snapRestoreIncludeAliases :: Bool
4273+ -- ^ Should the restore also restore the aliases captured in the
4274+ -- snapshot.
4275+ , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4276+ -- ^ Settings to apply during the restore process. __NOTE:__ This
4277+ -- option is not supported in ES < 1.5 and should be set to
4278+ -- Nothing in that case.
4279+ , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4280+ -- ^ This type could be more rich but it isn't clear which
4281+ -- settings are allowed to be ignored during restore, so we're
4282+ -- going with including this feature in a basic form rather than
4283+ -- omitting it. One example here would be
4284+ -- "index.refresh_interval". Any setting specified here will
4285+ -- revert back to the server default during the restore process.
4286+ } deriving (Eq, Generic, Show, Typeable)
4287+
4288+-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4289+newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4290+ deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4291+
4292+
4293+-- | A single token in a index renaming scheme for a restore. These
4294+-- are concatenated into a string before being sent to
4295+-- ElasticSearch. Check out these Java
4296+-- <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.
4297+data RestoreRenameToken = RRTLit Text
4298+ -- ^ Just a literal string of characters
4299+ | RRSubWholeMatch
4300+ -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4301+ | RRSubGroup RRGroupRefNum
4302+ -- ^ A specific reference to a group number
4303+ deriving (Show, Eq, Generic, Typeable)
4304+
4305+
4306+-- | A group number for regex matching. Only values from 1-9 are
4307+-- supported. Construct with 'mkRRGroupRefNum'
4308+newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4309+ deriving (Show, Eq, Generic, Typeable, Ord)
4310+
4311+instance Bounded RRGroupRefNum where
4312+ minBound = RRGroupRefNum 1
4313+ maxBound = RRGroupRefNum 9
4314+
4315+
4316+-- | Only allows valid group number references (1-9).
4317+mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4318+mkRRGroupRefNum i
4319+ | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4320+ Just $ RRGroupRefNum i
4321+ | otherwise = Nothing
4322+
4323+
4324+-- | Reasonable defaults for snapshot restores
4325+--
4326+-- * snapRestoreWaitForCompletion False
4327+-- * snapRestoreIndices Nothing
4328+-- * snapRestoreIgnoreUnavailable False
4329+-- * snapRestoreIncludeGlobalState True
4330+-- * snapRestoreRenamePattern Nothing
4331+-- * snapRestoreRenameReplacement Nothing
4332+-- * snapRestorePartial False
4333+-- * snapRestoreIncludeAliases True
4334+-- * snapRestoreIndexSettingsOverrides Nothing
4335+-- * snapRestoreIgnoreIndexSettings Nothing
4336+defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4337+defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4338+ snapRestoreWaitForCompletion = False
4339+ , snapRestoreIndices = Nothing
4340+ , snapRestoreIgnoreUnavailable = False
4341+ , snapRestoreIncludeGlobalState = True
4342+ , snapRestoreRenamePattern = Nothing
4343+ , snapRestoreRenameReplacement = Nothing
4344+ , snapRestorePartial = False
4345+ , snapRestoreIncludeAliases = True
4346+ , snapRestoreIndexSettingsOverrides = Nothing
4347+ , snapRestoreIgnoreIndexSettings = Nothing
4348+ }
4349+
4350+
4351+-- | Index settings that can be overridden. The docs only mention you
4352+-- can update number of replicas, but there may be more. You
4353+-- definitely cannot override shard count.
4354+data RestoreIndexSettings = RestoreIndexSettings {
4355+ restoreOverrideReplicas :: Maybe ReplicaCount
4356+ } deriving (Show, Eq, Generic, Typeable)
4357+
4358+
4359+instance ToJSON RestoreIndexSettings where
4360+ toJSON RestoreIndexSettings {..} = object prs
4361+ where
4362+ prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
4363+
4364+
4365+instance FromJSON NodesInfo where
4366+ parseJSON = withObject "NodesInfo" parse
4367+ where
4368+ parse o = do
4369+ nodes <- o .: "nodes"
4370+ infos <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4371+ node <- parseJSON v
4372+ parseNodeInfo (FullNodeId fullNID) node
4373+ cn <- o .: "cluster_name"
4374+ return (NodesInfo infos cn)
4375+
4376+
4377+parseNodeInfo :: FullNodeId -> Object -> Parser NodeInfo
4378+parseNodeInfo nid o =
4379+ NodeInfo <$> o .: "http_address"
4380+ <*> o .: "build"
4381+ <*> o .: "version"
4382+ <*> o .: "ip"
4383+ <*> o .: "host"
4384+ <*> o .: "transport_address"
4385+ <*> o .: "name"
4386+ <*> pure nid
4387+ <*> o .: "plugins"
4388+ <*> o .: "http"
4389+ <*> o .: "transport"
4390+ <*> o .: "network"
4391+ <*> o .: "thread_pool"
4392+ <*> o .: "jvm"
4393+ <*> o .: "process"
4394+ <*> o .: "os"
4395+ <*> o .: "settings"
4396+
4397+instance FromJSON NodePluginInfo where
4398+ parseJSON = withObject "NodePluginInfo" parse
4399+ where
4400+ parse o = NodePluginInfo <$> o .: "site"
4401+ <*> o .: "jvm"
4402+ <*> o .: "description"
4403+ <*> o .: "version"
4404+ <*> o .: "name"
4405+
4406+instance FromJSON NodeHTTPInfo where
4407+ parseJSON = withObject "NodeHTTPInfo" parse
4408+ where
4409+ parse o = NodeHTTPInfo <$> o .: "max_content_length_in_bytes"
4410+ <*> parseJSON (Object o)
4411+
4412+instance FromJSON BoundTransportAddress where
4413+ parseJSON = withObject "BoundTransportAddress" parse
4414+ where
4415+ parse o = BoundTransportAddress <$> o .: "publish_address"
4416+ <*> o .: "bound_address"
4417+
4418+instance FromJSON NodeOSInfo where
4419+ parseJSON = withObject "NodeOSInfo" parse
4420+ where
4421+ parse o = do
4422+ swap <- o .: "swap"
4423+ mem <- o .: "mem"
4424+ NodeOSInfo <$> swap .: "total_in_bytes"
4425+ <*> mem .: "total_in_bytes"
4426+ <*> o .: "cpu"
4427+ <*> o .: "available_processors"
4428+ <*> (unMS <$> o .: "refresh_interval_in_millis")
4429+
4430+
4431+instance FromJSON CPUInfo where
4432+ parseJSON = withObject "CPUInfo" parse
4433+ where
4434+ parse o = CPUInfo <$> o .: "cache_size_in_bytes"
4435+ <*> o .: "cores_per_socket"
4436+ <*> o .: "total_sockets"
4437+ <*> o .: "total_cores"
4438+ <*> o .: "mhz"
4439+ <*> o .: "model"
4440+ <*> o .: "vendor"
4441+
4442+instance FromJSON NodeProcessInfo where
4443+ parseJSON = withObject "NodeProcessInfo" parse
4444+ where
4445+ parse o = NodeProcessInfo <$> o .: "mlockall"
4446+ <*> o .: "max_file_descriptors"
4447+ <*> o .: "id"
4448+ <*> (unMS <$> o .: "refresh_interval_in_millis")
4449+
4450+instance FromJSON NodeJVMInfo where
4451+ parseJSON = withObject "NodeJVMInfo" parse
4452+ where
4453+ parse o = NodeJVMInfo <$> o .: "memory_pools"
4454+ <*> o .: "gc_collectors"
4455+ <*> o .: "mem"
4456+ <*> (posixMS <$> o .: "start_time_in_millis")
4457+ <*> o .: "vm_vendor"
4458+ <*> o .: "vm_version"
4459+ <*> o .: "vm_name"
4460+ <*> (unJVMVersion <$> o .: "version")
4461+ <*> o .: "pid"
4462+
4463+instance FromJSON JVMVersion where
4464+ parseJSON (String t) =
4465+ JVMVersion <$> parseJSON (String (T.replace "_" "." t))
4466+ parseJSON v = JVMVersion <$> parseJSON v
4467+
4468+instance FromJSON JVMMemoryInfo where
4469+ parseJSON = withObject "JVMMemoryInfo" parse
4470+ where
4471+ parse o = JVMMemoryInfo <$> o .: "direct_max_in_bytes"
4472+ <*> o .: "non_heap_max_in_bytes"
4473+ <*> o .: "non_heap_init_in_bytes"
4474+ <*> o .: "heap_max_in_bytes"
4475+ <*> o .: "heap_init_in_bytes"
4476+
4477+instance FromJSON NodeThreadPoolsInfo where
4478+ parseJSON = withObject "NodeThreadPoolsInfo" parse
4479+ where
4480+ parse o = NodeThreadPoolsInfo <$> o .: "refresh"
4481+ <*> o .: "management"
4482+ <*> o .: "percolate"
4483+ <*> o .:? "listener"
4484+ <*> o .:? "fetch_shard_started"
4485+ <*> o .: "search"
4486+ <*> o .: "flush"
4487+ <*> o .: "warmer"
4488+ <*> o .: "optimize"
4489+ <*> o .: "bulk"
4490+ <*> o .: "suggest"
4491+ <*> o .: "merge"
4492+ <*> o .: "snapshot"
4493+ <*> o .: "get"
4494+ <*> o .:? "fetch_shard_store"
4495+ <*> o .: "index"
4496+ <*> o .: "generic"
4497+
4498+instance FromJSON NodeThreadPoolInfo where
4499+ parseJSON = withObject "NodeThreadPoolInfo" parse
4500+ where
4501+ parse o = do
4502+ ka <- maybe (return Nothing) (fmap Just . parseStringInterval) =<< o .:? "keep_alive"
4503+ NodeThreadPoolInfo <$> (parseJSON . unStringlyTypeJSON =<< o .: "queue_size")
4504+ <*> pure ka
4505+ <*> o .:? "min"
4506+ <*> o .:? "max"
4507+ <*> o .: "type"
4508+
4509+parseStringInterval :: (Monad m) => String -> m NominalDiffTime
4510+parseStringInterval s = case span isNumber s of
4511+ ("", _) -> fail "Invalid interval"
4512+ (nS, unitS) -> case (readMay nS, readMay unitS) of
4513+ (Just n, Just unit) -> return (fromInteger (n * unitNDT unit))
4514+ (Nothing, _) -> fail "Invalid interval number"
4515+ (_, Nothing) -> fail "Invalid interval unit"
4516+ where
4517+ unitNDT Seconds = 1
4518+ unitNDT Minutes = 60
4519+ unitNDT Hours = 60 * 60
4520+ unitNDT Days = 24 * 60 * 60
4521+ unitNDT Weeks = 7 * 24 * 60 * 60
4522+
4523+instance FromJSON ThreadPoolSize where
4524+ parseJSON v = parseAsNumber v <|> parseAsString v
4525+ where
4526+ parseAsNumber = parseAsInt <=< parseJSON
4527+ parseAsInt (-1) = return ThreadPoolUnbounded
4528+ parseAsInt n
4529+ | n >= 0 = return (ThreadPoolBounded n)
4530+ | otherwise = fail "Thread pool size must be >= -1."
4531+ parseAsString = withText "ThreadPoolSize" $ \t ->
4532+ case first (readMay . T.unpack) (T.span isNumber t) of
4533+ (Just n, "k") -> return (ThreadPoolBounded (n * 1000))
4534+ (Just n, "") -> return (ThreadPoolBounded n)
4535+ _ -> fail ("Invalid thread pool size " <> T.unpack t)
4536+
4537+instance FromJSON ThreadPoolType where
4538+ parseJSON = withText "ThreadPoolType" parse
4539+ where
4540+ parse "scaling" = return ThreadPoolScaling
4541+ parse "fixed" = return ThreadPoolFixed
4542+ parse "cached" = return ThreadPoolCached
4543+ parse e = fail ("Unexpected thread pool type" <> T.unpack e)
4544+
4545+instance FromJSON NodeTransportInfo where
4546+ parseJSON = withObject "NodeTransportInfo" parse
4547+ where
4548+ parse o = NodeTransportInfo <$> (maybe (return mempty) parseProfiles =<< o .:? "profiles")
4549+ <*> parseJSON (Object o)
4550+ parseProfiles (Object o) | HM.null o = return []
4551+ parseProfiles v@(Array _) = parseJSON v
4552+ parseProfiles Null = return []
4553+ parseProfiles _ = fail "Could not parse profiles"
4554+
4555+instance FromJSON NodeNetworkInfo where
4556+ parseJSON = withObject "NodeNetworkInfo" parse
4557+ where
4558+ parse o = NodeNetworkInfo <$> o .: "primary_interface"
4559+ <*> (unMS <$> o .: "refresh_interval_in_millis")
4560+
4561+
4562+instance FromJSON NodeNetworkInterface where
4563+ parseJSON = withObject "NodeNetworkInterface" parse
4564+ where
4565+ parse o = NodeNetworkInterface <$> o .: "mac_address"
4566+ <*> o .: "name"
4567+ <*> o .: "address"