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