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