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