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