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