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