@@ -0,0 +1,5271 @@
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 #-}
13+-------------------------------------------------------------------------------
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
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
28+-------------------------------------------------------------------------------
32+module Database.V1.Bloodhound.Types
34+ , defaultIndexSettings
35+ , defaultIndexDocumentSettings
46+ , mkTermsScriptAggregation
48+ , mkCardinalityAggregation
72+ , UpdatableIndexSetting(..)
73+ , IndexSettingsSummary(..)
74+ , AllocationPolicy(..)
81+ , InitialShardCount(..)
91+ , EsProtocolException(..)
94+ , IndexAliasAction(..)
95+ , IndexAliasCreate(..)
96+ , IndexAliasSummary(..)
97+ , IndexAliasesSummary(..)
99+ , SearchAliasRouting(..)
100+ , IndexAliasRouting(..)
103+ , ExternalDocVersion(..)
104+ , VersionControl(..)
105+ , DocumentParent(..)
106+ , IndexDocumentSettings(..)
117+ , PatternOrPatterns(..)
128+ , GeoBoundingBoxConstraint(..)
129+ , GeoBoundingBox(..)
138+ , RangeExecution(..)
146+ , GreaterThanEqD(..)
153+ , IndexSelection(..)
156+ , IndexOptimizationSettings(..)
157+ , defaultIndexOptimizationSettings
159+ , TemplatePattern(..)
173+ , OpenCloseIndex(..)
177+ , MultiMatchQuery(..)
180+ , CommonTermsQuery(..)
183+ , FuzzyLikeThisQuery(..)
184+ , FuzzyLikeFieldQuery(..)
187+ , HasParentQuery(..)
189+ , MoreLikeThisQuery(..)
190+ , MoreLikeThisFieldQuery(..)
193+ , QueryStringQuery(..)
194+ , SimpleQueryStringQuery(..)
198+ , BooleanOperator(..)
199+ , ZeroTermsQuery(..)
200+ , CutoffFrequency(..)
204+ , MatchQueryType(..)
205+ , MultiMatchQueryType(..)
209+ , CommonMinimumMatch(..)
210+ , MinimumMatchHighLow(..)
213+ , IgnoreTermFrequency(..)
222+ , MaxDocFrequency(..)
223+ , MinDocFrequency(..)
227+ , MinimumTermFrequency(..)
229+ , FieldDefinition(..)
232+ , AllowLeadingWildcard(..)
233+ , LowercaseExpanded(..)
234+ , GeneratePhraseQueries(..)
236+ , AnalyzeWildcard(..)
237+ , EnablePositionIncrements(..)
238+ , SimpleQueryFlag(..)
245+ , CollectionMode(..)
248+ , SnapshotRepoSelection(..)
249+ , GenericSnapshotRepo(..)
251+ , SnapshotRepoConversionError(..)
252+ , SnapshotRepoType(..)
253+ , GenericSnapshotRepoSettings(..)
254+ , SnapshotRepoUpdateSettings(..)
255+ , defaultSnapshotRepoUpdateSettings
256+ , SnapshotRepoName(..)
257+ , SnapshotRepoPattern(..)
258+ , SnapshotVerification(..)
259+ , SnapshotNodeVerification(..)
266+ , NodeBreakersStats(..)
267+ , NodeBreakerStats(..)
269+ , NodeTransportStats(..)
271+ , NodeDataPathStats(..)
272+ , NodeFSTotalStats(..)
273+ , NodeNetworkStats(..)
274+ , NodeThreadPoolsStats(..)
275+ , NodeThreadPoolStats(..)
277+ , JVMBufferPoolStats(..)
280+ , NodeProcessStats(..)
283+ , NodeIndicesStats(..)
287+ , NodePluginInfo(..)
289+ , NodeTransportInfo(..)
290+ , BoundTransportAddress(..)
291+ , NodeNetworkInfo(..)
293+ , NetworkInterfaceName(..)
294+ , NodeNetworkInterface(..)
295+ , NodeThreadPoolsInfo(..)
296+ , NodeThreadPoolInfo(..)
297+ , ThreadPoolSize(..)
298+ , ThreadPoolType(..)
301+ , JVMGCCollector(..)
306+ , NodeProcessInfo(..)
307+ , FsSnapshotRepo(..)
308+ , SnapshotCreateSettings(..)
309+ , defaultSnapshotCreateSettings
310+ , SnapshotSelection(..)
311+ , SnapshotPattern(..)
313+ , SnapshotShardFailure(..)
317+ , SnapshotRestoreSettings(..)
318+ , defaultSnapshotRestoreSettings
319+ , RestoreRenamePattern(..)
320+ , RestoreRenameToken(..)
324+ , RestoreIndexSettings(..)
328+ , AggregationResults
331+ , BucketAggregation(..)
332+ , TermsAggregation(..)
333+ , MissingAggregation(..)
334+ , ValueCountAggregation(..)
335+ , FilterAggregation(..)
336+ , CardinalityAggregation(..)
337+ , DateHistogramAggregation(..)
338+ , DateRangeAggregation(..)
339+ , DateRangeAggRange(..)
341+ , DateMathAnchor(..)
342+ , DateMathModifier(..)
344+ , TopHitsAggregation(..)
347+ , FieldHighlight(..)
348+ , HighlightSettings(..)
349+ , PlainHighlight(..)
350+ , PostingsHighlight(..)
351+ , FastVectorHighlight(..)
352+ , CommonHighlight(..)
354+ , HighlightEncoder(..)
360+ , DateHistogramResult(..)
361+ , DateRangeResult(..)
368+import Control.Applicative as A
369+import Control.Arrow (first)
370+import Control.Monad.Catch
371+import Control.Monad.Except
372+import Control.Monad.Reader
373+import Control.Monad.State
374+import Control.Monad.Writer
376+import Data.Aeson.Types (Pair, Parser, emptyObject,
377+ parseEither, parseMaybe)
378+import qualified Data.ByteString.Lazy.Char8 as L
380+import Data.Hashable (Hashable)
381+import qualified Data.HashMap.Strict as HM
382+import Data.List (foldl', intercalate, nub)
383+import Data.List.NonEmpty (NonEmpty (..), toList)
384+import qualified Data.Map.Strict as M
386+import Data.Scientific (Scientific)
387+import Data.Text (Text)
388+import qualified Data.Text as T
389+import Data.Time.Calendar
390+import Data.Time.Clock (NominalDiffTime, UTCTime)
391+import Data.Time.Clock.POSIX
392+import qualified Data.Traversable as DT
393+import Data.Typeable (Typeable)
394+import qualified Data.Vector as V
395+import qualified Data.Version as Vers
397+import GHC.Generics (Generic)
398+import Network.HTTP.Client
399+import qualified Network.HTTP.Types.Method as NHTM
400+import qualified Text.ParserCombinators.ReadP as RP
401+import qualified Text.Read as TR
403+import Database.V1.Bloodhound.Types.Class
404+import Database.V1.Bloodhound.Types.Internal
407+-- >>> :set -XOverloadedStrings
408+-- >>> import Data.Aeson
409+-- >>> import Database.V1.Bloodhound
410+-- >>> let testServer = (Server "http://localhost:9200")
411+-- >>> let testIndex = IndexName "twitter"
412+-- >>> let testMapping = MappingName "tweet"
413+-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
415+-- defaultIndexSettings is exported by Database.Bloodhound as well
416+-- no trailing slashes in servers, library handles building the path.
418+-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
419+-- will be a noop. You can use the exported fields to customize it further, e.g.:
421+-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
422+mkBHEnv :: Server -> Manager -> BHEnv
423+mkBHEnv s m = BHEnv s m return
425+newtype BH m a = BH {
426+ unBH :: ReaderT BHEnv m a
427+ } deriving ( Functor
441+instance MonadTrans BH where
444+instance (MonadReader r m) => MonadReader r (BH m) where
446+ local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
449+instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
450+ getBHEnv = BH getBHEnv
452+runBH :: BHEnv -> BH m a -> m a
453+runBH e f = runReaderT (unBH f) e
455+{-| 'Version' is embedded in 'Status' -}
456+data Version = Version { number :: VersionNumber
457+ , build_hash :: BuildHash
458+ , build_timestamp :: UTCTime
459+ , build_snapshot :: Bool
460+ , lucene_version :: VersionNumber } deriving (Eq, Read, Show, Generic, Typeable)
462+-- | Traditional software versioning number
463+newtype VersionNumber = VersionNumber { versionNumber :: Vers.Version
464+ } deriving (Eq, Read, Show, Generic, Typeable, Ord)
466+{-| 'Status' is a data type for describing the JSON body returned by
467+ Elasticsearch when you query its status. This was deprecated in 1.2.0.
469+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
472+data Status = Status { ok :: Maybe Bool
475+ , version :: Version
476+ , tagline :: Text } deriving (Eq, Read, Show, Generic)
478+{-| 'IndexSettings' is used to configure the shards and replicas when you create
479+ an Elasticsearch Index.
481+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
485+ IndexSettings { indexShards :: ShardCount
486+ , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
488+{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
489+defaultIndexSettings :: IndexSettings
490+defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
493+{-| 'IndexOptimizationSettings' is used to configure index optimization. See
494+ <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
497+data IndexOptimizationSettings =
498+ IndexOptimizationSettings { maxNumSegments :: Maybe Int
499+ -- ^ 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.
500+ , onlyExpungeDeletes :: Bool
501+ -- ^ 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.
502+ , flushAfterOptimize :: Bool
503+ -- ^ Should a flush be performed after the optimize.
504+ } deriving (Eq, Show, Generic, Typeable)
507+{-| 'defaultIndexOptimizationSettings' implements the default settings that
508+ ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
509+ 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
511+defaultIndexOptimizationSettings :: IndexOptimizationSettings
512+defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
514+{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
516+ <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
518+data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
519+ -- ^ The number of replicas each shard has.
520+ | AutoExpandReplicas ReplicaBounds
521+ | BlocksReadOnly Bool
522+ -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
524+ -- ^ Set to True to disable read operations against the index.
526+ -- ^ Set to True to disable write operations against the index.
527+ | BlocksMetaData Bool
528+ -- ^ Set to True to disable metadata operations against the index.
529+ | RefreshInterval NominalDiffTime
530+ -- ^ The async refresh interval of a shard
531+ | IndexConcurrency Int
532+ | FailOnMergeFailure Bool
533+ | TranslogFlushThresholdOps Int
534+ -- ^ When to flush on operations.
535+ | TranslogFlushThresholdSize Bytes
536+ -- ^ When to flush based on translog (bytes) size.
537+ | TranslogFlushThresholdPeriod NominalDiffTime
538+ -- ^ When to flush based on a period of not flushing.
539+ | TranslogDisableFlush Bool
540+ -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
541+ | CacheFilterMaxSize (Maybe Bytes)
542+ -- ^ The maximum size of filter cache (per segment in shard).
543+ | CacheFilterExpire (Maybe NominalDiffTime)
544+ -- ^ The expire after access time for filter cache.
545+ | GatewaySnapshotInterval NominalDiffTime
546+ -- ^ The gateway snapshot interval (only applies to shared gateways).
547+ | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
548+ -- ^ A node matching any rule will be allowed to host shards from the index.
549+ | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
550+ -- ^ A node matching any rule will NOT be allowed to host shards from the index.
551+ | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
552+ -- ^ Only nodes matching all rules will be allowed to host shards from the index.
553+ | RoutingAllocationEnable AllocationPolicy
554+ -- ^ Enables shard allocation for a specific index.
555+ | RoutingAllocationShardsPerNode ShardCount
556+ -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
557+ | RecoveryInitialShards InitialShardCount
558+ -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
559+ | GCDeletes NominalDiffTime
560+ | TTLDisablePurge Bool
561+ -- ^ Disables temporarily the purge of expired docs.
562+ | TranslogFSType FSType
563+ | IndexCompoundFormat CompoundFormat
564+ | IndexCompoundOnFlush Bool
565+ | WarmerEnabled Bool
566+ deriving (Eq, Show, Generic, Typeable)
568+data AllocationPolicy = AllocAll
569+ -- ^ Allows shard allocation for all shards.
571+ -- ^ Allows shard allocation only for primary shards.
573+ -- ^ Allows shard allocation only for primary shards for new indices.
575+ -- ^ No shard allocation is allowed
576+ deriving (Eq, Read, Show, Generic, Typeable)
578+data ReplicaBounds = ReplicasBounded Int Int
579+ | ReplicasLowerBounded Int
581+ deriving (Eq, Read, Show, Generic, Typeable)
583+-- | A measure of bytes used for various configurations. You may want
584+-- to use smart constructors like 'gigabytes' for larger values.
594+newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
596+gigabytes :: Int -> Bytes
597+gigabytes n = megabytes (1000 * n)
600+megabytes :: Int -> Bytes
601+megabytes n = kilobytes (1000 * n)
604+kilobytes :: Int -> Bytes
605+kilobytes n = Bytes (1000 * n)
608+data FSType = FSSimple
609+ | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
611+data InitialShardCount = QuorumShards
612+ | QuorumMinus1Shards
615+ | ExplicitShards Int
616+ deriving (Eq, Read, Show, Generic, Typeable)
618+data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
619+ , nodeAttrFilterValues :: NonEmpty Text}
620+ deriving (Eq, Read, Show, Generic, Ord, Typeable)
622+newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
624+data CompoundFormat = CompoundFileFormat Bool
625+ | MergeSegmentVsTotalIndex Double
626+ -- ^ percentage between 0 and 1 where 0 is false, 1 is true
627+ deriving (Eq, Read, Show, Generic, Typeable)
629+newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
631+data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
632+ , sSummaryFixedSettings :: IndexSettings
633+ , sSummaryUpdateable :: [UpdatableIndexSetting]}
634+ deriving (Eq, Show, Generic, Typeable)
636+{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
637+type Reply = Network.HTTP.Client.Response L.ByteString
638+type Method = NHTM.Method
640+{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
642+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
644+data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
646+data FieldType = GeoPointType
652+ | ByteType deriving (Eq, Read, Show, Generic, Typeable)
654+data FieldDefinition =
655+ FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
657+{-| An 'IndexTemplate' defines a template that will automatically be
658+ applied to new indices created. The templates include both
659+ 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
660+ controls if the template will be applied to the index created.
661+ Specify mappings as follows: @[toJSON TweetMapping, ...]@
663+ https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
666+ IndexTemplate { templatePattern :: TemplatePattern
667+ , templateSettings :: Maybe IndexSettings
668+ , templateMappings :: [Value]
672+ MappingField { mappingFieldName :: FieldName
673+ , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
675+{-| Support for type reification of 'Mapping's is currently incomplete, for
676+ now the mapping API verbiage expects a 'ToJSON'able blob.
678+ Indexes have mappings, mappings are schemas for the documents contained in the
679+ index. I'd recommend having only one mapping per index, always having a mapping,
680+ and keeping different kinds of documents separated if possible.
682+data Mapping = Mapping { typeName :: TypeName
683+ , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
685+{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
686+ operation index, create, delete, and update. 'BulkIndex' behaves like an
687+ "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
689+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
692+ BulkIndex IndexName MappingName DocId Value
693+ | BulkCreate IndexName MappingName DocId Value
694+ | BulkDelete IndexName MappingName DocId
695+ | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
697+{-| 'EsResult' describes the standard wrapper JSON document that you see in
698+ successful Elasticsearch lookups or lookups that couldn't find the document.
700+data EsResult a = EsResult { _index :: Text
703+ , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
705+{-| 'EsResultFound' contains the document and its metadata inside of an
706+ 'EsResult' when the document was successfully found.
708+data EsResultFound a = EsResultFound { _version :: DocVersion
709+ , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
711+{-| 'EsError' is the generic type that will be returned when there was a
712+ problem. If you can't parse the expected response, its a good idea to
715+data EsError = EsError { errorStatus :: Int
716+ , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
718+{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
719+returned by the ElasticSearch server. If you encounter this error, please
720+verify that your domain data types and FromJSON instances are working properly
721+(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
722+sure that your mappings are correct, then this error may be an indication of an
723+incompatibility between Bloodhound and ElasticSearch. Please open a bug report
724+and be sure to include the exception body.
726+data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
727+ deriving (Eq, Read, Show, Generic, Typeable)
729+instance Exception EsProtocolException
731+data IndexAlias = IndexAlias { srcIndex :: IndexName
732+ , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
734+newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
736+data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
737+ | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
739+data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
740+ , aliasCreateFilter :: Maybe Filter}
741+ deriving (Read, Show, Eq, Generic, Typeable)
743+data AliasRouting = AllAliasRouting RoutingValue
744+ | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
745+ deriving (Read, Show, Eq, Generic, Typeable)
747+newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
749+newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
751+newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
753+newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
755+{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
756+data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
757+ , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
759+{-| 'DocVersion' is an integer version number for a document between 1
760+and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
762+newtype DocVersion = DocVersion {
763+ docVersionNumber :: Int
764+ } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
766+-- | Smart constructor for in-range doc version
767+mkDocVersion :: Int -> Maybe DocVersion
769+ | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
771+ | otherwise = Nothing
774+{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
775+own version numbers instead of ones from ES.
777+newtype ExternalDocVersion = ExternalDocVersion DocVersion
778+ deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
780+{-| 'VersionControl' is specified when indexing documents as a
781+optimistic concurrency control.
783+data VersionControl = NoVersionControl
784+ -- ^ Don't send a version. This is a pure overwrite.
785+ | InternalVersion DocVersion
786+ -- ^ Use the default ES versioning scheme. Only
787+ -- index the document if the version is the same
788+ -- as the one specified. Only applicable to
789+ -- updates, as you should be getting Version from
791+ | ExternalGT ExternalDocVersion
792+ -- ^ Use your own version numbering. Only index
793+ -- the document if the version is strictly higher
794+ -- OR the document doesn't exist. The given
795+ -- version will be used as the new version number
796+ -- for the stored document. N.B. All updates must
797+ -- increment this number, meaning there is some
798+ -- global, external ordering of updates.
799+ | ExternalGTE ExternalDocVersion
800+ -- ^ Use your own version numbering. Only index
801+ -- the document if the version is equal or higher
802+ -- than the stored version. Will succeed if there
803+ -- is no existing document. The given version will
804+ -- be used as the new version number for the
805+ -- stored document. Use with care, as this could
806+ -- result in data loss.
807+ | ForceVersion ExternalDocVersion
808+ -- ^ The document will always be indexed and the
809+ -- given version will be the new version. This is
810+ -- typically used for correcting errors. Use with
811+ -- care, as this could result in data loss.
812+ deriving (Read, Show, Eq, Generic, Ord)
814+{-| 'DocumentParent' is used to specify a parent document.
816+newtype DocumentParent = DocumentParent DocId
817+ deriving (Eq, Read, Show, Generic, Typeable)
819+{-| 'IndexDocumentSettings' are special settings supplied when indexing
820+a document. For the best backwards compatiblity when new fields are
821+added, you should probably prefer to start with 'defaultIndexDocumentSettings'
823+data IndexDocumentSettings =
824+ IndexDocumentSettings { idsVersionControl :: VersionControl
825+ , idsParent :: Maybe DocumentParent
826+ } deriving (Eq, Read, Show, Generic, Typeable)
828+{-| Reasonable default settings. Chooses no version control and no parent.
830+defaultIndexDocumentSettings :: IndexDocumentSettings
831+defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
833+{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
834+ dependent with later sorts acting as tie-breakers for earlier sorts.
836+type Sort = [SortSpec]
838+{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
839+ 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
840+ 'DistanceUnit' to express "nearness" to a single geographical point as a
843+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
845+data SortSpec = DefaultSortSpec DefaultSort
846+ | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
848+{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
849+ 'mkSort' convenience function for when you want to specify only the most
852+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
855+ DefaultSort { sortFieldName :: FieldName
856+ , sortOrder :: SortOrder
858+ , ignoreUnmapped :: Bool
859+ , sortMode :: Maybe SortMode
860+ , missingSort :: Maybe Missing
861+ , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
863+{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
864+ encoded into "asc" or "desc" when turned into JSON.
866+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
868+data SortOrder = Ascending
869+ | Descending deriving (Eq, Read, Show, Generic, Typeable)
871+{-| 'Missing' prescribes how to handle missing fields. A missing field can be
872+ sorted last, first, or using a custom value as a substitute.
874+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
876+data Missing = LastMissing
878+ | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
880+{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
882+http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
884+data SortMode = SortMin
887+ | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
889+{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
890+ that you can concisely describe the usual kind of 'SortSpec's you want.
892+mkSort :: FieldName -> SortOrder -> DefaultSort
893+mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
895+{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
896+ 'Query's cannot be cached.
898+type Cache = Bool -- caching on/off
899+defaultCache :: Cache
902+{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
904+type PrefixValue = Text
906+{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
907+ JSON encoding baked in. Used all over the place.
909+data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
911+{-| 'ShardCount' is part of 'IndexSettings'
913+newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
915+{-| 'ReplicaCount' is part of 'IndexSettings'
917+newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
919+{-| 'IndexName' is used to describe which index to query/create/delete
921+newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
923+{-| 'IndexSelection' is used for APIs which take a single index, a list of
924+ indexes, or the special @_all@ index.
926+--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.
927+data IndexSelection = IndexList (NonEmpty IndexName)
928+ | AllIndexes deriving (Eq, Generic, Show, Typeable)
930+{-| '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.
932+data NodeSelection = LocalNode
933+ -- ^ Whatever node receives this request
934+ | NodeList (NonEmpty NodeSelector)
935+ | AllNodes deriving (Eq, Generic, Show, Typeable)
938+-- | An exact match or pattern to identify a node. Note that All of
939+-- these options support wildcarding, so your node name, server, attr
940+-- name can all contain * characters to be a fuzzy match.
941+data NodeSelector = NodeByName NodeName
942+ | NodeByFullNodeId FullNodeId
944+ -- ^ e.g. 10.0.0.1 or even 10.0.0.*
945+ | NodeByAttribute NodeAttrName Text
946+ -- ^ NodeAttrName can be a pattern, e.g. rack*. The value can too.
947+ deriving (Eq, Generic, Show, Typeable)
949+{-| 'TemplateName' is used to describe which template to query/create/delete
951+newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
953+{-| 'TemplatePattern' represents a pattern which is matched against index names
955+newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
957+{-| 'MappingName' is part of mappings which are how ES describes and schematizes
958+ the data in the indices.
960+newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
962+{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
963+ Can be set by the user or created by ES itself. Often used in client
964+ functions for poking at specific documents.
966+newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
968+{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
970+newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
972+{-| 'FieldName' is used all over the place wherever a specific field within
973+ a document needs to be specified, usually in 'Query's or 'Filter's.
975+newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
978+{-| 'Script' is often used in place of 'FieldName' to specify more
979+complex ways of extracting a value from a document.
981+newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
983+{-| 'CacheName' is used in 'RegexpFilter' for describing the
984+ 'CacheKey' keyed caching behavior.
986+newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
988+{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
991+ CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
993+ Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
995+ NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
996+newtype CutoffFrequency =
997+ CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
999+ Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1000+newtype MaxExpansions =
1001+ MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1003+{-| 'Lenient', if set to true, will cause format based failures to be
1004+ ignored. I don't know what the bloody default is, Elasticsearch
1005+ documentation didn't say what it was. Let me know if you figure it out.
1008+ Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1009+newtype Tiebreaker =
1010+ Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1012+ Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1013+newtype BoostTerms =
1014+ BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1016+{-| 'MinimumMatch' controls how many should clauses in the bool query should
1017+ match. Can be an absolute value (2) or a percentage (30%) or a
1018+ combination of both.
1020+newtype MinimumMatch =
1021+ MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1022+newtype DisableCoord =
1023+ DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1024+newtype IgnoreTermFrequency =
1025+ IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1026+newtype MinimumTermFrequency =
1027+ MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1028+newtype MaxQueryTerms =
1029+ MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1031+ Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1033+{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
1034+newtype PrefixLength =
1035+ PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1037+ TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1038+newtype PercentMatch =
1039+ PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1041+ StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1043+ QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1045+{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
1046+ heavy, because all terms in the index need to be examined, just in case
1047+ they match. Leading wildcards can be disabled by setting
1048+ 'AllowLeadingWildcard' to false. -}
1049+newtype AllowLeadingWildcard =
1050+ AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1051+newtype LowercaseExpanded =
1052+ LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1053+newtype EnablePositionIncrements =
1054+ EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1056+{-| By default, wildcard terms in a query are not analyzed.
1057+ Setting 'AnalyzeWildcard' to true enables best-effort analysis.
1059+newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1061+{-| 'GeneratePhraseQueries' defaults to false.
1063+newtype GeneratePhraseQueries =
1064+ GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1066+{-| 'Locale' is used for string conversions - defaults to ROOT.
1068+newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1069+newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1070+newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1072+{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
1073+ phrase matches. Default is 0.
1075+newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1076+newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1077+newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1079+-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
1080+newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
1082+{-| 'unpackId' is a silly convenience function that gets used once.
1084+unpackId :: DocId -> Text
1085+unpackId (DocId docId) = docId
1087+type TrackSortScores = Bool
1088+newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1089+newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
1091+data Search = Search { queryBody :: Maybe Query
1092+ , filterBody :: Maybe Filter
1093+ , sortBody :: Maybe Sort
1094+ , aggBody :: Maybe Aggregations
1095+ , highlight :: Maybe Highlights
1097+ , trackSortScores :: TrackSortScores
1100+ , searchType :: SearchType
1101+ , fields :: Maybe [FieldName]
1102+ , source :: Maybe Source } deriving (Eq, Read, Show, Generic, Typeable)
1104+data SearchType = SearchTypeQueryThenFetch
1105+ | SearchTypeDfsQueryThenFetch
1108+ | SearchTypeQueryAndFetch
1109+ | SearchTypeDfsQueryAndFetch
1110+ deriving (Eq, Read, Show, Generic, Typeable)
1114+ | SourcePatterns PatternOrPatterns
1115+ | SourceIncludeExclude Include Exclude
1116+ deriving (Read, Show, Eq, Generic, Typeable)
1118+data PatternOrPatterns = PopPattern Pattern
1119+ | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1121+data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1122+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1124+newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
1126+data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1127+ , highlightFields :: [FieldHighlight]
1128+ } deriving (Read, Show, Eq, Generic, Typeable)
1130+data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1131+ deriving (Read, Show, Eq, Generic, Typeable)
1134+data HighlightSettings = Plain PlainHighlight
1135+ | Postings PostingsHighlight
1136+ | FastVector FastVectorHighlight
1137+ deriving (Read, Show, Eq, Generic, Typeable)
1138+data PlainHighlight =
1139+ PlainHighlight { plainCommon :: Maybe CommonHighlight
1140+ , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1142+ -- This requires that index_options are set to 'offset' in the mapping.
1143+data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1145+-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1146+data FastVectorHighlight =
1147+ FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1148+ , fvNonPostSettings :: Maybe NonPostings
1149+ , boundaryChars :: Maybe Text
1150+ , boundaryMaxScan :: Maybe Int
1151+ , fragmentOffset :: Maybe Int
1152+ , matchedFields :: [Text]
1153+ , phraseLimit :: Maybe Int
1154+ } deriving (Read, Show, Eq, Generic, Typeable)
1156+data CommonHighlight =
1157+ CommonHighlight { order :: Maybe Text
1158+ , forceSource :: Maybe Bool
1159+ , tag :: Maybe HighlightTag
1160+ , encoder :: Maybe HighlightEncoder
1161+ , noMatchSize :: Maybe Int
1162+ , highlightQuery :: Maybe Query
1163+ , requireFieldMatch :: Maybe Bool
1164+ } deriving (Read, Show, Eq, Generic, Typeable)
1166+-- Settings that are only applicable to FastVector and Plain highlighters.
1168+ NonPostings { fragmentSize :: Maybe Int
1169+ , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1171+data HighlightEncoder = DefaultEncoder
1173+ deriving (Read, Show, Eq, Generic, Typeable)
1175+-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1176+data HighlightTag = TagSchema Text
1177+ | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1178+ deriving (Read, Show, Eq, Generic, Typeable)
1182+ TermQuery Term (Maybe Boost)
1183+ | TermsQuery Text (NonEmpty Text)
1184+ | QueryMatchQuery MatchQuery
1185+ | QueryMultiMatchQuery MultiMatchQuery
1186+ | QueryBoolQuery BoolQuery
1187+ | QueryBoostingQuery BoostingQuery
1188+ | QueryCommonTermsQuery CommonTermsQuery
1189+ | ConstantScoreFilter Filter Boost
1190+ | ConstantScoreQuery Query Boost
1191+ | QueryDisMaxQuery DisMaxQuery
1192+ | QueryFilteredQuery FilteredQuery
1193+ | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1194+ | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1195+ | QueryFuzzyQuery FuzzyQuery
1196+ | QueryHasChildQuery HasChildQuery
1197+ | QueryHasParentQuery HasParentQuery
1198+ | IdsQuery MappingName [DocId]
1199+ | QueryIndicesQuery IndicesQuery
1200+ | MatchAllQuery (Maybe Boost)
1201+ | QueryMoreLikeThisQuery MoreLikeThisQuery
1202+ | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1203+ | QueryNestedQuery NestedQuery
1204+ | QueryPrefixQuery PrefixQuery
1205+ | QueryQueryStringQuery QueryStringQuery
1206+ | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1207+ | QueryRangeQuery RangeQuery
1208+ | QueryRegexpQuery RegexpQuery
1209+ deriving (Eq, Read, Show, Generic, Typeable)
1212+ RegexpQuery { regexpQueryField :: FieldName
1213+ , regexpQuery :: Regexp
1214+ , regexpQueryFlags :: RegexpFlags
1215+ , regexpQueryBoost :: Maybe Boost
1216+ } deriving (Eq, Read, Show, Generic, Typeable)
1219+ RangeQuery { rangeQueryField :: FieldName
1220+ , rangeQueryRange :: RangeValue
1221+ , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1223+mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1224+mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1226+data SimpleQueryStringQuery =
1227+ SimpleQueryStringQuery
1228+ { simpleQueryStringQuery :: QueryString
1229+ , simpleQueryStringField :: Maybe FieldOrFields
1230+ , simpleQueryStringOperator :: Maybe BooleanOperator
1231+ , simpleQueryStringAnalyzer :: Maybe Analyzer
1232+ , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1233+ , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1234+ , simpleQueryStringLocale :: Maybe Locale
1235+ } deriving (Eq, Read, Show, Generic, Typeable)
1237+data SimpleQueryFlag =
1242+ | SimpleQueryPrefix
1243+ | SimpleQueryPhrase
1244+ | SimpleQueryPrecedence
1245+ | SimpleQueryEscape
1246+ | SimpleQueryWhitespace
1249+ | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1251+-- use_dis_max and tie_breaker when fields are plural?
1252+data QueryStringQuery =
1254+ { queryStringQuery :: QueryString
1255+ , queryStringDefaultField :: Maybe FieldName
1256+ , queryStringOperator :: Maybe BooleanOperator
1257+ , queryStringAnalyzer :: Maybe Analyzer
1258+ , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1259+ , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1260+ , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1261+ , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1262+ , queryStringFuzziness :: Maybe Fuzziness
1263+ , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1264+ , queryStringPhraseSlop :: Maybe PhraseSlop
1265+ , queryStringBoost :: Maybe Boost
1266+ , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1267+ , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1268+ , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1269+ , queryStringLenient :: Maybe Lenient
1270+ , queryStringLocale :: Maybe Locale
1271+ } deriving (Eq, Read, Show, Generic, Typeable)
1273+mkQueryStringQuery :: QueryString -> QueryStringQuery
1274+mkQueryStringQuery qs =
1275+ QueryStringQuery qs Nothing Nothing
1276+ Nothing Nothing Nothing Nothing
1277+ Nothing Nothing Nothing Nothing
1278+ Nothing Nothing Nothing Nothing
1281+data FieldOrFields = FofField FieldName
1282+ | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1286+ { prefixQueryField :: FieldName
1287+ , prefixQueryPrefixValue :: Text
1288+ , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1292+ { nestedQueryPath :: QueryPath
1293+ , nestedQueryScoreType :: ScoreType
1294+ , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1296+data MoreLikeThisFieldQuery =
1297+ MoreLikeThisFieldQuery
1298+ { moreLikeThisFieldText :: Text
1299+ , moreLikeThisFieldFields :: FieldName
1300+ -- default 0.3 (30%)
1301+ , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1302+ , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1303+ , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1304+ , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1305+ , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1306+ , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1307+ , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1308+ , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1309+ , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1310+ , moreLikeThisFieldBoost :: Maybe Boost
1311+ , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1312+ } deriving (Eq, Read, Show, Generic, Typeable)
1314+data MoreLikeThisQuery =
1316+ { moreLikeThisText :: Text
1317+ , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1318+ -- default 0.3 (30%)
1319+ , moreLikeThisPercentMatch :: Maybe PercentMatch
1320+ , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1321+ , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1322+ , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1323+ , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1324+ , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1325+ , moreLikeThisMinWordLength :: Maybe MinWordLength
1326+ , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1327+ , moreLikeThisBoostTerms :: Maybe BoostTerms
1328+ , moreLikeThisBoost :: Maybe Boost
1329+ , moreLikeThisAnalyzer :: Maybe Analyzer
1330+ } deriving (Eq, Read, Show, Generic, Typeable)
1334+ { indicesQueryIndices :: [IndexName]
1335+ , indicesQuery :: Query
1337+ , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1339+data HasParentQuery =
1341+ { hasParentQueryType :: TypeName
1342+ , hasParentQuery :: Query
1343+ , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1345+data HasChildQuery =
1347+ { hasChildQueryType :: TypeName
1348+ , hasChildQuery :: Query
1349+ , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1355+ | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1358+ FuzzyQuery { fuzzyQueryField :: FieldName
1359+ , fuzzyQueryValue :: Text
1360+ , fuzzyQueryPrefixLength :: PrefixLength
1361+ , fuzzyQueryMaxExpansions :: MaxExpansions
1362+ , fuzzyQueryFuzziness :: Fuzziness
1363+ , fuzzyQueryBoost :: Maybe Boost
1364+ } deriving (Eq, Read, Show, Generic, Typeable)
1366+data FuzzyLikeFieldQuery =
1367+ FuzzyLikeFieldQuery
1368+ { fuzzyLikeField :: FieldName
1369+ -- anaphora is good for the soul.
1370+ , fuzzyLikeFieldText :: Text
1371+ , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1372+ , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1373+ , fuzzyLikeFieldFuzziness :: Fuzziness
1374+ , fuzzyLikeFieldPrefixLength :: PrefixLength
1375+ , fuzzyLikeFieldBoost :: Boost
1376+ , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1377+ } deriving (Eq, Read, Show, Generic, Typeable)
1379+data FuzzyLikeThisQuery =
1381+ { fuzzyLikeFields :: [FieldName]
1382+ , fuzzyLikeText :: Text
1383+ , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1384+ , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1385+ , fuzzyLikeFuzziness :: Fuzziness
1386+ , fuzzyLikePrefixLength :: PrefixLength
1387+ , fuzzyLikeBoost :: Boost
1388+ , fuzzyLikeAnalyzer :: Maybe Analyzer
1389+ } deriving (Eq, Read, Show, Generic, Typeable)
1391+data FilteredQuery =
1393+ { filteredQuery :: Query
1394+ , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1397+ DisMaxQuery { disMaxQueries :: [Query]
1399+ , disMaxTiebreaker :: Tiebreaker
1400+ , disMaxBoost :: Maybe Boost
1401+ } deriving (Eq, Read, Show, Generic, Typeable)
1404+ MatchQuery { matchQueryField :: FieldName
1405+ , matchQueryQueryString :: QueryString
1406+ , matchQueryOperator :: BooleanOperator
1407+ , matchQueryZeroTerms :: ZeroTermsQuery
1408+ , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1409+ , matchQueryMatchType :: Maybe MatchQueryType
1410+ , matchQueryAnalyzer :: Maybe Analyzer
1411+ , matchQueryMaxExpansions :: Maybe MaxExpansions
1412+ , matchQueryLenient :: Maybe Lenient
1413+ , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1415+{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1416+ enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1418+mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1419+mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1421+data MatchQueryType =
1423+ | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1425+data MultiMatchQuery =
1426+ MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1427+ , multiMatchQueryString :: QueryString
1428+ , multiMatchQueryOperator :: BooleanOperator
1429+ , multiMatchQueryZeroTerms :: ZeroTermsQuery
1430+ , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1431+ , multiMatchQueryType :: Maybe MultiMatchQueryType
1432+ , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1433+ , multiMatchQueryAnalyzer :: Maybe Analyzer
1434+ , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1435+ , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1437+{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1438+ enabling you to provide only the list of 'FieldName's and 'QueryString' to
1439+ make a 'MultiMatchQuery'.
1442+mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1443+mkMultiMatchQuery matchFields query =
1444+ MultiMatchQuery matchFields query
1445+ Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1447+data MultiMatchQueryType =
1448+ MultiMatchBestFields
1449+ | MultiMatchMostFields
1450+ | MultiMatchCrossFields
1452+ | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1455+ BoolQuery { boolQueryMustMatch :: [Query]
1456+ , boolQueryMustNotMatch :: [Query]
1457+ , boolQueryShouldMatch :: [Query]
1458+ , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1459+ , boolQueryBoost :: Maybe Boost
1460+ , boolQueryDisableCoord :: Maybe DisableCoord
1461+ } deriving (Eq, Read, Show, Generic, Typeable)
1463+mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1464+mkBoolQuery must mustNot should =
1465+ BoolQuery must mustNot should Nothing Nothing Nothing
1467+data BoostingQuery =
1468+ BoostingQuery { positiveQuery :: Query
1469+ , negativeQuery :: Query
1470+ , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1472+data CommonTermsQuery =
1473+ CommonTermsQuery { commonField :: FieldName
1474+ , commonQuery :: QueryString
1475+ , commonCutoffFrequency :: CutoffFrequency
1476+ , commonLowFreqOperator :: BooleanOperator
1477+ , commonHighFreqOperator :: BooleanOperator
1478+ , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1479+ , commonBoost :: Maybe Boost
1480+ , commonAnalyzer :: Maybe Analyzer
1481+ , commonDisableCoord :: Maybe DisableCoord
1482+ } deriving (Eq, Read, Show, Generic, Typeable)
1484+data CommonMinimumMatch =
1485+ CommonMinimumMatchHighLow MinimumMatchHighLow
1486+ | CommonMinimumMatch MinimumMatch
1487+ deriving (Eq, Read, Show, Generic, Typeable)
1489+data MinimumMatchHighLow =
1490+ MinimumMatchHighLow { lowFreq :: MinimumMatch
1491+ , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1493+data Filter = AndFilter [Filter] Cache
1494+ | OrFilter [Filter] Cache
1495+ | NotFilter Filter Cache
1497+ | BoolFilter BoolMatch
1498+ | ExistsFilter FieldName -- always cached
1499+ | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1500+ | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1501+ | GeoDistanceRangeFilter GeoPoint DistanceRange
1502+ | GeoPolygonFilter FieldName [LatLon]
1503+ | IdsFilter MappingName [DocId]
1505+ | MissingFilter FieldName Existence NullValue
1506+ | PrefixFilter FieldName PrefixValue Cache
1507+ | QueryFilter Query Cache
1508+ | RangeFilter FieldName RangeValue RangeExecution Cache
1509+ | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1510+ | TermFilter Term Cache
1511+ deriving (Eq, Read, Show, Generic, Typeable)
1513+data ZeroTermsQuery = ZeroTermsNone
1514+ | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1516+data RangeExecution = RangeExecutionIndex
1517+ | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1519+newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1521+data RegexpFlags = AllRegexpFlags
1523+ | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1525+data RegexpFlag = AnyString
1530+ | Interval deriving (Eq, Read, Show, Generic, Typeable)
1532+newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1533+newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1534+newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1535+newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1537+newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1538+newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1539+newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1540+newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1542+data RangeValue = RangeDateLte LessThanEqD
1543+ | RangeDateLt LessThanD
1544+ | RangeDateGte GreaterThanEqD
1545+ | RangeDateGt GreaterThanD
1546+ | RangeDateGtLt GreaterThanD LessThanD
1547+ | RangeDateGteLte GreaterThanEqD LessThanEqD
1548+ | RangeDateGteLt GreaterThanEqD LessThanD
1549+ | RangeDateGtLte GreaterThanD LessThanEqD
1550+ | RangeDoubleLte LessThanEq
1551+ | RangeDoubleLt LessThan
1552+ | RangeDoubleGte GreaterThanEq
1553+ | RangeDoubleGt GreaterThan
1554+ | RangeDoubleGtLt GreaterThan LessThan
1555+ | RangeDoubleGteLte GreaterThanEq LessThanEq
1556+ | RangeDoubleGteLt GreaterThanEq LessThan
1557+ | RangeDoubleGtLte GreaterThan LessThanEq
1558+ deriving (Eq, Read, Show, Generic, Typeable)
1560+rangeValueToPair :: RangeValue -> [Pair]
1561+rangeValueToPair rv = case rv of
1562+ RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1563+ RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1564+ RangeDateLt (LessThanD t) -> ["lt" .= t]
1565+ RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1566+ RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1567+ RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1568+ RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1569+ RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1570+ RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1571+ RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1572+ RangeDoubleLt (LessThan t) -> ["lt" .= t]
1573+ RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1574+ RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1575+ RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1576+ RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1577+ RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1579+data Term = Term { termField :: Text
1580+ , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1582+data BoolMatch = MustMatch Term Cache
1583+ | MustNotMatch Term Cache
1584+ | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1586+-- "memory" or "indexed"
1587+data GeoFilterType = GeoFilterMemory
1588+ | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1590+data LatLon = LatLon { lat :: Double
1591+ , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1593+data GeoBoundingBox =
1594+ GeoBoundingBox { topLeft :: LatLon
1595+ , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1597+data GeoBoundingBoxConstraint =
1598+ GeoBoundingBoxConstraint { geoBBField :: FieldName
1599+ , constraintBox :: GeoBoundingBox
1600+ , bbConstraintcache :: Cache
1601+ , geoType :: GeoFilterType
1602+ } deriving (Eq, Read, Show, Generic, Typeable)
1605+ GeoPoint { geoField :: FieldName
1606+ , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
1608+data DistanceUnit = Miles
1616+ | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
1618+data DistanceType = Arc
1619+ | SloppyArc -- doesn't exist <1.0
1620+ | Plane deriving (Eq, Read, Show, Generic, Typeable)
1622+data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1623+ | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
1626+ Distance { coefficient :: Double
1627+ , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1629+data DistanceRange =
1630+ DistanceRange { distanceFrom :: Distance
1631+ , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
1633+data SearchResult a =
1634+ SearchResult { took :: Int
1636+ , shards :: ShardResult
1637+ , searchHits :: SearchHits a
1638+ , aggregations :: Maybe AggregationResults
1639+ , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
1641+newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
1643+type Score = Maybe Double
1646+ SearchHits { hitsTotal :: Int
1647+ , maxScore :: Score
1648+ , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1651+instance Monoid (SearchHits a) where
1652+ mempty = SearchHits 0 Nothing mempty
1653+ mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1654+ SearchHits (ta + tb) (max ma mb) (ha <> hb)
1658+ Hit { hitIndex :: IndexName
1659+ , hitType :: MappingName
1660+ , hitDocId :: DocId
1661+ , hitScore :: Score
1662+ , hitSource :: Maybe a
1663+ , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1666+ ShardResult { shardTotal :: Int
1667+ , shardsSuccessful :: Int
1668+ , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1670+type HitHighlight = M.Map Text [Text]
1672+showText :: Show a => a -> Text
1673+showText = T.pack . show
1675+readMay :: Read a => String -> Maybe a
1676+readMay s = case reads s of
1677+ (a, ""):_ -> Just a
1680+parseReadText :: Read a => Text -> Parser a
1681+parseReadText = maybe mzero return . readMay . T.unpack
1683+type Aggregations = M.Map Text Aggregation
1685+emptyAggregations :: Aggregations
1686+emptyAggregations = M.empty
1688+mkAggregations :: Text -> Aggregation -> Aggregations
1689+mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1691+data TermOrder = TermOrder{ termSortField :: Text
1692+ , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1694+data TermInclusion = TermInclusion Text
1695+ | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1697+data CollectionMode = BreadthFirst
1698+ | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1700+data ExecutionHint = Ordinals
1702+ | GlobalOrdinalsHash
1703+ | GlobalOrdinalsLowCardinality
1704+ | Map deriving (Eq, Read, Show, Generic, Typeable)
1706+data TimeInterval = Weeks
1710+ | Seconds deriving Eq
1712+data Interval = Year
1720+ | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1722+data Aggregation = TermsAgg TermsAggregation
1723+ | CardinalityAgg CardinalityAggregation
1724+ | DateHistogramAgg DateHistogramAggregation
1725+ | ValueCountAgg ValueCountAggregation
1726+ | FilterAgg FilterAggregation
1727+ | DateRangeAgg DateRangeAggregation
1728+ | MissingAgg MissingAggregation
1729+ | TopHitsAgg TopHitsAggregation
1730+ deriving (Eq, Read, Show, Generic, Typeable)
1732+data TopHitsAggregation = TopHitsAggregation
1733+ { taFrom :: Maybe From
1734+ , taSize :: Maybe Size
1735+ , taSort :: Maybe Sort
1736+ } deriving (Eq, Read, Show)
1738+data MissingAggregation = MissingAggregation
1740+ } deriving (Eq, Read, Show, Generic, Typeable)
1742+data TermsAggregation = TermsAggregation { term :: Either Text Text
1743+ , termInclude :: Maybe TermInclusion
1744+ , termExclude :: Maybe TermInclusion
1745+ , termOrder :: Maybe TermOrder
1746+ , termMinDocCount :: Maybe Int
1747+ , termSize :: Maybe Int
1748+ , termShardSize :: Maybe Int
1749+ , termCollectMode :: Maybe CollectionMode
1750+ , termExecutionHint :: Maybe ExecutionHint
1751+ , termAggs :: Maybe Aggregations
1752+ } deriving (Eq, Read, Show, Generic, Typeable)
1754+data CardinalityAggregation = CardinalityAggregation { cardinalityField :: FieldName,
1755+ precisionThreshold :: Maybe Int
1756+ } deriving (Eq, Read, Show, Generic, Typeable)
1758+data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1759+ , dateInterval :: Interval
1760+ , dateFormat :: Maybe Text
1761+ -- pre and post deprecated in 1.5
1762+ , datePreZone :: Maybe Text
1763+ , datePostZone :: Maybe Text
1764+ , datePreOffset :: Maybe Text
1765+ , datePostOffset :: Maybe Text
1766+ , dateAggs :: Maybe Aggregations
1767+ } deriving (Eq, Read, Show, Generic, Typeable)
1770+data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1771+ , draFormat :: Maybe Text
1772+ , draRanges :: NonEmpty DateRangeAggRange
1773+ } deriving (Eq, Read, Show, Generic, Typeable)
1775+data DateRangeAggRange = DateRangeFrom DateMathExpr
1776+ | DateRangeTo DateMathExpr
1777+ | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1779+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1780+data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1783+-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1784+data DateMathAnchor = DMNow
1785+ | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1787+data DateMathModifier = AddTime Int DateMathUnit
1788+ | SubtractTime Int DateMathUnit
1789+ | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1791+data DateMathUnit = DMYear
1797+ | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1799+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1800+data ValueCountAggregation = FieldValueCount FieldName
1801+ | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1803+-- | 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.
1804+data FilterAggregation = FilterAggregation { faFilter :: Filter
1805+ , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1807+mkTermsAggregation :: Text -> TermsAggregation
1808+mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1810+mkTermsScriptAggregation :: Text -> TermsAggregation
1811+mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1813+mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1814+mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1816+mkCardinalityAggregation :: FieldName -> CardinalityAggregation
1817+mkCardinalityAggregation t = CardinalityAggregation t Nothing
1819+instance ToJSON Version where
1820+ toJSON Version {..} = object ["number" .= number
1821+ ,"build_hash" .= build_hash
1822+ ,"build_timestamp" .= build_timestamp
1823+ ,"build_snapshot" .= build_snapshot
1824+ ,"lucene_version" .= lucene_version]
1826+instance FromJSON Version where
1827+ parseJSON = withObject "Version" parse
1828+ where parse o = Version
1830+ <*> o .: "build_hash"
1831+ <*> o .: "build_timestamp"
1832+ <*> o .: "build_snapshot"
1833+ <*> o .: "lucene_version"
1835+instance ToJSON VersionNumber where
1836+ toJSON = toJSON . Vers.showVersion . versionNumber
1838+instance FromJSON VersionNumber where
1839+ parseJSON = withText "VersionNumber" (parse . T.unpack)
1841+ parse s = case filter (null . snd)(RP.readP_to_S Vers.parseVersion s) of
1842+ [(v, _)] -> pure (VersionNumber v)
1843+ [] -> fail ("Invalid version string " ++ s)
1844+ xs -> fail ("Ambiguous version string " ++ s ++ " (" ++ intercalate ", " (Vers.showVersion . fst <$> xs) ++ ")")
1846+instance ToJSON TermOrder where
1847+ toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1849+instance ToJSON TermInclusion where
1850+ toJSON (TermInclusion x) = toJSON x
1851+ toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1854+instance ToJSON CollectionMode where
1855+ toJSON BreadthFirst = "breadth_first"
1856+ toJSON DepthFirst = "depth_first"
1858+instance ToJSON ExecutionHint where
1859+ toJSON Ordinals = "ordinals"
1860+ toJSON GlobalOrdinals = "global_ordinals"
1861+ toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1862+ toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1865+instance ToJSON Interval where
1866+ toJSON Year = "year"
1867+ toJSON Quarter = "quarter"
1868+ toJSON Month = "month"
1869+ toJSON Week = "week"
1871+ toJSON Hour = "hour"
1872+ toJSON Minute = "minute"
1873+ toJSON Second = "second"
1874+ toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1876+instance Show TimeInterval where
1883+instance Read TimeInterval where
1884+ readPrec = f =<< TR.get
1886+ f 'w' = return Weeks
1887+ f 'd' = return Days
1888+ f 'h' = return Hours
1889+ f 'm' = return Minutes
1890+ f 's' = return Seconds
1891+ f _ = fail "TimeInterval expected one of w, d, h, m, s"
1893+instance ToJSON Aggregation where
1894+ toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1895+ omitNulls ["terms" .= omitNulls [ toJSON' term,
1896+ "include" .= include,
1897+ "exclude" .= exclude,
1899+ "min_doc_count" .= minDocCount,
1901+ "shard_size" .= shardSize,
1902+ "collect_mode" .= collectMode,
1903+ "execution_hint" .= executionHint
1905+ "aggs" .= termAggs ]
1907+ toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1909+ toJSON (CardinalityAgg (CardinalityAggregation field precisionThreshold)) =
1910+ object ["cardinality" .= omitNulls [ "field" .= field,
1911+ "precisionThreshold" .= precisionThreshold
1915+ toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1916+ omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1917+ "interval" .= interval,
1918+ "format" .= format,
1919+ "pre_zone" .= preZone,
1920+ "post_zone" .= postZone,
1921+ "pre_offset" .= preOffset,
1922+ "post_offset" .= postOffset
1924+ "aggs" .= dateHistoAggs ]
1925+ toJSON (ValueCountAgg a) = object ["value_count" .= v]
1926+ where v = case a of
1927+ (FieldValueCount (FieldName n)) -> object ["field" .= n]
1928+ (ScriptValueCount (Script s)) -> object ["script" .= s]
1929+ toJSON (FilterAgg (FilterAggregation filt ags)) =
1930+ omitNulls [ "filter" .= filt
1932+ toJSON (DateRangeAgg a) = object [ "date_range" .= a
1934+ toJSON (MissingAgg (MissingAggregation{..})) =
1935+ object ["missing" .= object ["field" .= maField]]
1937+ toJSON (TopHitsAgg (TopHitsAggregation mfrom msize msort)) =
1938+ omitNulls ["top_hits" .= omitNulls [ "size" .= msize
1944+instance ToJSON DateRangeAggregation where
1945+ toJSON DateRangeAggregation {..} =
1946+ omitNulls [ "field" .= draField
1947+ , "format" .= draFormat
1948+ , "ranges" .= toList draRanges
1951+instance ToJSON DateRangeAggRange where
1952+ toJSON (DateRangeFrom e) = object [ "from" .= e ]
1953+ toJSON (DateRangeTo e) = object [ "to" .= e ]
1954+ toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1956+instance ToJSON DateMathExpr where
1957+ toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1958+ where fmtA DMNow = "now"
1959+ fmtA (DMDate date) = (T.pack $ showGregorian date) <> "||"
1960+ fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1961+ fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1962+ fmtMod (RoundDownTo u) = "/" <> fmtU u
1968+ fmtU DMMinute = "m"
1969+ fmtU DMSecond = "s"
1972+type AggregationResults = M.Map Text Value
1974+class BucketAggregation a where
1975+ key :: a -> BucketValue
1976+ docCount :: a -> Int
1977+ aggs :: a -> Maybe AggregationResults
1980+data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1982+data BucketValue = TextValue Text
1983+ | ScientificValue Scientific
1984+ | BoolValue Bool deriving (Read, Show)
1986+data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1988+data TopHitResult a = TopHitResult { tarHits :: (SearchHits a)
1991+data TermsResult = TermsResult { termKey :: BucketValue
1992+ , termsDocCount :: Int
1993+ , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1995+data DateHistogramResult = DateHistogramResult { dateKey :: Int
1996+ , dateKeyStr :: Maybe Text
1997+ , dateDocCount :: Int
1998+ , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
2000+data DateRangeResult = DateRangeResult { dateRangeKey :: Text
2001+ , dateRangeFrom :: Maybe UTCTime
2002+ , dateRangeFromAsString :: Maybe Text
2003+ , dateRangeTo :: Maybe UTCTime
2004+ , dateRangeToAsString :: Maybe Text
2005+ , dateRangeDocCount :: Int
2006+ , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
2008+toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
2009+toTerms = toAggResult
2011+toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
2012+toDateHistogram = toAggResult
2014+toMissing :: Text -> AggregationResults -> Maybe MissingResult
2015+toMissing = toAggResult
2017+toTopHits :: (FromJSON a) => Text -> AggregationResults -> Maybe (TopHitResult a)
2018+toTopHits = toAggResult
2020+toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
2021+toAggResult t a = M.lookup t a >>= deserialize
2022+ where deserialize = parseMaybe parseJSON
2024+instance BucketAggregation TermsResult where
2026+ docCount = termsDocCount
2029+instance BucketAggregation DateHistogramResult where
2030+ key = TextValue . showText . dateKey
2031+ docCount = dateDocCount
2032+ aggs = dateHistogramAggs
2034+instance BucketAggregation DateRangeResult where
2035+ key = TextValue . dateRangeKey
2036+ docCount = dateRangeDocCount
2037+ aggs = dateRangeAggs
2039+instance (FromJSON a) => FromJSON (Bucket a) where
2040+ parseJSON (Object v) = Bucket <$>
2042+ parseJSON _ = mempty
2044+instance FromJSON BucketValue where
2045+ parseJSON (String t) = return $ TextValue t
2046+ parseJSON (Number s) = return $ ScientificValue s
2047+ parseJSON (Bool b) = return $ BoolValue b
2048+ parseJSON _ = mempty
2050+instance FromJSON MissingResult where
2051+ parseJSON = withObject "MissingResult" parse
2052+ where parse v = MissingResult <$> v .: "doc_count"
2054+instance FromJSON TermsResult where
2055+ parseJSON (Object v) = TermsResult <$>
2057+ v .: "doc_count" <*>
2058+ (pure $ getNamedSubAgg v ["key", "doc_count"])
2059+ parseJSON _ = mempty
2061+instance FromJSON DateHistogramResult where
2062+ parseJSON (Object v) = DateHistogramResult <$>
2064+ v .:? "key_as_string" <*>
2065+ v .: "doc_count" <*>
2066+ (pure $ getNamedSubAgg v [ "key"
2071+ parseJSON _ = mempty
2073+instance FromJSON DateRangeResult where
2074+ parseJSON = withObject "DateRangeResult" parse
2075+ where parse v = DateRangeResult <$>
2077+ (fmap posixMS <$> v .:? "from") <*>
2078+ v .:? "from_as_string" <*>
2079+ (fmap posixMS <$> v .:? "to") <*>
2080+ v .:? "to_as_string" <*>
2081+ v .: "doc_count" <*>
2082+ (pure $ getNamedSubAgg v [ "key"
2091+instance FromJSON POSIXMS where
2092+ parseJSON = withScientific "POSIXMS" (return . parse)
2093+ where parse n = let n' = truncate n :: Integer
2094+ in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
2096+instance (FromJSON a) => FromJSON (TopHitResult a) where
2097+ parseJSON (Object v) = TopHitResult <$>
2099+ parseJSON _ = fail "Failure in FromJSON (TopHitResult a)"
2101+instance Monoid Filter where
2102+ mempty = IdentityFilter
2103+ mappend a b = AndFilter [a, b] defaultCache
2105+instance Seminearring Filter where
2106+ a <||> b = OrFilter [a, b] defaultCache
2108+instance ToJSON Filter where
2109+ toJSON (AndFilter filters cache) =
2111+ object [ "filters" .= fmap toJSON filters
2112+ , "_cache" .= cache]]
2114+ toJSON (OrFilter filters cache) =
2116+ object [ "filters" .= fmap toJSON filters
2117+ , "_cache" .= cache]]
2119+ toJSON (NotFilter notFilter cache) =
2121+ object ["filter" .= notFilter
2122+ , "_cache" .= cache]]
2124+ toJSON (IdentityFilter) =
2125+ object ["match_all" .= object []]
2127+ toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
2128+ object ["term" .= object base]
2129+ where base = [termFilterField .= termFilterValue,
2132+ toJSON (ExistsFilter (FieldName fieldName)) =
2133+ object ["exists" .= object
2134+ ["field" .= fieldName]]
2136+ toJSON (BoolFilter boolMatch) =
2137+ object ["bool" .= boolMatch]
2139+ toJSON (GeoBoundingBoxFilter bbConstraint) =
2140+ object ["geo_bounding_box" .= bbConstraint]
2142+ toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2143+ distance distanceType optimizeBbox cache) =
2144+ object ["geo_distance" .=
2145+ object ["distance" .= distance
2146+ , "distance_type" .= distanceType
2147+ , "optimize_bbox" .= optimizeBbox
2148+ , distanceGeoField .= geoDistLatLon
2149+ , "_cache" .= cache]]
2151+ toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2152+ (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2153+ object ["geo_distance_range" .=
2154+ object ["from" .= geoDistRangeDistFrom
2155+ , "to" .= drDistanceTo
2156+ , gddrField .= drLatLon]]
2158+ toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2159+ object ["geo_polygon" .=
2160+ object [geoPolygonFilterField .=
2161+ object ["points" .= fmap toJSON latLons]]]
2163+ toJSON (IdsFilter (MappingName mappingName) values) =
2165+ object ["type" .= mappingName
2166+ , "values" .= fmap unpackId values]]
2168+ toJSON (LimitFilter limit) =
2169+ object ["limit" .= object ["value" .= limit]]
2171+ toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2172+ object ["missing" .=
2173+ object ["field" .= fieldName
2174+ , "existence" .= existence
2175+ , "null_value" .= nullValue]]
2177+ toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2178+ object ["prefix" .=
2179+ object [fieldName .= fieldValue
2180+ , "_cache" .= cache]]
2182+ toJSON (QueryFilter query False) =
2183+ object ["query" .= toJSON query ]
2184+ toJSON (QueryFilter query True) =
2185+ object ["fquery" .=
2186+ object [ "query" .= toJSON query
2187+ , "_cache" .= True ]]
2189+ toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2191+ object [ fieldName .= object (rangeValueToPair rangeValue)
2192+ , "execution" .= rangeExecution
2193+ , "_cache" .= cache]]
2195+ toJSON (RegexpFilter (FieldName fieldName)
2196+ (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2197+ object ["regexp" .=
2198+ object [fieldName .=
2199+ object ["value" .= regexText
2200+ , "flags" .= flags]
2201+ , "_name" .= cacheName
2202+ , "_cache" .= cache
2203+ , "_cache_key" .= cacheKey]]
2205+instance FromJSON Filter where
2206+ parseJSON = withObject "Filter" parse
2207+ where parse o = andFilter `taggedWith` "and"
2208+ <|> orFilter `taggedWith` "or"
2209+ <|> notFilter `taggedWith` "not"
2210+ <|> identityFilter `taggedWith` "match_all"
2211+ <|> boolFilter `taggedWith` "bool"
2212+ <|> existsFilter `taggedWith` "exists"
2213+ <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2214+ <|> geoDistanceFilter `taggedWith` "geo_distance"
2215+ <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2216+ <|> geoPolygonFilter `taggedWith` "geo_polygon"
2217+ <|> idsFilter `taggedWith` "ids"
2218+ <|> limitFilter `taggedWith` "limit"
2219+ <|> missingFilter `taggedWith` "missing"
2220+ <|> prefixFilter `taggedWith` "prefix"
2221+ <|> queryFilter `taggedWith` "query"
2222+ <|> fqueryFilter `taggedWith` "fquery"
2223+ <|> rangeFilter `taggedWith` "range"
2224+ <|> regexpFilter `taggedWith` "regexp"
2225+ <|> termFilter `taggedWith` "term"
2226+ where taggedWith parser k = parser =<< o .: k
2227+ andFilter o = AndFilter <$> o .: "filters"
2228+ <*> o .:? "_cache" .!= defaultCache
2229+ orFilter o = OrFilter <$> o .: "filters"
2230+ <*> o .:? "_cache" .!= defaultCache
2231+ notFilter o = NotFilter <$> o .: "filter"
2232+ <*> o .: "_cache" .!= defaultCache
2233+ identityFilter :: Object -> Parser Filter
2235+ | HM.null m = pure IdentityFilter
2236+ | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2237+ boolFilter = pure . BoolFilter
2238+ existsFilter o = ExistsFilter <$> o .: "field"
2239+ geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2240+ geoDistanceFilter o = do
2241+ case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2243+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
2244+ GeoDistanceFilter gp <$> o .: "distance"
2245+ <*> o .: "distance_type"
2246+ <*> o .: "optimize_bbox"
2247+ <*> o .:? "_cache" .!= defaultCache
2248+ _ -> fail "Could not find GeoDistanceFilter field name"
2249+ geoDistanceRangeFilter o = do
2250+ case HM.toList (deleteSeveral ["from", "to"] o) of
2252+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
2253+ rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2254+ return (GeoDistanceRangeFilter gp rng)
2255+ _ -> fail "Could not find GeoDistanceRangeFilter field name"
2256+ geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2257+ idsFilter o = IdsFilter <$> o .: "type"
2259+ limitFilter o = LimitFilter <$> o .: "value"
2260+ missingFilter o = MissingFilter <$> o .: "field"
2261+ <*> o .: "existence"
2262+ <*> o .: "null_value"
2263+ prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2264+ [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2265+ _ -> fail "Could not parse PrefixFilter"
2267+ queryFilter q = pure (QueryFilter q False)
2268+ fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2269+ rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2270+ [(fn, v)] -> RangeFilter (FieldName fn)
2272+ <*> o .: "execution"
2273+ <*> o .:? "_cache" .!= defaultCache
2274+ _ -> fail "Could not find field name for RangeFilter"
2275+ regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2276+ [(fn, Object o')] -> RegexpFilter (FieldName fn)
2280+ <*> o .:? "_cache" .!= defaultCache
2281+ <*> o .: "_cache_key"
2282+ _ -> fail "Could not find field name for RegexpFilter"
2283+ termFilter o = case HM.toList (HM.delete "_cache" o) of
2284+ [(termField, String termVal)] -> TermFilter (Term termField termVal)
2285+ <$> o .:? "_cache" .!= defaultCache
2286+ _ -> fail "Could not find term field for TermFilter"
2288+fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2289+fieldTagged f o = case HM.toList o of
2290+ [(k, Object o')] -> f (FieldName k) o'
2291+ _ -> fail "Expected object with 1 field-named key"
2293+-- Try to get an AggregationResults when we don't know the
2294+-- field name. We filter out the known keys to try to minimize the noise.
2295+getNamedSubAgg :: Object -> [Text] -> Maybe AggregationResults
2296+getNamedSubAgg o knownKeys = maggRes
2297+ where unknownKeys = HM.filterWithKey (\k _ -> k `notElem` knownKeys) o
2299+ | HM.null unknownKeys = Nothing
2300+ | otherwise = Just . M.fromList $ HM.toList unknownKeys
2302+instance ToJSON GeoPoint where
2303+ toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2304+ object [ geoPointField .= geoPointLatLon ]
2307+instance ToJSON Query where
2308+ toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2310+ object [termQueryField .= object merged]]
2312+ base = [ "value" .= termQueryValue ]
2313+ boosted = maybe [] (return . ("boost" .=)) boost
2314+ merged = mappend base boosted
2316+ toJSON (TermsQuery fieldName terms) =
2317+ object [ "terms" .= object conjoined ]
2318+ where conjoined = [fieldName .= terms]
2320+ toJSON (IdsQuery idsQueryMappingName docIds) =
2321+ object [ "ids" .= object conjoined ]
2322+ where conjoined = [ "type" .= idsQueryMappingName
2323+ , "values" .= fmap toJSON docIds ]
2325+ toJSON (QueryQueryStringQuery qQueryStringQuery) =
2326+ object [ "query_string" .= qQueryStringQuery ]
2328+ toJSON (QueryMatchQuery matchQuery) =
2329+ object [ "match" .= matchQuery ]
2331+ toJSON (QueryMultiMatchQuery multiMatchQuery) =
2332+ toJSON multiMatchQuery
2334+ toJSON (QueryBoolQuery boolQuery) =
2335+ object [ "bool" .= boolQuery ]
2337+ toJSON (QueryBoostingQuery boostingQuery) =
2338+ object [ "boosting" .= boostingQuery ]
2340+ toJSON (QueryCommonTermsQuery commonTermsQuery) =
2341+ object [ "common" .= commonTermsQuery ]
2343+ toJSON (ConstantScoreFilter csFilter boost) =
2344+ object ["constant_score" .= object ["filter" .= csFilter
2345+ , "boost" .= boost]]
2347+ toJSON (ConstantScoreQuery query boost) =
2348+ object ["constant_score" .= object ["query" .= query
2349+ , "boost" .= boost]]
2351+ toJSON (QueryDisMaxQuery disMaxQuery) =
2352+ object [ "dis_max" .= disMaxQuery ]
2354+ toJSON (QueryFilteredQuery qFilteredQuery) =
2355+ object [ "filtered" .= qFilteredQuery ]
2357+ toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2358+ object [ "fuzzy_like_this" .= fuzzyQuery ]
2360+ toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2361+ object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2363+ toJSON (QueryFuzzyQuery fuzzyQuery) =
2364+ object [ "fuzzy" .= fuzzyQuery ]
2366+ toJSON (QueryHasChildQuery childQuery) =
2367+ object [ "has_child" .= childQuery ]
2369+ toJSON (QueryHasParentQuery parentQuery) =
2370+ object [ "has_parent" .= parentQuery ]
2372+ toJSON (QueryIndicesQuery qIndicesQuery) =
2373+ object [ "indices" .= qIndicesQuery ]
2375+ toJSON (MatchAllQuery boost) =
2376+ object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2378+ toJSON (QueryMoreLikeThisQuery query) =
2379+ object [ "more_like_this" .= query ]
2381+ toJSON (QueryMoreLikeThisFieldQuery query) =
2382+ object [ "more_like_this_field" .= query ]
2384+ toJSON (QueryNestedQuery query) =
2385+ object [ "nested" .= query ]
2387+ toJSON (QueryPrefixQuery query) =
2388+ object [ "prefix" .= query ]
2390+ toJSON (QueryRangeQuery query) =
2391+ object [ "range" .= query ]
2393+ toJSON (QueryRegexpQuery query) =
2394+ object [ "regexp" .= query ]
2396+ toJSON (QuerySimpleQueryStringQuery query) =
2397+ object [ "simple_query_string" .= query ]
2399+instance FromJSON Query where
2400+ parseJSON v = withObject "Query" parse v
2401+ where parse o = termQuery `taggedWith` "term"
2402+ <|> termsQuery `taggedWith` "terms"
2403+ <|> idsQuery `taggedWith` "ids"
2404+ <|> queryQueryStringQuery `taggedWith` "query_string"
2405+ <|> queryMatchQuery `taggedWith` "match"
2406+ <|> queryMultiMatchQuery
2407+ <|> queryBoolQuery `taggedWith` "bool"
2408+ <|> queryBoostingQuery `taggedWith` "boosting"
2409+ <|> queryCommonTermsQuery `taggedWith` "common"
2410+ <|> constantScoreFilter `taggedWith` "constant_score"
2411+ <|> constantScoreQuery `taggedWith` "constant_score"
2412+ <|> queryDisMaxQuery `taggedWith` "dis_max"
2413+ <|> queryFilteredQuery `taggedWith` "filtered"
2414+ <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2415+ <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2416+ <|> queryFuzzyQuery `taggedWith` "fuzzy"
2417+ <|> queryHasChildQuery `taggedWith` "has_child"
2418+ <|> queryHasParentQuery `taggedWith` "has_parent"
2419+ <|> queryIndicesQuery `taggedWith` "indices"
2420+ <|> matchAllQuery `taggedWith` "match_all"
2421+ <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2422+ <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2423+ <|> queryNestedQuery `taggedWith` "nested"
2424+ <|> queryPrefixQuery `taggedWith` "prefix"
2425+ <|> queryRangeQuery `taggedWith` "range"
2426+ <|> queryRegexpQuery `taggedWith` "regexp"
2427+ <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2428+ where taggedWith parser k = parser =<< o .: k
2429+ termQuery = fieldTagged $ \(FieldName fn) o ->
2430+ TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2431+ termsQuery o = case HM.toList o of
2432+ [(fn, vs)] -> do vals <- parseJSON vs
2434+ x:xs -> return (TermsQuery fn (x :| xs))
2435+ _ -> fail "Expected non empty list of values"
2436+ _ -> fail "Expected object with 1 field-named key"
2437+ idsQuery o = IdsQuery <$> o .: "type"
2439+ queryQueryStringQuery = pure . QueryQueryStringQuery
2440+ queryMatchQuery = pure . QueryMatchQuery
2441+ queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2442+ queryBoolQuery = pure . QueryBoolQuery
2443+ queryBoostingQuery = pure . QueryBoostingQuery
2444+ queryCommonTermsQuery = pure . QueryCommonTermsQuery
2445+ constantScoreFilter o = case HM.lookup "filter" o of
2446+ Just x -> ConstantScoreFilter <$> parseJSON x
2448+ _ -> fail "Does not appear to be a ConstantScoreFilter"
2449+ constantScoreQuery o = case HM.lookup "query" o of
2450+ Just x -> ConstantScoreQuery <$> parseJSON x
2452+ _ -> fail "Does not appear to be a ConstantScoreQuery"
2453+ queryDisMaxQuery = pure . QueryDisMaxQuery
2454+ queryFilteredQuery = pure . QueryFilteredQuery
2455+ queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2456+ queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2457+ queryFuzzyQuery = pure . QueryFuzzyQuery
2458+ queryHasChildQuery = pure . QueryHasChildQuery
2459+ queryHasParentQuery = pure . QueryHasParentQuery
2460+ queryIndicesQuery = pure . QueryIndicesQuery
2461+ matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2462+ queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2463+ queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2464+ queryNestedQuery = pure . QueryNestedQuery
2465+ queryPrefixQuery = pure . QueryPrefixQuery
2466+ queryRangeQuery = pure . QueryRangeQuery
2467+ queryRegexpQuery = pure . QueryRegexpQuery
2468+ querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2471+omitNulls :: [(Text, Value)] -> Value
2472+omitNulls = object . filter notNull where
2473+ notNull (_, Null) = False
2474+ notNull (_, Array a) = (not . V.null) a
2478+instance ToJSON SimpleQueryStringQuery where
2479+ toJSON SimpleQueryStringQuery {..} =
2480+ omitNulls (base ++ maybeAdd)
2481+ where base = [ "query" .= simpleQueryStringQuery ]
2482+ maybeAdd = [ "fields" .= simpleQueryStringField
2483+ , "default_operator" .= simpleQueryStringOperator
2484+ , "analyzer" .= simpleQueryStringAnalyzer
2485+ , "flags" .= simpleQueryStringFlags
2486+ , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2487+ , "locale" .= simpleQueryStringLocale ]
2489+instance FromJSON SimpleQueryStringQuery where
2490+ parseJSON = withObject "SimpleQueryStringQuery" parse
2491+ where parse o = SimpleQueryStringQuery <$> o .: "query"
2493+ <*> o .:? "default_operator"
2494+ <*> o .:? "analyzer"
2495+ <*> (parseFlags <$> o .:? "flags")
2496+ <*> o .:? "lowercase_expanded_terms"
2498+ parseFlags (Just (x:xs)) = Just (x :| xs)
2499+ parseFlags _ = Nothing
2501+instance ToJSON FieldOrFields where
2502+ toJSON (FofField fieldName) =
2504+ toJSON (FofFields fieldNames) =
2507+instance FromJSON FieldOrFields where
2508+ parseJSON v = FofField <$> parseJSON v
2509+ <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2511+instance ToJSON SimpleQueryFlag where
2512+ toJSON SimpleQueryAll = "ALL"
2513+ toJSON SimpleQueryNone = "NONE"
2514+ toJSON SimpleQueryAnd = "AND"
2515+ toJSON SimpleQueryOr = "OR"
2516+ toJSON SimpleQueryPrefix = "PREFIX"
2517+ toJSON SimpleQueryPhrase = "PHRASE"
2518+ toJSON SimpleQueryPrecedence = "PRECEDENCE"
2519+ toJSON SimpleQueryEscape = "ESCAPE"
2520+ toJSON SimpleQueryWhitespace = "WHITESPACE"
2521+ toJSON SimpleQueryFuzzy = "FUZZY"
2522+ toJSON SimpleQueryNear = "NEAR"
2523+ toJSON SimpleQuerySlop = "SLOP"
2525+instance FromJSON SimpleQueryFlag where
2526+ parseJSON = withText "SimpleQueryFlag" parse
2527+ where parse "ALL" = pure SimpleQueryAll
2528+ parse "NONE" = pure SimpleQueryNone
2529+ parse "AND" = pure SimpleQueryAnd
2530+ parse "OR" = pure SimpleQueryOr
2531+ parse "PREFIX" = pure SimpleQueryPrefix
2532+ parse "PHRASE" = pure SimpleQueryPhrase
2533+ parse "PRECEDENCE" = pure SimpleQueryPrecedence
2534+ parse "ESCAPE" = pure SimpleQueryEscape
2535+ parse "WHITESPACE" = pure SimpleQueryWhitespace
2536+ parse "FUZZY" = pure SimpleQueryFuzzy
2537+ parse "NEAR" = pure SimpleQueryNear
2538+ parse "SLOP" = pure SimpleQuerySlop
2539+ parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2541+instance ToJSON RegexpQuery where
2542+ toJSON (RegexpQuery (FieldName rqQueryField)
2543+ (Regexp regexpQueryQuery) rqQueryFlags
2545+ object [ rqQueryField .= omitNulls base ]
2546+ where base = [ "value" .= regexpQueryQuery
2547+ , "flags" .= rqQueryFlags
2548+ , "boost" .= rqQueryBoost ]
2550+instance FromJSON RegexpQuery where
2551+ parseJSON = withObject "RegexpQuery" parse
2552+ where parse = fieldTagged $ \fn o ->
2558+instance ToJSON QueryStringQuery where
2559+ toJSON (QueryStringQuery qsQueryString
2560+ qsDefaultField qsOperator
2561+ qsAnalyzer qsAllowWildcard
2562+ qsLowercaseExpanded qsEnablePositionIncrements
2563+ qsFuzzyMaxExpansions qsFuzziness
2564+ qsFuzzyPrefixLength qsPhraseSlop
2565+ qsBoost qsAnalyzeWildcard
2566+ qsGeneratePhraseQueries qsMinimumShouldMatch
2567+ qsLenient qsLocale) =
2570+ base = [ "query" .= qsQueryString
2571+ , "default_field" .= qsDefaultField
2572+ , "default_operator" .= qsOperator
2573+ , "analyzer" .= qsAnalyzer
2574+ , "allow_leading_wildcard" .= qsAllowWildcard
2575+ , "lowercase_expanded_terms" .= qsLowercaseExpanded
2576+ , "enable_position_increments" .= qsEnablePositionIncrements
2577+ , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2578+ , "fuzziness" .= qsFuzziness
2579+ , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2580+ , "phrase_slop" .= qsPhraseSlop
2581+ , "boost" .= qsBoost
2582+ , "analyze_wildcard" .= qsAnalyzeWildcard
2583+ , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2584+ , "minimum_should_match" .= qsMinimumShouldMatch
2585+ , "lenient" .= qsLenient
2586+ , "locale" .= qsLocale ]
2588+instance FromJSON QueryStringQuery where
2589+ parseJSON = withObject "QueryStringQuery" parse
2590+ where parse o = QueryStringQuery
2592+ <*> o .:? "default_field"
2593+ <*> o .:? "default_operator"
2594+ <*> o .:? "analyzer"
2595+ <*> o .:? "allow_leading_wildcard"
2596+ <*> o .:? "lowercase_expanded_terms"
2597+ <*> o .:? "enable_position_increments"
2598+ <*> o .:? "fuzzy_max_expansions"
2599+ <*> o .:? "fuzziness"
2600+ <*> o .:? "fuzzy_prefix_length"
2601+ <*> o .:? "phrase_slop"
2603+ <*> o .:? "analyze_wildcard"
2604+ <*> o .:? "auto_generate_phrase_queries"
2605+ <*> o .:? "minimum_should_match"
2606+ <*> o .:? "lenient"
2609+instance ToJSON RangeQuery where
2610+ toJSON (RangeQuery (FieldName fieldName) range boost) =
2611+ object [ fieldName .= object conjoined ]
2612+ where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2614+instance FromJSON RangeQuery where
2615+ parseJSON = withObject "RangeQuery" parse
2616+ where parse = fieldTagged $ \fn o ->
2618+ <$> parseJSON (Object o)
2621+instance FromJSON RangeValue where
2622+ parseJSON = withObject "RangeValue" parse
2623+ where parse o = parseDate o
2625+ parseDate o = do lt <- o .:? "lt"
2629+ case (lt, lte, gt, gte) of
2630+ (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2631+ (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2632+ (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2633+ (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2634+ (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2635+ (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2636+ (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2637+ (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2638+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2639+ parseDouble o = do lt <- o .:? "lt"
2643+ case (lt, lte, gt, gte) of
2644+ (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2645+ (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2646+ (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2647+ (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2648+ (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2649+ (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2650+ (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2651+ (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2652+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2654+instance ToJSON PrefixQuery where
2655+ toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2656+ object [ fieldName .= omitNulls base ]
2657+ where base = [ "value" .= queryValue
2658+ , "boost" .= boost ]
2660+instance FromJSON PrefixQuery where
2661+ parseJSON = withObject "PrefixQuery" parse
2662+ where parse = fieldTagged $ \fn o ->
2667+instance ToJSON NestedQuery where
2668+ toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2669+ object [ "path" .= nqPath
2670+ , "score_mode" .= nqScoreType
2671+ , "query" .= nqQuery ]
2673+instance FromJSON NestedQuery where
2674+ parseJSON = withObject "NestedQuery" parse
2675+ where parse o = NestedQuery
2677+ <*> o .: "score_mode"
2680+instance ToJSON MoreLikeThisFieldQuery where
2681+ toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2682+ percent mtf mqt stopwords mindf maxdf
2683+ minwl maxwl boostTerms boost analyzer) =
2684+ object [ fieldName .= omitNulls base ]
2685+ where base = [ "like_text" .= text
2686+ , "percent_terms_to_match" .= percent
2687+ , "min_term_freq" .= mtf
2688+ , "max_query_terms" .= mqt
2689+ , "stop_words" .= stopwords
2690+ , "min_doc_freq" .= mindf
2691+ , "max_doc_freq" .= maxdf
2692+ , "min_word_length" .= minwl
2693+ , "max_word_length" .= maxwl
2694+ , "boost_terms" .= boostTerms
2696+ , "analyzer" .= analyzer ]
2698+instance FromJSON MoreLikeThisFieldQuery where
2699+ parseJSON = withObject "MoreLikeThisFieldQuery" parse
2700+ where parse = fieldTagged $ \fn o ->
2701+ MoreLikeThisFieldQuery
2702+ <$> o .: "like_text"
2704+ <*> o .:? "percent_terms_to_match"
2705+ <*> o .:? "min_term_freq"
2706+ <*> o .:? "max_query_terms"
2707+ -- <*> (optionalNE =<< o .:? "stop_words")
2708+ <*> o .:? "stop_words"
2709+ <*> o .:? "min_doc_freq"
2710+ <*> o .:? "max_doc_freq"
2711+ <*> o .:? "min_word_length"
2712+ <*> o .:? "max_word_length"
2713+ <*> o .:? "boost_terms"
2715+ <*> o .:? "analyzer"
2716+ -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2718+instance ToJSON MoreLikeThisQuery where
2719+ toJSON (MoreLikeThisQuery text fields percent
2720+ mtf mqt stopwords mindf maxdf
2721+ minwl maxwl boostTerms boost analyzer) =
2723+ where base = [ "like_text" .= text
2724+ , "fields" .= fields
2725+ , "percent_terms_to_match" .= percent
2726+ , "min_term_freq" .= mtf
2727+ , "max_query_terms" .= mqt
2728+ , "stop_words" .= stopwords
2729+ , "min_doc_freq" .= mindf
2730+ , "max_doc_freq" .= maxdf
2731+ , "min_word_length" .= minwl
2732+ , "max_word_length" .= maxwl
2733+ , "boost_terms" .= boostTerms
2735+ , "analyzer" .= analyzer ]
2737+instance FromJSON MoreLikeThisQuery where
2738+ parseJSON = withObject "MoreLikeThisQuery" parse
2739+ where parse o = MoreLikeThisQuery
2740+ <$> o .: "like_text"
2741+ -- <*> (optionalNE =<< o .:? "fields")
2743+ <*> o .:? "percent_terms_to_match"
2744+ <*> o .:? "min_term_freq"
2745+ <*> o .:? "max_query_terms"
2746+ -- <*> (optionalNE =<< o .:? "stop_words")
2747+ <*> o .:? "stop_words"
2748+ <*> o .:? "min_doc_freq"
2749+ <*> o .:? "max_doc_freq"
2750+ <*> o .:? "min_word_length"
2751+ <*> o .:? "max_word_length"
2752+ <*> o .:? "boost_terms"
2754+ <*> o .:? "analyzer"
2755+ -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2757+instance ToJSON IndicesQuery where
2758+ toJSON (IndicesQuery indices query noMatch) =
2759+ omitNulls [ "indices" .= indices
2760+ , "no_match_query" .= noMatch
2761+ , "query" .= query ]
2763+instance FromJSON IndicesQuery where
2764+ parseJSON = withObject "IndicesQuery" parse
2765+ where parse o = IndicesQuery
2766+ <$> o .:? "indices" .!= []
2768+ <*> o .:? "no_match_query"
2770+instance ToJSON HasParentQuery where
2771+ toJSON (HasParentQuery queryType query scoreType) =
2772+ omitNulls [ "parent_type" .= queryType
2773+ , "score_type" .= scoreType
2774+ , "query" .= query ]
2776+instance FromJSON HasParentQuery where
2777+ parseJSON = withObject "HasParentQuery" parse
2778+ where parse o = HasParentQuery
2779+ <$> o .: "parent_type"
2781+ <*> o .:? "score_type"
2783+instance ToJSON HasChildQuery where
2784+ toJSON (HasChildQuery queryType query scoreType) =
2785+ omitNulls [ "query" .= query
2786+ , "score_type" .= scoreType
2787+ , "type" .= queryType ]
2789+instance FromJSON HasChildQuery where
2790+ parseJSON = withObject "HasChildQuery" parse
2791+ where parse o = HasChildQuery
2794+ <*> o .:? "score_type"
2796+instance ToJSON FuzzyQuery where
2797+ toJSON (FuzzyQuery (FieldName fieldName) queryText
2798+ prefixLength maxEx fuzziness boost) =
2799+ object [ fieldName .= omitNulls base ]
2800+ where base = [ "value" .= queryText
2801+ , "fuzziness" .= fuzziness
2802+ , "prefix_length" .= prefixLength
2804+ , "max_expansions" .= maxEx ]
2806+instance FromJSON FuzzyQuery where
2807+ parseJSON = withObject "FuzzyQuery" parse
2808+ where parse = fieldTagged $ \fn o ->
2811+ <*> o .: "prefix_length"
2812+ <*> o .: "max_expansions"
2813+ <*> o .: "fuzziness"
2816+instance ToJSON FuzzyLikeFieldQuery where
2817+ toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2818+ fieldText maxTerms ignoreFreq fuzziness prefixLength
2820+ object [ fieldName .=
2821+ omitNulls [ "like_text" .= fieldText
2822+ , "max_query_terms" .= maxTerms
2823+ , "ignore_tf" .= ignoreFreq
2824+ , "fuzziness" .= fuzziness
2825+ , "prefix_length" .= prefixLength
2826+ , "analyzer" .= analyzer
2827+ , "boost" .= boost ]]
2829+instance FromJSON FuzzyLikeFieldQuery where
2830+ parseJSON = withObject "FuzzyLikeFieldQuery" parse
2831+ where parse = fieldTagged $ \fn o ->
2832+ FuzzyLikeFieldQuery fn
2833+ <$> o .: "like_text"
2834+ <*> o .: "max_query_terms"
2835+ <*> o .: "ignore_tf"
2836+ <*> o .: "fuzziness"
2837+ <*> o .: "prefix_length"
2839+ <*> o .:? "analyzer"
2841+instance ToJSON FuzzyLikeThisQuery where
2842+ toJSON (FuzzyLikeThisQuery fields text maxTerms
2843+ ignoreFreq fuzziness prefixLength boost analyzer) =
2845+ where base = [ "fields" .= fields
2846+ , "like_text" .= text
2847+ , "max_query_terms" .= maxTerms
2848+ , "ignore_tf" .= ignoreFreq
2849+ , "fuzziness" .= fuzziness
2850+ , "prefix_length" .= prefixLength
2851+ , "analyzer" .= analyzer
2852+ , "boost" .= boost ]
2854+instance FromJSON FuzzyLikeThisQuery where
2855+ parseJSON = withObject "FuzzyLikeThisQuery" parse
2856+ where parse o = FuzzyLikeThisQuery
2857+ <$> o .:? "fields" .!= []
2858+ <*> o .: "like_text"
2859+ <*> o .: "max_query_terms"
2860+ <*> o .: "ignore_tf"
2861+ <*> o .: "fuzziness"
2862+ <*> o .: "prefix_length"
2864+ <*> o .:? "analyzer"
2866+instance ToJSON FilteredQuery where
2867+ toJSON (FilteredQuery query fFilter) =
2868+ object [ "query" .= query
2869+ , "filter" .= fFilter ]
2871+instance FromJSON FilteredQuery where
2872+ parseJSON = withObject "FilteredQuery" parse
2873+ where parse o = FilteredQuery
2877+instance ToJSON DisMaxQuery where
2878+ toJSON (DisMaxQuery queries tiebreaker boost) =
2880+ where base = [ "queries" .= queries
2882+ , "tie_breaker" .= tiebreaker ]
2884+instance FromJSON DisMaxQuery where
2885+ parseJSON = withObject "DisMaxQuery" parse
2886+ where parse o = DisMaxQuery
2887+ <$> o .:? "queries" .!= []
2888+ <*> o .: "tie_breaker"
2891+instance ToJSON CommonTermsQuery where
2892+ toJSON (CommonTermsQuery (FieldName fieldName)
2893+ (QueryString query) cf lfo hfo msm
2894+ boost analyzer disableCoord) =
2895+ object [fieldName .= omitNulls base ]
2896+ where base = [ "query" .= query
2897+ , "cutoff_frequency" .= cf
2898+ , "low_freq_operator" .= lfo
2899+ , "minimum_should_match" .= msm
2901+ , "analyzer" .= analyzer
2902+ , "disable_coord" .= disableCoord
2903+ , "high_freq_operator" .= hfo ]
2905+instance FromJSON CommonTermsQuery where
2906+ parseJSON = withObject "CommonTermsQuery" parse
2907+ where parse = fieldTagged $ \fn o ->
2908+ CommonTermsQuery fn
2910+ <*> o .: "cutoff_frequency"
2911+ <*> o .: "low_freq_operator"
2912+ <*> o .: "high_freq_operator"
2913+ <*> o .:? "minimum_should_match"
2915+ <*> o .:? "analyzer"
2916+ <*> o .:? "disable_coord"
2918+instance ToJSON CommonMinimumMatch where
2919+ toJSON (CommonMinimumMatch mm) = toJSON mm
2920+ toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2921+ object [ "low_freq" .= lowF
2922+ , "high_freq" .= highF ]
2924+instance FromJSON CommonMinimumMatch where
2925+ parseJSON v = parseMinimum v
2926+ <|> parseMinimumHighLow v
2927+ where parseMinimum = fmap CommonMinimumMatch . parseJSON
2928+ parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2929+ MinimumMatchHighLow
2930+ <$> o .: "low_freq"
2931+ <*> o .: "high_freq")
2934+instance ToJSON BoostingQuery where
2935+ toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2936+ object [ "positive" .= bqPositiveQuery
2937+ , "negative" .= bqNegativeQuery
2938+ , "negative_boost" .= bqNegativeBoost ]
2940+instance FromJSON BoostingQuery where
2941+ parseJSON = withObject "BoostingQuery" parse
2942+ where parse o = BoostingQuery
2943+ <$> o .: "positive"
2944+ <*> o .: "negative"
2945+ <*> o .: "negative_boost"
2947+instance ToJSON BoolQuery where
2948+ toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2950+ where base = [ "must" .= mustM
2951+ , "must_not" .= notM
2952+ , "should" .= shouldM
2953+ , "minimum_should_match" .= bqMin
2955+ , "disable_coord" .= disableCoord ]
2957+instance FromJSON BoolQuery where
2958+ parseJSON = withObject "BoolQuery" parse
2959+ where parse o = BoolQuery
2960+ <$> o .:? "must" .!= []
2961+ <*> o .:? "must_not" .!= []
2962+ <*> o .:? "should" .!= []
2963+ <*> o .:? "minimum_should_match"
2965+ <*> o .:? "disable_coord"
2967+instance ToJSON MatchQuery where
2968+ toJSON (MatchQuery (FieldName fieldName)
2969+ (QueryString mqQueryString) booleanOperator
2970+ zeroTermsQuery cutoffFrequency matchQueryType
2971+ analyzer maxExpansions lenient boost) =
2972+ object [ fieldName .= omitNulls base ]
2973+ where base = [ "query" .= mqQueryString
2974+ , "operator" .= booleanOperator
2975+ , "zero_terms_query" .= zeroTermsQuery
2976+ , "cutoff_frequency" .= cutoffFrequency
2977+ , "type" .= matchQueryType
2978+ , "analyzer" .= analyzer
2979+ , "max_expansions" .= maxExpansions
2980+ , "lenient" .= lenient
2981+ , "boost" .= boost ]
2983+instance FromJSON MatchQuery where
2984+ parseJSON = withObject "MatchQuery" parse
2985+ where parse = fieldTagged $ \fn o ->
2988+ <*> o .: "operator"
2989+ <*> o .: "zero_terms_query"
2990+ <*> o .:? "cutoff_frequency"
2992+ <*> o .:? "analyzer"
2993+ <*> o .:? "max_expansions"
2994+ <*> o .:? "lenient"
2997+instance ToJSON MultiMatchQuery where
2998+ toJSON (MultiMatchQuery fields (QueryString query) boolOp
2999+ ztQ tb mmqt cf analyzer maxEx lenient) =
3000+ object ["multi_match" .= omitNulls base]
3001+ where base = [ "fields" .= fmap toJSON fields
3003+ , "operator" .= boolOp
3004+ , "zero_terms_query" .= ztQ
3005+ , "tie_breaker" .= tb
3007+ , "cutoff_frequency" .= cf
3008+ , "analyzer" .= analyzer
3009+ , "max_expansions" .= maxEx
3010+ , "lenient" .= lenient ]
3012+instance FromJSON MultiMatchQuery where
3013+ parseJSON = withObject "MultiMatchQuery" parse
3014+ where parse raw = do o <- raw .: "multi_match"
3016+ <$> o .:? "fields" .!= []
3018+ <*> o .: "operator"
3019+ <*> o .: "zero_terms_query"
3020+ <*> o .:? "tie_breaker"
3022+ <*> o .:? "cutoff_frequency"
3023+ <*> o .:? "analyzer"
3024+ <*> o .:? "max_expansions"
3025+ <*> o .:? "lenient"
3027+instance ToJSON MultiMatchQueryType where
3028+ toJSON MultiMatchBestFields = "best_fields"
3029+ toJSON MultiMatchMostFields = "most_fields"
3030+ toJSON MultiMatchCrossFields = "cross_fields"
3031+ toJSON MultiMatchPhrase = "phrase"
3032+ toJSON MultiMatchPhrasePrefix = "phrase_prefix"
3034+instance FromJSON MultiMatchQueryType where
3035+ parseJSON = withText "MultiMatchPhrasePrefix" parse
3036+ where parse "best_fields" = pure MultiMatchBestFields
3037+ parse "most_fields" = pure MultiMatchMostFields
3038+ parse "cross_fields" = pure MultiMatchCrossFields
3039+ parse "phrase" = pure MultiMatchPhrase
3040+ parse "phrase_prefix" = pure MultiMatchPhrasePrefix
3041+ parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
3043+instance ToJSON BooleanOperator where
3044+ toJSON And = String "and"
3045+ toJSON Or = String "or"
3047+instance FromJSON BooleanOperator where
3048+ parseJSON = withText "BooleanOperator" parse
3049+ where parse "and" = pure And
3050+ parse "or" = pure Or
3051+ parse o = fail ("Unexpected BooleanOperator: " <> show o)
3053+instance ToJSON ZeroTermsQuery where
3054+ toJSON ZeroTermsNone = String "none"
3055+ toJSON ZeroTermsAll = String "all"
3057+instance FromJSON ZeroTermsQuery where
3058+ parseJSON = withText "ZeroTermsQuery" parse
3059+ where parse "none" = pure ZeroTermsNone
3060+ parse "all" = pure ZeroTermsAll
3061+ parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
3063+instance ToJSON MatchQueryType where
3064+ toJSON MatchPhrase = "phrase"
3065+ toJSON MatchPhrasePrefix = "phrase_prefix"
3067+instance FromJSON MatchQueryType where
3068+ parseJSON = withText "MatchQueryType" parse
3069+ where parse "phrase" = pure MatchPhrase
3070+ parse "phrase_prefix" = pure MatchPhrasePrefix
3071+ parse t = fail ("Unexpected MatchQueryType: " <> show t)
3073+instance FromJSON Status where
3074+ parseJSON (Object v) = Status <$>
3076+ (v .:? "status" .!= 200) <*>
3080+ parseJSON _ = empty
3083+instance ToJSON IndexSettings where
3084+ toJSON (IndexSettings s r) = object ["settings" .=
3086+ object ["number_of_shards" .= s, "number_of_replicas" .= r]
3090+instance FromJSON IndexSettings where
3091+ parseJSON = withObject "IndexSettings" parse
3092+ where parse o = do s <- o .: "settings"
3094+ IndexSettings <$> i .: "number_of_shards"
3095+ <*> i .: "number_of_replicas"
3097+instance ToJSON UpdatableIndexSetting where
3098+ toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
3099+ toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
3100+ toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
3101+ toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
3102+ toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
3103+ toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
3104+ toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
3105+ toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
3106+ toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
3107+ toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
3108+ toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
3109+ toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
3110+ toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
3111+ toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
3112+ toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
3113+ toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
3114+ toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
3115+ toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
3116+ toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
3117+ toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
3118+ toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
3119+ toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
3120+ toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
3121+ toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
3122+ toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
3123+ toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
3124+ toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
3125+ toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
3127+instance FromJSON UpdatableIndexSetting where
3128+ parseJSON = withObject "UpdatableIndexSetting" parse
3129+ where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
3130+ <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
3131+ <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
3132+ <|> indexConcurrency `taggedAt` ["index", "concurrency"]
3133+ <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
3134+ <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
3135+ <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
3136+ <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
3137+ <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
3138+ <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
3139+ <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
3140+ <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
3141+ <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
3142+ <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
3143+ <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
3144+ <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
3145+ <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
3146+ <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
3147+ <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
3148+ <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
3149+ <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
3150+ <|> compoundFormat `taggedAt` ["index", "compound_format"]
3151+ <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3152+ <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3153+ <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3154+ <|> blocksRead `taggedAt` ["blocks", "read"]
3155+ <|> blocksWrite `taggedAt` ["blocks", "write"]
3156+ <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3157+ where taggedAt f ks = taggedAt' f (Object o) ks
3158+ taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3159+ taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3160+ taggedAt' f v' ks) v
3161+ numberOfReplicas = pure . NumberOfReplicas
3162+ autoExpandReplicas = pure . AutoExpandReplicas
3163+ refreshInterval = pure . RefreshInterval . ndtJSON
3164+ indexConcurrency = pure . IndexConcurrency
3165+ failOnMergeFailure = pure . FailOnMergeFailure
3166+ translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3167+ translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3168+ translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3169+ translogDisableFlush = pure . TranslogDisableFlush
3170+ cacheFilterMaxSize = pure . CacheFilterMaxSize
3171+ cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3172+ gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3173+ routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3174+ routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3175+ routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3176+ routingAllocationEnable = pure . RoutingAllocationEnable
3177+ routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3178+ recoveryInitialShards = pure . RecoveryInitialShards
3179+ gcDeletes = pure . GCDeletes . ndtJSON
3180+ ttlDisablePurge = pure . TTLDisablePurge
3181+ translogFSType = pure . TranslogFSType
3182+ compoundFormat = pure . IndexCompoundFormat
3183+ compoundOnFlush = pure . IndexCompoundOnFlush
3184+ warmerEnabled = pure . WarmerEnabled
3185+ blocksReadOnly = pure . BlocksReadOnly
3186+ blocksRead = pure . BlocksRead
3187+ blocksWrite = pure . BlocksWrite
3188+ blocksMetaData = pure . BlocksMetaData
3190+instance FromJSON IndexSettingsSummary where
3191+ parseJSON = withObject "IndexSettingsSummary" parse
3192+ where parse o = case HM.toList o of
3193+ [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3195+ <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3196+ _ -> fail "Expected single-key object with index name"
3197+ redundant (NumberOfReplicas _) = True
3198+ redundant _ = False
3200+-- | For some reason in several settings APIs, all leaf values get returned
3201+-- as strings. This function attepmts to recover from this for all
3202+-- non-recursive JSON types. If nothing can be done, the value is left alone.
3203+unStringlyTypeJSON :: Value -> Value
3204+unStringlyTypeJSON (String "true") = Bool True
3205+unStringlyTypeJSON (String "false") = Bool False
3206+unStringlyTypeJSON (String "null") = Null
3207+unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3210+unStringlyTypeJSON v = v
3213+parseSettings :: Object -> Parser [UpdatableIndexSetting]
3214+parseSettings o = do
3216+ -- slice the index object into singleton hashmaps and try to parse each
3217+ parses <- forM (HM.toList o') $ \(k, v) -> do
3218+ -- blocks are now nested into the "index" key, which is not how they're serialized
3219+ let atRoot = Object (HM.singleton k v)
3220+ let atIndex = Object (HM.singleton "index" atRoot)
3221+ optional (parseJSON atRoot <|> parseJSON atIndex)
3222+ return (catMaybes parses)
3224+oPath :: ToJSON a => NonEmpty Text -> a -> Value
3225+oPath (k :| []) v = object [k .= v]
3226+oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3228+attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3229+attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3230+ | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3232+parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3233+parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3234+ where parse o = case HM.toList o of
3235+ [] -> fail "Expected non-empty list of NodeAttrFilters"
3236+ x:xs -> DT.mapM (uncurry parse') (x :| xs)
3237+ parse' n = withText "Text" $ \t ->
3238+ case T.splitOn "," t of
3239+ fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3240+ [] -> fail "Expected non-empty list of filter values"
3242+instance ToJSON ReplicaBounds where
3243+ toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3244+ toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3245+ toJSON ReplicasUnbounded = Bool False
3247+instance FromJSON ReplicaBounds where
3248+ parseJSON v = withText "ReplicaBounds" parseText v
3249+ <|> withBool "ReplicaBounds" parseBool v
3250+ where parseText t = case T.splitOn "-" t of
3251+ [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3252+ [a, b] -> ReplicasBounded <$> parseReadText a
3253+ <*> parseReadText b
3254+ _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3255+ parseBool False = pure ReplicasUnbounded
3256+ parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3258+instance ToJSON AllocationPolicy where
3259+ toJSON AllocAll = String "all"
3260+ toJSON AllocPrimaries = String "primaries"
3261+ toJSON AllocNewPrimaries = String "new_primaries"
3262+ toJSON AllocNone = String "none"
3264+instance FromJSON AllocationPolicy where
3265+ parseJSON = withText "AllocationPolicy" parse
3266+ where parse "all" = pure AllocAll
3267+ parse "primaries" = pure AllocPrimaries
3268+ parse "new_primaries" = pure AllocNewPrimaries
3269+ parse "none" = pure AllocNone
3270+ parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3272+instance ToJSON InitialShardCount where
3273+ toJSON QuorumShards = String "quorum"
3274+ toJSON QuorumMinus1Shards = String "quorum-1"
3275+ toJSON FullShards = String "full"
3276+ toJSON FullMinus1Shards = String "full-1"
3277+ toJSON (ExplicitShards x) = toJSON x
3279+instance FromJSON InitialShardCount where
3280+ parseJSON v = withText "InitialShardCount" parseText v
3281+ <|> ExplicitShards <$> parseJSON v
3282+ where parseText "quorum" = pure QuorumShards
3283+ parseText "quorum-1" = pure QuorumMinus1Shards
3284+ parseText "full" = pure FullShards
3285+ parseText "full-1" = pure FullMinus1Shards
3286+ parseText _ = mzero
3288+instance ToJSON FSType where
3289+ toJSON FSSimple = "simple"
3290+ toJSON FSBuffered = "buffered"
3292+instance FromJSON FSType where
3293+ parseJSON = withText "FSType" parse
3294+ where parse "simple" = pure FSSimple
3295+ parse "buffered" = pure FSBuffered
3296+ parse t = fail ("Invalid FSType: " <> show t)
3298+instance ToJSON CompoundFormat where
3299+ toJSON (CompoundFileFormat x) = Bool x
3300+ toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3302+instance FromJSON CompoundFormat where
3303+ parseJSON v = CompoundFileFormat <$> parseJSON v
3304+ <|> MergeSegmentVsTotalIndex <$> parseJSON v
3306+instance ToJSON NominalDiffTimeJSON where
3307+ toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3309+instance FromJSON NominalDiffTimeJSON where
3310+ parseJSON = withText "NominalDiffTime" parse
3311+ where parse t = case T.takeEnd 1 t of
3312+ "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3313+ _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3315+instance ToJSON IndexTemplate where
3316+ toJSON (IndexTemplate p s m) = merge
3317+ (object [ "template" .= p
3318+ , "mappings" .= foldl' merge (object []) m
3322+ merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3324+ merge _ _ = undefined
3326+instance (FromJSON a) => FromJSON (EsResult a) where
3327+ parseJSON jsonVal@(Object v) = do
3328+ found <- v .:? "found" .!= False
3330+ then parseJSON jsonVal
3331+ else return Nothing
3332+ EsResult <$> v .: "_index" <*>
3336+ parseJSON _ = empty
3338+instance (FromJSON a) => FromJSON (EsResultFound a) where
3339+ parseJSON (Object v) = EsResultFound <$>
3340+ v .: "_version" <*>
3342+ parseJSON _ = empty
3344+instance FromJSON EsError where
3345+ parseJSON (Object v) = EsError <$>
3347+ (v .: "error" <|> (v .: "error" >>= (.: "reason")))
3348+ parseJSON _ = empty
3350+instance FromJSON IndexAliasesSummary where
3351+ parseJSON = withObject "IndexAliasesSummary" parse
3352+ where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3353+ go ixn = withObject "index aliases" $ \ia -> do
3354+ aliases <- ia .:? "aliases" .!= mempty
3355+ forM (HM.toList aliases) $ \(aName, v) -> do
3356+ let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3357+ IndexAliasSummary indexAlias <$> parseJSON v
3360+instance ToJSON IndexAliasAction where
3361+ toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3362+ where Object iaObj = toJSON ia
3363+ Object optsObj = toJSON opts
3364+ toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3365+ where Object iaObj = toJSON ia
3367+instance ToJSON IndexAlias where
3368+ toJSON IndexAlias {..} = object ["index" .= srcIndex
3369+ , "alias" .= indexAlias
3372+instance ToJSON IndexAliasCreate where
3373+ toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3374+ where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3375+ Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3377+instance ToJSON AliasRouting where
3378+ toJSON (AllAliasRouting v) = object ["routing" .= v]
3379+ toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3380+ where prs = [("search_routing" .=) <$> srch
3381+ ,("index_routing" .=) <$> idx]
3383+instance FromJSON AliasRouting where
3384+ parseJSON = withObject "AliasRouting" parse
3385+ where parse o = parseAll o <|> parseGranular o
3386+ parseAll o = AllAliasRouting <$> o .: "routing"
3387+ parseGranular o = do
3388+ sr <- o .:? "search_routing"
3389+ ir <- o .:? "index_routing"
3390+ if isNothing sr && isNothing ir
3391+ then fail "Both search_routing and index_routing can't be blank"
3392+ else return (GranularAliasRouting sr ir)
3394+instance FromJSON IndexAliasCreate where
3395+ parseJSON v = withObject "IndexAliasCreate" parse v
3396+ where parse o = IndexAliasCreate <$> optional (parseJSON v)
3399+instance ToJSON SearchAliasRouting where
3400+ toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3402+instance FromJSON SearchAliasRouting where
3403+ parseJSON = withText "SearchAliasRouting" parse
3404+ where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3406+instance ToJSON Search where
3407+ toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3408+ omitNulls [ "query" .= query
3409+ , "filter" .= sFilter
3411+ , "aggregations" .= searchAggs
3412+ , "highlight" .= highlight
3415+ , "track_scores" .= sTrackSortScores
3416+ , "fields" .= sFields
3417+ , "_source" .= sSource]
3420+instance ToJSON Source where
3421+ toJSON NoSource = toJSON False
3422+ toJSON (SourcePatterns patterns) = toJSON patterns
3423+ toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3425+instance ToJSON PatternOrPatterns where
3426+ toJSON (PopPattern pattern) = toJSON pattern
3427+ toJSON (PopPatterns patterns) = toJSON patterns
3429+instance ToJSON Include where
3430+ toJSON (Include patterns) = toJSON patterns
3432+instance ToJSON Exclude where
3433+ toJSON (Exclude patterns) = toJSON patterns
3435+instance ToJSON Pattern where
3436+ toJSON (Pattern pattern) = toJSON pattern
3439+instance ToJSON FieldHighlight where
3440+ toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3441+ object [ fName .= fSettings ]
3442+ toJSON (FieldHighlight (FieldName fName) Nothing) =
3443+ object [ fName .= emptyObject ]
3445+instance ToJSON Highlights where
3446+ toJSON (Highlights global fields) =
3447+ omitNulls (("fields" .= fields)
3448+ : highlightSettingsPairs global)
3450+instance ToJSON HighlightSettings where
3451+ toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3453+highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3454+highlightSettingsPairs Nothing = []
3455+highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3456+highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3457+highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3460+plainHighPairs :: Maybe PlainHighlight -> [Pair]
3461+plainHighPairs Nothing = []
3462+plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3463+ [ "type" .= String "plain"]
3464+ ++ commonHighlightPairs plCom
3465+ ++ nonPostingsToPairs plNonPost
3467+postHighPairs :: Maybe PostingsHighlight -> [Pair]
3468+postHighPairs Nothing = []
3469+postHighPairs (Just (PostingsHighlight pCom)) =
3470+ ("type" .= String "postings")
3471+ : commonHighlightPairs pCom
3473+fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3474+fastVectorHighPairs Nothing = []
3475+fastVectorHighPairs (Just
3476+ (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3477+ fvBoundMaxScan fvFragOff fvMatchedFields
3479+ [ "type" .= String "fvh"
3480+ , "boundary_chars" .= fvBoundChars
3481+ , "boundary_max_scan" .= fvBoundMaxScan
3482+ , "fragment_offset" .= fvFragOff
3483+ , "matched_fields" .= fvMatchedFields
3484+ , "phraseLimit" .= fvPhraseLim]
3485+ ++ commonHighlightPairs fvCom
3486+ ++ nonPostingsToPairs fvNonPostSettings
3488+deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3489+deleteSeveral ks hm = foldr HM.delete hm ks
3491+commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3492+commonHighlightPairs Nothing = []
3493+commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3494+ chNoMatchSize chHighlightQuery
3495+ chRequireFieldMatch)) =
3496+ [ "order" .= chScore
3497+ , "force_source" .= chForceSource
3498+ , "encoder" .= chEncoder
3499+ , "no_match_size" .= chNoMatchSize
3500+ , "highlight_query" .= chHighlightQuery
3501+ , "require_fieldMatch" .= chRequireFieldMatch]
3502+ ++ highlightTagToPairs chTag
3505+nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3506+nonPostingsToPairs Nothing = []
3507+nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3508+ [ "fragment_size" .= npFragSize
3509+ , "number_of_fragments" .= npNumOfFrags]
3511+parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3512+parseNEJSON [] = fail "Expected non-empty list"
3513+parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3516+instance ToJSON HighlightEncoder where
3517+ toJSON DefaultEncoder = String "default"
3518+ toJSON HTMLEncoder = String "html"
3520+highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3521+highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3522+highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3523+ , "post_tags" .= post]
3524+highlightTagToPairs Nothing = []
3526+instance ToJSON SortSpec where
3527+ toJSON (DefaultSortSpec
3528+ (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3529+ dsSortMode dsMissingSort dsNestedFilter)) =
3530+ object [dsSortFieldName .= omitNulls base] where
3531+ base = [ "order" .= dsSortOrder
3532+ , "ignore_unmapped" .= dsIgnoreUnmapped
3533+ , "mode" .= dsSortMode
3534+ , "missing" .= dsMissingSort
3535+ , "nested_filter" .= dsNestedFilter ]
3537+ toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3538+ object [ "unit" .= units
3539+ , field .= gdsLatLon
3540+ , "order" .= gdsSortOrder ]
3543+instance ToJSON SortOrder where
3544+ toJSON Ascending = String "asc"
3545+ toJSON Descending = String "desc"
3548+instance ToJSON SortMode where
3549+ toJSON SortMin = String "min"
3550+ toJSON SortMax = String "max"
3551+ toJSON SortSum = String "sum"
3552+ toJSON SortAvg = String "avg"
3555+instance ToJSON Missing where
3556+ toJSON LastMissing = String "_last"
3557+ toJSON FirstMissing = String "_first"
3558+ toJSON (CustomMissing txt) = String txt
3561+instance ToJSON ScoreType where
3562+ toJSON ScoreTypeMax = "max"
3563+ toJSON ScoreTypeAvg = "avg"
3564+ toJSON ScoreTypeSum = "sum"
3565+ toJSON ScoreTypeNone = "none"
3567+instance FromJSON ScoreType where
3568+ parseJSON = withText "ScoreType" parse
3569+ where parse "max" = pure ScoreTypeMax
3570+ parse "avg" = pure ScoreTypeAvg
3571+ parse "sum" = pure ScoreTypeSum
3572+ parse "none" = pure ScoreTypeNone
3573+ parse t = fail ("Unexpected ScoreType: " <> show t)
3575+instance ToJSON Distance where
3576+ toJSON (Distance dCoefficient dUnit) =
3577+ String boltedTogether where
3578+ coefText = showText dCoefficient
3579+ (String unitText) = toJSON dUnit
3580+ boltedTogether = mappend coefText unitText
3582+instance FromJSON Distance where
3583+ parseJSON = withText "Distance" parse
3584+ where parse t = Distance <$> parseCoeff nT
3585+ <*> parseJSON (String unitT)
3586+ where (nT, unitT) = T.span validForNumber t
3587+ -- may be a better way to do this
3588+ validForNumber '-' = True
3589+ validForNumber '.' = True
3590+ validForNumber 'e' = True
3591+ validForNumber c = isNumber c
3592+ parseCoeff "" = fail "Empty string cannot be parsed as number"
3593+ parseCoeff s = return (read (T.unpack s))
3595+instance ToJSON DistanceUnit where
3596+ toJSON Miles = String "mi"
3597+ toJSON Yards = String "yd"
3598+ toJSON Feet = String "ft"
3599+ toJSON Inches = String "in"
3600+ toJSON Kilometers = String "km"
3601+ toJSON Meters = String "m"
3602+ toJSON Centimeters = String "cm"
3603+ toJSON Millimeters = String "mm"
3604+ toJSON NauticalMiles = String "nmi"
3607+instance FromJSON DistanceUnit where
3608+ parseJSON = withText "DistanceUnit" parse
3609+ where parse "mi" = pure Miles
3610+ parse "yd" = pure Yards
3611+ parse "ft" = pure Feet
3612+ parse "in" = pure Inches
3613+ parse "km" = pure Kilometers
3614+ parse "m" = pure Meters
3615+ parse "cm" = pure Centimeters
3616+ parse "mm" = pure Millimeters
3617+ parse "nmi" = pure NauticalMiles
3618+ parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3620+instance ToJSON DistanceType where
3621+ toJSON Arc = String "arc"
3622+ toJSON SloppyArc = String "sloppy_arc"
3623+ toJSON Plane = String "plane"
3625+instance FromJSON DistanceType where
3626+ parseJSON = withText "DistanceType" parse
3627+ where parse "arc" = pure Arc
3628+ parse "sloppy_arc" = pure SloppyArc
3629+ parse "plane" = pure Plane
3630+ parse t = fail ("Unrecognized DistanceType: " <> show t)
3633+instance ToJSON OptimizeBbox where
3634+ toJSON NoOptimizeBbox = String "none"
3635+ toJSON (OptimizeGeoFilterType gft) = toJSON gft
3637+instance FromJSON OptimizeBbox where
3638+ parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3639+ <|> parseOptimize v
3640+ where parseNoOptimize "none" = pure NoOptimizeBbox
3641+ parseNoOptimize _ = mzero
3642+ parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3644+instance ToJSON GeoBoundingBoxConstraint where
3645+ toJSON (GeoBoundingBoxConstraint
3646+ (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3647+ object [gbbcGeoBBField .= gbbcConstraintBox
3648+ , "_cache" .= cache
3651+instance FromJSON GeoBoundingBoxConstraint where
3652+ parseJSON = withObject "GeoBoundingBoxConstraint" parse
3653+ where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3654+ [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3656+ <*> o .:? "_cache" .!= defaultCache
3658+ _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3660+instance ToJSON GeoFilterType where
3661+ toJSON GeoFilterMemory = String "memory"
3662+ toJSON GeoFilterIndexed = String "indexed"
3664+instance FromJSON GeoFilterType where
3665+ parseJSON = withText "GeoFilterType" parse
3666+ where parse "memory" = pure GeoFilterMemory
3667+ parse "indexed" = pure GeoFilterIndexed
3668+ parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3670+instance ToJSON GeoBoundingBox where
3671+ toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3672+ object ["top_left" .= gbbTopLeft
3673+ , "bottom_right" .= gbbBottomRight]
3675+instance FromJSON GeoBoundingBox where
3676+ parseJSON = withObject "GeoBoundingBox" parse
3677+ where parse o = GeoBoundingBox
3678+ <$> o .: "top_left"
3679+ <*> o .: "bottom_right"
3681+instance ToJSON LatLon where
3682+ toJSON (LatLon lLat lLon) =
3683+ object ["lat" .= lLat
3686+instance FromJSON LatLon where
3687+ parseJSON = withObject "LatLon" parse
3688+ where parse o = LatLon <$> o .: "lat"
3691+-- index for smaller ranges, fielddata for longer ranges
3692+instance ToJSON RangeExecution where
3693+ toJSON RangeExecutionIndex = "index"
3694+ toJSON RangeExecutionFielddata = "fielddata"
3697+instance FromJSON RangeExecution where
3698+ parseJSON = withText "RangeExecution" parse
3699+ where parse "index" = pure RangeExecutionIndex
3700+ parse "fielddata" = pure RangeExecutionFielddata
3701+ parse t = error ("Unrecognized RangeExecution " <> show t)
3703+instance ToJSON RegexpFlags where
3704+ toJSON AllRegexpFlags = String "ALL"
3705+ toJSON NoRegexpFlags = String "NONE"
3706+ toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3707+ where flagStrs = map flagStr . nub $ h:fs
3708+ flagStr AnyString = "ANYSTRING"
3709+ flagStr Automaton = "AUTOMATON"
3710+ flagStr Complement = "COMPLEMENT"
3711+ flagStr Empty = "EMPTY"
3712+ flagStr Intersection = "INTERSECTION"
3713+ flagStr Interval = "INTERVAL"
3715+instance FromJSON RegexpFlags where
3716+ parseJSON = withText "RegexpFlags" parse
3717+ where parse "ALL" = pure AllRegexpFlags
3718+ parse "NONE" = pure NoRegexpFlags
3719+ parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3721+instance FromJSON RegexpFlag where
3722+ parseJSON = withText "RegexpFlag" parse
3723+ where parse "ANYSTRING" = pure AnyString
3724+ parse "AUTOMATON" = pure Automaton
3725+ parse "COMPLEMENT" = pure Complement
3726+ parse "EMPTY" = pure Empty
3727+ parse "INTERSECTION" = pure Intersection
3728+ parse "INTERVAL" = pure Interval
3729+ parse f = fail ("Unknown RegexpFlag: " <> show f)
3731+instance ToJSON Term where
3732+ toJSON (Term field value) = object ["term" .= object
3735+instance FromJSON Term where
3736+ parseJSON = withObject "Term" parse
3737+ where parse o = do termObj <- o .: "term"
3738+ case HM.toList termObj of
3739+ [(fn, v)] -> Term fn <$> parseJSON v
3740+ _ -> fail "Expected object with 1 field-named key"
3742+instance ToJSON BoolMatch where
3743+ toJSON (MustMatch term cache) = object ["must" .= term,
3745+ toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3747+ toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3750+instance FromJSON BoolMatch where
3751+ parseJSON = withObject "BoolMatch" parse
3752+ where parse o = mustMatch `taggedWith` "must"
3753+ <|> mustNotMatch `taggedWith` "must_not"
3754+ <|> shouldMatch `taggedWith` "should"
3755+ where taggedWith parser k = parser =<< o .: k
3756+ mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3757+ mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3758+ shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3760+instance (FromJSON a) => FromJSON (SearchResult a) where
3761+ parseJSON (Object v) = SearchResult <$>
3763+ v .: "timed_out" <*>
3766+ v .:? "aggregations" <*>
3768+ parseJSON _ = empty
3770+instance (FromJSON a) => FromJSON (SearchHits a) where
3771+ parseJSON (Object v) = SearchHits <$>
3773+ v .: "max_score" <*>
3775+ parseJSON _ = empty
3777+instance (FromJSON a) => FromJSON (Hit a) where
3778+ parseJSON (Object v) = Hit <$>
3783+ v .:? "_source" <*>
3785+ parseJSON _ = empty
3787+instance FromJSON ShardResult where
3788+ parseJSON (Object v) = ShardResult <$>
3790+ v .: "successful" <*>
3792+ parseJSON _ = empty
3795+instance FromJSON DocVersion where
3798+ maybe (fail "DocVersion out of range") return $ mkDocVersion i
3800+-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3801+instance FromJSON ReplicaCount where
3802+ parseJSON v = parseAsInt v
3803+ <|> parseAsString v
3804+ where parseAsInt = fmap ReplicaCount . parseJSON
3805+ parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3807+instance FromJSON ShardCount where
3808+ parseJSON v = parseAsInt v
3809+ <|> parseAsString v
3810+ where parseAsInt = fmap ShardCount . parseJSON
3811+ parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3813+instance Bounded DocVersion where
3814+ minBound = DocVersion 1
3815+ maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3817+instance Enum DocVersion where
3819+ | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3820+ | otherwise = succError "DocVersion"
3822+ | x /= minBound = DocVersion (pred $ docVersionNumber x)
3823+ | otherwise = predError "DocVersion"
3825+ fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3826+ fromEnum = docVersionNumber
3827+ enumFrom = boundedEnumFrom
3828+ enumFromThen = boundedEnumFromThen
3830+-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3831+newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3833+-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3834+newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3837+data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3838+ | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3841+-- | Either specifies an exact repo name or one with globs in it,
3842+-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3843+data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3845+ deriving (Eq, Generic, Show, Typeable)
3847+-- | The unique name of a snapshot repository.
3848+newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3849+ deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3852+-- | A generic representation of a snapshot repo. This is what gets
3853+-- sent to and parsed from the server. For repo types enabled by
3854+-- plugins that aren't exported by this library, consider making a
3855+-- custom type which implements 'SnapshotRepo'. If it is a common repo
3856+-- type, consider submitting a pull request to have it included in the
3858+data GenericSnapshotRepo = GenericSnapshotRepo {
3859+ gSnapshotRepoName :: SnapshotRepoName
3860+ , gSnapshotRepoType :: SnapshotRepoType
3861+ , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3862+ } deriving (Eq, Generic, Show, Typeable)
3865+instance SnapshotRepo GenericSnapshotRepo where
3866+ toGSnapshotRepo = id
3867+ fromGSnapshotRepo = Right
3870+newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3871+ deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3874+-- | Opaque representation of snapshot repo settings. Instances of
3875+-- 'SnapshotRepo' will produce this.
3876+newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3877+ deriving (Eq, Generic, Show, Typeable, ToJSON)
3880+ -- Regardless of whether you send strongly typed json, my version of
3881+ -- ES sends back stringly typed json in the settings, e.g. booleans
3882+ -- as strings, so we'll try to convert them.
3883+instance FromJSON GenericSnapshotRepoSettings where
3884+ parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3886+-- | The result of running 'verifySnapshotRepo'.
3887+newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3888+ deriving (Eq, Generic, Show, Typeable)
3891+instance FromJSON SnapshotVerification where
3892+ parseJSON = withObject "SnapshotVerification" parse
3896+ SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3897+ parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3898+ SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3901+-- | A node that has verified a snapshot
3902+data SnapshotNodeVerification = SnapshotNodeVerification {
3903+ snvFullId :: FullNodeId
3904+ , snvNodeName :: NodeName
3905+ } deriving (Eq, Generic, Show, Typeable)
3908+-- | Unique, automatically-generated name assigned to nodes that are
3909+-- usually returned in node-oriented APIs.
3910+newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3911+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3914+-- | A human-readable node name that is supplied by the user in the
3915+-- node config or automatically generated by ElasticSearch.
3916+newtype NodeName = NodeName { nodeName :: Text }
3917+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3919+newtype ClusterName = ClusterName { clusterName :: Text }
3920+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3922+data NodesInfo = NodesInfo {
3923+ nodesInfo :: [NodeInfo]
3924+ , nodesClusterName :: ClusterName
3925+ } deriving (Eq, Show, Generic, Typeable)
3927+data NodesStats = NodesStats {
3928+ nodesStats :: [NodeStats]
3929+ , nodesStatsClusterName :: ClusterName
3930+ } deriving (Eq, Show, Generic, Typeable)
3932+data NodeStats = NodeStats {
3933+ nodeStatsName :: NodeName
3934+ , nodeStatsFullId :: FullNodeId
3935+ , nodeStatsBreakersStats :: Maybe NodeBreakersStats
3936+ , nodeStatsHTTP :: NodeHTTPStats
3937+ , nodeStatsTransport :: NodeTransportStats
3938+ , nodeStatsFS :: NodeFSStats
3939+ , nodeStatsNetwork :: NodeNetworkStats
3940+ , nodeStatsThreadPool :: NodeThreadPoolsStats
3941+ , nodeStatsJVM :: NodeJVMStats
3942+ , nodeStatsProcess :: NodeProcessStats
3943+ , nodeStatsOS :: NodeOSStats
3944+ , nodeStatsIndices :: NodeIndicesStats
3945+ } deriving (Eq, Show, Generic, Typeable)
3947+data NodeBreakersStats = NodeBreakersStats {
3948+ nodeStatsParentBreaker :: NodeBreakerStats
3949+ , nodeStatsRequestBreaker :: NodeBreakerStats
3950+ , nodeStatsFieldDataBreaker :: NodeBreakerStats
3951+ } deriving (Eq, Show, Generic, Typeable)
3953+data NodeBreakerStats = NodeBreakerStats {
3954+ nodeBreakersTripped :: Int
3955+ , nodeBreakersOverhead :: Double
3956+ , nodeBreakersEstSize :: Bytes
3957+ , nodeBreakersLimitSize :: Bytes
3958+ } deriving (Eq, Show, Generic, Typeable)
3960+data NodeHTTPStats = NodeHTTPStats {
3961+ nodeHTTPTotalOpened :: Int
3962+ , nodeHTTPCurrentOpen :: Int
3963+ } deriving (Eq, Show, Generic, Typeable)
3965+data NodeTransportStats = NodeTransportStats {
3966+ nodeTransportTXSize :: Bytes
3967+ , nodeTransportCount :: Int
3968+ , nodeTransportRXSize :: Bytes
3969+ , nodeTransportRXCount :: Int
3970+ , nodeTransportServerOpen :: Int
3971+ } deriving (Eq, Show, Generic, Typeable)
3973+data NodeFSStats = NodeFSStats {
3974+ nodeFSDataPaths :: [NodeDataPathStats]
3975+ , nodeFSTotal :: NodeFSTotalStats
3976+ , nodeFSTimestamp :: UTCTime
3977+ } deriving (Eq, Show, Generic, Typeable)
3979+data NodeDataPathStats = NodeDataPathStats {
3980+ nodeDataPathDiskServiceTime :: Maybe Double
3981+ , nodeDataPathDiskQueue :: Maybe Double
3982+ , nodeDataPathIOSize :: Maybe Bytes
3983+ , nodeDataPathWriteSize :: Maybe Bytes
3984+ , nodeDataPathReadSize :: Maybe Bytes
3985+ , nodeDataPathIOOps :: Maybe Int
3986+ , nodeDataPathWrites :: Maybe Int
3987+ , nodeDataPathReads :: Maybe Int
3988+ , nodeDataPathAvailable :: Bytes
3989+ , nodeDataPathFree :: Bytes
3990+ , nodeDataPathTotal :: Bytes
3991+ , nodeDataPathType :: Maybe Text
3992+ , nodeDataPathDevice :: Text
3993+ , nodeDataPathMount :: Text
3994+ , nodeDataPathPath :: Text
3995+ } deriving (Eq, Show, Generic, Typeable)
3997+data NodeFSTotalStats = NodeFSTotalStats {
3998+ nodeFSTotalDiskServiceTime :: Maybe Double
3999+ , nodeFSTotalDiskQueue :: Maybe Double
4000+ , nodeFSTotalIOSize :: Maybe Bytes
4001+ , nodeFSTotalWriteSize :: Maybe Bytes
4002+ , nodeFSTotalReadSize :: Maybe Bytes
4003+ , nodeFSTotalIOOps :: Maybe Int
4004+ , nodeFSTotalWrites :: Maybe Int
4005+ , nodeFSTotalReads :: Maybe Int
4006+ , nodeFSTotalAvailable :: Bytes
4007+ , nodeFSTotalFree :: Bytes
4008+ , nodeFSTotalTotal :: Bytes
4009+ } deriving (Eq, Show, Generic, Typeable)
4011+data NodeNetworkStats = NodeNetworkStats {
4012+ nodeNetTCPOutRSTs :: Int
4013+ , nodeNetTCPInErrs :: Int
4014+ , nodeNetTCPAttemptFails :: Int
4015+ , nodeNetTCPEstabResets :: Int
4016+ , nodeNetTCPRetransSegs :: Int
4017+ , nodeNetTCPOutSegs :: Int
4018+ , nodeNetTCPInSegs :: Int
4019+ , nodeNetTCPCurrEstab :: Int
4020+ , nodeNetTCPPassiveOpens :: Int
4021+ , nodeNetTCPActiveOpens :: Int
4022+ } deriving (Eq, Show, Generic, Typeable)
4024+data NodeThreadPoolsStats = NodeThreadPoolsStats {
4025+ nodeThreadPoolsStatsSnapshot :: NodeThreadPoolStats
4026+ , nodeThreadPoolsStatsBulk :: NodeThreadPoolStats
4027+ , nodeThreadPoolsStatsMerge :: NodeThreadPoolStats
4028+ , nodeThreadPoolsStatsGet :: NodeThreadPoolStats
4029+ , nodeThreadPoolsStatsManagement :: NodeThreadPoolStats
4030+ , nodeThreadPoolsStatsFetchShardStore :: Maybe NodeThreadPoolStats
4031+ , nodeThreadPoolsStatsOptimize :: NodeThreadPoolStats
4032+ , nodeThreadPoolsStatsFlush :: NodeThreadPoolStats
4033+ , nodeThreadPoolsStatsSearch :: NodeThreadPoolStats
4034+ , nodeThreadPoolsStatsWarmer :: NodeThreadPoolStats
4035+ , nodeThreadPoolsStatsGeneric :: NodeThreadPoolStats
4036+ , nodeThreadPoolsStatsSuggest :: NodeThreadPoolStats
4037+ , nodeThreadPoolsStatsRefresh :: NodeThreadPoolStats
4038+ , nodeThreadPoolsStatsIndex :: NodeThreadPoolStats
4039+ , nodeThreadPoolsStatsListener :: Maybe NodeThreadPoolStats
4040+ , nodeThreadPoolsStatsFetchShardStarted :: Maybe NodeThreadPoolStats
4041+ , nodeThreadPoolsStatsPercolate :: NodeThreadPoolStats
4042+ } deriving (Eq, Show, Generic, Typeable)
4044+data NodeThreadPoolStats = NodeThreadPoolStats {
4045+ nodeThreadPoolCompleted :: Int
4046+ , nodeThreadPoolLargest :: Int
4047+ , nodeThreadPoolRejected :: Int
4048+ , nodeThreadPoolActive :: Int
4049+ , nodeThreadPoolQueue :: Int
4050+ , nodeThreadPoolThreads :: Int
4051+ } deriving (Eq, Show, Generic, Typeable)
4053+data NodeJVMStats = NodeJVMStats {
4054+ nodeJVMStatsMappedBufferPool :: JVMBufferPoolStats
4055+ , nodeJVMStatsDirectBufferPool :: JVMBufferPoolStats
4056+ , nodeJVMStatsGCOldCollector :: JVMGCStats
4057+ , nodeJVMStatsGCYoungCollector :: JVMGCStats
4058+ , nodeJVMStatsPeakThreadsCount :: Int
4059+ , nodeJVMStatsThreadsCount :: Int
4060+ , nodeJVMStatsOldPool :: JVMPoolStats
4061+ , nodeJVMStatsSurvivorPool :: JVMPoolStats
4062+ , nodeJVMStatsYoungPool :: JVMPoolStats
4063+ , nodeJVMStatsNonHeapCommitted :: Bytes
4064+ , nodeJVMStatsNonHeapUsed :: Bytes
4065+ , nodeJVMStatsHeapMax :: Bytes
4066+ , nodeJVMStatsHeapCommitted :: Bytes
4067+ , nodeJVMStatsHeapUsedPercent :: Int
4068+ , nodeJVMStatsHeapUsed :: Bytes
4069+ , nodeJVMStatsUptime :: NominalDiffTime
4070+ , nodeJVMStatsTimestamp :: UTCTime
4071+ } deriving (Eq, Show, Generic, Typeable)
4073+data JVMBufferPoolStats = JVMBufferPoolStats {
4074+ jvmBufferPoolStatsTotalCapacity :: Bytes
4075+ , jvmBufferPoolStatsUsed :: Bytes
4076+ , jvmBufferPoolStatsCount :: Int
4077+ } deriving (Eq, Show, Generic, Typeable)
4079+data JVMGCStats = JVMGCStats {
4080+ jvmGCStatsCollectionTime :: NominalDiffTime
4081+ , jvmGCStatsCollectionCount :: Int
4082+ } deriving (Eq, Show, Generic, Typeable)
4084+data JVMPoolStats = JVMPoolStats {
4085+ jvmPoolStatsPeakMax :: Bytes
4086+ , jvmPoolStatsPeakUsed :: Bytes
4087+ , jvmPoolStatsMax :: Bytes
4088+ , jvmPoolStatsUsed :: Bytes
4089+ } deriving (Eq, Show, Generic, Typeable)
4091+data NodeProcessStats = NodeProcessStats {
4092+ nodeProcessMemTotalVirtual :: Bytes
4093+ , nodeProcessMemShare :: Bytes
4094+ , nodeProcessMemResident :: Bytes
4095+ , nodeProcessCPUTotal :: NominalDiffTime
4096+ , nodeProcessCPUUser :: NominalDiffTime
4097+ , nodeProcessCPUSys :: NominalDiffTime
4098+ , nodeProcessCPUPercent :: Int
4099+ , nodeProcessOpenFDs :: Int
4100+ , nodeProcessTimestamp :: UTCTime
4101+ } deriving (Eq, Show, Generic, Typeable)
4103+data NodeOSStats = NodeOSStats {
4104+ nodeOSSwapFree :: Bytes
4105+ , nodeOSSwapUsed :: Bytes
4106+ , nodeOSMemActualUsed :: Bytes
4107+ , nodeOSMemActualFree :: Bytes
4108+ , nodeOSMemUsedPercent :: Int
4109+ , nodeOSMemFreePercent :: Int
4110+ , nodeOSMemUsed :: Bytes
4111+ , nodeOSMemFree :: Bytes
4112+ , nodeOSCPUStolen :: Int
4113+ , nodeOSCPUUsage :: Int
4114+ , nodeOSCPUIdle :: Int
4115+ , nodeOSCPUUser :: Int
4116+ , nodeOSCPUSys :: Int
4117+ , nodeOSLoad :: Maybe LoadAvgs
4118+ , nodeOSUptime :: NominalDiffTime
4119+ , nodeOSTimestamp :: UTCTime
4120+ } deriving (Eq, Show, Generic, Typeable)
4122+data LoadAvgs = LoadAvgs {
4123+ loadAvg1Min :: Double
4124+ , loadAvg5Min :: Double
4125+ , loadAvg15Min :: Double
4126+ } deriving (Eq, Show, Generic, Typeable)
4128+data NodeIndicesStats = NodeIndicesStats {
4129+ nodeIndicesStatsRecoveryThrottleTime :: Maybe NominalDiffTime
4130+ , nodeIndicesStatsRecoveryCurrentAsTarget :: Maybe Int
4131+ , nodeIndicesStatsRecoveryCurrentAsSource :: Maybe Int
4132+ , nodeIndicesStatsQueryCacheMisses :: Maybe Int
4133+ , nodeIndicesStatsQueryCacheHits :: Maybe Int
4134+ , nodeIndicesStatsQueryCacheEvictions :: Maybe Int
4135+ , nodeIndicesStatsQueryCacheSize :: Maybe Bytes
4136+ , nodeIndicesStatsSuggestCurrent :: Int
4137+ , nodeIndicesStatsSuggestTime :: NominalDiffTime
4138+ , nodeIndicesStatsSuggestTotal :: Int
4139+ , nodeIndicesStatsTranslogSize :: Bytes
4140+ , nodeIndicesStatsTranslogOps :: Int
4141+ , nodeIndicesStatsSegFixedBitSetMemory :: Maybe Bytes
4142+ , nodeIndicesStatsSegVersionMapMemory :: Bytes
4143+ , nodeIndicesStatsSegIndexWriterMaxMemory :: Maybe Bytes
4144+ , nodeIndicesStatsSegIndexWriterMemory :: Bytes
4145+ , nodeIndicesStatsSegMemory :: Bytes
4146+ , nodeIndicesStatsSegCount :: Int
4147+ , nodeIndicesStatsCompletionSize :: Bytes
4148+ , nodeIndicesStatsPercolateQueries :: Int
4149+ , nodeIndicesStatsPercolateMemory :: Bytes
4150+ , nodeIndicesStatsPercolateCurrent :: Int
4151+ , nodeIndicesStatsPercolateTime :: NominalDiffTime
4152+ , nodeIndicesStatsPercolateTotal :: Int
4153+ , nodeIndicesStatsFieldDataEvictions :: Int
4154+ , nodeIndicesStatsFieldDataMemory :: Bytes
4155+ , nodeIndicesStatsIDCacheMemory :: Bytes
4156+ , nodeIndicesStatsFilterCacheEvictions :: Int
4157+ , nodeIndicesStatsFilterCacheMemory :: Bytes
4158+ , nodeIndicesStatsWarmerTotalTime :: NominalDiffTime
4159+ , nodeIndicesStatsWarmerTotal :: Int
4160+ , nodeIndicesStatsWarmerCurrent :: Int
4161+ , nodeIndicesStatsFlushTotalTime :: NominalDiffTime
4162+ , nodeIndicesStatsFlushTotal :: Int
4163+ , nodeIndicesStatsRefreshTotalTime :: NominalDiffTime
4164+ , nodeIndicesStatsRefreshTotal :: Int
4165+ , nodeIndicesStatsMergesTotalSize :: Bytes
4166+ , nodeIndicesStatsMergesTotalDocs :: Int
4167+ , nodeIndicesStatsMergesTotalTime :: NominalDiffTime
4168+ , nodeIndicesStatsMergesTotal :: Int
4169+ , nodeIndicesStatsMergesCurrentSize :: Bytes
4170+ , nodeIndicesStatsMergesCurrentDocs :: Int
4171+ , nodeIndicesStatsMergesCurrent :: Int
4172+ , nodeIndicesStatsSearchFetchCurrent :: Int
4173+ , nodeIndicesStatsSearchFetchTime :: NominalDiffTime
4174+ , nodeIndicesStatsSearchFetchTotal :: Int
4175+ , nodeIndicesStatsSearchQueryCurrent :: Int
4176+ , nodeIndicesStatsSearchQueryTime :: NominalDiffTime
4177+ , nodeIndicesStatsSearchQueryTotal :: Int
4178+ , nodeIndicesStatsSearchOpenContexts :: Int
4179+ , nodeIndicesStatsGetCurrent :: Int
4180+ , nodeIndicesStatsGetMissingTime :: NominalDiffTime
4181+ , nodeIndicesStatsGetMissingTotal :: Int
4182+ , nodeIndicesStatsGetExistsTime :: NominalDiffTime
4183+ , nodeIndicesStatsGetExistsTotal :: Int
4184+ , nodeIndicesStatsGetTime :: NominalDiffTime
4185+ , nodeIndicesStatsGetTotal :: Int
4186+ , nodeIndicesStatsIndexingThrottleTime :: Maybe NominalDiffTime
4187+ , nodeIndicesStatsIndexingIsThrottled :: Maybe Bool
4188+ , nodeIndicesStatsIndexingNoopUpdateTotal :: Maybe Int
4189+ , nodeIndicesStatsIndexingDeleteCurrent :: Int
4190+ , nodeIndicesStatsIndexingDeleteTime :: NominalDiffTime
4191+ , nodeIndicesStatsIndexingDeleteTotal :: Int
4192+ , nodeIndicesStatsIndexingIndexCurrent :: Int
4193+ , nodeIndicesStatsIndexingIndexTime :: NominalDiffTime
4194+ , nodeIndicesStatsIndexingTotal :: Int
4195+ , nodeIndicesStatsStoreThrottleTime :: NominalDiffTime
4196+ , nodeIndicesStatsStoreSize :: Bytes
4197+ , nodeIndicesStatsDocsDeleted :: Int
4198+ , nodeIndicesStatsDocsCount :: Int
4199+ } deriving (Eq, Show, Generic, Typeable)
4201+-- | A quirky address format used throughout ElasticSearch. An example
4202+-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
4203+-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
4204+newtype EsAddress = EsAddress { esAddress :: Text }
4205+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4207+-- | Typically a 7 character hex string.
4208+newtype BuildHash = BuildHash { buildHash :: Text }
4209+ deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
4211+newtype PluginName = PluginName { pluginName :: Text }
4212+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4214+data NodeInfo = NodeInfo {
4215+ nodeInfoHTTPAddress :: EsAddress
4216+ , nodeInfoBuild :: BuildHash
4217+ , nodeInfoESVersion :: VersionNumber
4218+ , nodeInfoIP :: Server
4219+ , nodeInfoHost :: Server
4220+ , nodeInfoTransportAddress :: EsAddress
4221+ , nodeInfoName :: NodeName
4222+ , nodeInfoFullId :: FullNodeId
4223+ , nodeInfoPlugins :: [NodePluginInfo]
4224+ , nodeInfoHTTP :: NodeHTTPInfo
4225+ , nodeInfoTransport :: NodeTransportInfo
4226+ , nodeInfoNetwork :: NodeNetworkInfo
4227+ , nodeInfoThreadPool :: NodeThreadPoolsInfo
4228+ , nodeInfoJVM :: NodeJVMInfo
4229+ , nodeInfoProcess :: NodeProcessInfo
4230+ , nodeInfoOS :: NodeOSInfo
4231+ , nodeInfoSettings :: Object
4232+ -- ^ The members of the settings objects are not consistent,
4233+ -- dependent on plugins, etc.
4234+ } deriving (Eq, Show, Generic, Typeable)
4236+data NodePluginInfo = NodePluginInfo {
4237+ nodePluginSite :: Bool
4238+ -- ^ Is this a site plugin?
4239+ , nodePluginJVM :: Bool
4240+ -- ^ Is this plugin running on the JVM
4241+ , nodePluginDescription :: Text
4242+ , nodePluginVersion :: MaybeNA VersionNumber
4243+ , nodePluginName :: PluginName
4244+ } deriving (Eq, Show, Generic, Typeable)
4246+data NodeHTTPInfo = NodeHTTPInfo {
4247+ nodeHTTPMaxContentLength :: Bytes
4248+ , nodeHTTPTransportAddress :: BoundTransportAddress
4249+ } deriving (Eq, Show, Generic, Typeable)
4251+data NodeTransportInfo = NodeTransportInfo {
4252+ nodeTransportProfiles :: [BoundTransportAddress]
4253+ , nodeTransportAddress :: BoundTransportAddress
4254+ } deriving (Eq, Show, Generic, Typeable)
4256+data BoundTransportAddress = BoundTransportAddress {
4257+ publishAddress :: EsAddress
4258+ , boundAddress :: EsAddress
4259+ } deriving (Eq, Show, Generic, Typeable)
4261+data NodeNetworkInfo = NodeNetworkInfo {
4262+ nodeNetworkPrimaryInterface :: NodeNetworkInterface
4263+ , nodeNetworkRefreshInterval :: NominalDiffTime
4264+ } deriving (Eq, Show, Generic, Typeable)
4266+newtype MacAddress = MacAddress { macAddress :: Text }
4267+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4269+newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
4270+ deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4272+data NodeNetworkInterface = NodeNetworkInterface {
4273+ nodeNetIfaceMacAddress :: MacAddress
4274+ , nodeNetIfaceName :: NetworkInterfaceName
4275+ , nodeNetIfaceAddress :: Server
4276+ } deriving (Eq, Show, Generic, Typeable)
4278+data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
4279+ nodeThreadPoolsRefresh :: NodeThreadPoolInfo
4280+ , nodeThreadPoolsManagement :: NodeThreadPoolInfo
4281+ , nodeThreadPoolsPercolate :: NodeThreadPoolInfo
4282+ , nodeThreadPoolsListener :: Maybe NodeThreadPoolInfo
4283+ , nodeThreadPoolsFetchShardStarted :: Maybe NodeThreadPoolInfo
4284+ , nodeThreadPoolsSearch :: NodeThreadPoolInfo
4285+ , nodeThreadPoolsFlush :: NodeThreadPoolInfo
4286+ , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
4287+ , nodeThreadPoolsOptimize :: NodeThreadPoolInfo
4288+ , nodeThreadPoolsBulk :: NodeThreadPoolInfo
4289+ , nodeThreadPoolsSuggest :: NodeThreadPoolInfo
4290+ , nodeThreadPoolsMerge :: NodeThreadPoolInfo
4291+ , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
4292+ , nodeThreadPoolsGet :: NodeThreadPoolInfo
4293+ , nodeThreadPoolsFetchShardStore :: Maybe NodeThreadPoolInfo
4294+ , nodeThreadPoolsIndex :: NodeThreadPoolInfo
4295+ , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
4296+ } deriving (Eq, Show, Generic, Typeable)
4298+data NodeThreadPoolInfo = NodeThreadPoolInfo {
4299+ nodeThreadPoolQueueSize :: ThreadPoolSize
4300+ , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
4301+ , nodeThreadPoolMin :: Maybe Int
4302+ , nodeThreadPoolMax :: Maybe Int
4303+ , nodeThreadPoolType :: ThreadPoolType
4304+ } deriving (Eq, Show, Generic, Typeable)
4306+data ThreadPoolSize = ThreadPoolBounded Int
4307+ | ThreadPoolUnbounded
4308+ deriving (Eq, Show, Generic, Typeable)
4310+data ThreadPoolType = ThreadPoolScaling
4313+ deriving (Eq, Show, Generic, Typeable)
4315+data NodeJVMInfo = NodeJVMInfo {
4316+ nodeJVMInfoMemoryPools :: [JVMMemoryPool]
4317+ , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
4318+ , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
4319+ , nodeJVMInfoStartTime :: UTCTime
4320+ , nodeJVMInfoVMVendor :: Text
4321+ , nodeJVMVMVersion :: VersionNumber
4322+ -- ^ JVM doesn't seme to follow normal version conventions
4323+ , nodeJVMVMName :: Text
4324+ , nodeJVMVersion :: VersionNumber
4325+ , nodeJVMPID :: PID
4326+ } deriving (Eq, Show, Generic, Typeable)
4328+-- | Handles quirks in the way JVM versions are rendered (1.7.0_101 -> 1.7.0.101)
4329+newtype JVMVersion = JVMVersion { unJVMVersion :: VersionNumber }
4331+data JVMMemoryInfo = JVMMemoryInfo {
4332+ jvmMemoryInfoDirectMax :: Bytes
4333+ , jvmMemoryInfoNonHeapMax :: Bytes
4334+ , jvmMemoryInfoNonHeapInit :: Bytes
4335+ , jvmMemoryInfoHeapMax :: Bytes
4336+ , jvmMemoryInfoHeapInit :: Bytes
4337+ } deriving (Eq, Show, Generic, Typeable)
4339+newtype JVMMemoryPool = JVMMemoryPool {
4340+ jvmMemoryPool :: Text
4341+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4343+newtype JVMGCCollector = JVMGCCollector {
4344+ jvmGCCollector :: Text
4345+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4349+ } deriving (Eq, Show, Generic, Typeable, FromJSON)
4351+data NodeOSInfo = NodeOSInfo {
4352+ nodeOSSwap :: Bytes
4353+ , nodeOSMem :: Bytes
4354+ , nodeOSCPUInfo :: CPUInfo
4355+ , nodeOSAvailableProcessors :: Int
4356+ , nodeOSRefreshInterval :: NominalDiffTime
4357+ } deriving (Eq, Show, Generic, Typeable)
4359+data CPUInfo = CPUInfo {
4360+ cpuCacheSize :: Bytes
4361+ , cpuCoresPerSocket :: Int
4362+ , cpuTotalSockets :: Int
4363+ , cpuTotalCores :: Int
4366+ , cpuVendor :: Text
4367+ } deriving (Eq, Show, Generic, Typeable)
4369+data NodeProcessInfo = NodeProcessInfo {
4370+ nodeProcessMLockAll :: Bool
4371+ -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
4372+ , nodeProcessMaxFileDescriptors :: Int
4373+ , nodeProcessId :: PID
4374+ , nodeProcessRefreshInterval :: NominalDiffTime
4375+ } deriving (Eq, Show, Generic, Typeable)
4377+data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
4378+ repoUpdateVerify :: Bool
4379+ -- ^ After creation/update, synchronously check that nodes can
4380+ -- write to this repo. Defaults to True. You may use False if you
4381+ -- need a faster response and plan on verifying manually later
4382+ -- with 'verifySnapshotRepo'.
4383+ } deriving (Eq, Show, Generic, Typeable)
4386+-- | Reasonable defaults for repo creation/update
4388+-- * repoUpdateVerify True
4389+defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4390+defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4393+-- | A filesystem-based snapshot repo that ships with
4394+-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4395+-- used with 'updateSnapshotRepo'
4396+data FsSnapshotRepo = FsSnapshotRepo {
4397+ fsrName :: SnapshotRepoName
4398+ , fsrLocation :: FilePath
4399+ , fsrCompressMetadata :: Bool
4400+ , fsrChunkSize :: Maybe Bytes
4401+ -- ^ Size by which to split large files during snapshotting.
4402+ , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4403+ -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4404+ , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4405+ -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4406+ } deriving (Eq, Generic, Show, Typeable)
4409+instance SnapshotRepo FsSnapshotRepo where
4410+ toGSnapshotRepo FsSnapshotRepo {..} =
4411+ GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4413+ Object settings = object $ [ "location" .= fsrLocation
4414+ , "compress" .= fsrCompressMetadata
4416+ optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4417+ , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4418+ , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4420+ fromGSnapshotRepo GenericSnapshotRepo {..}
4421+ | gSnapshotRepoType == fsRepoType = do
4422+ let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4424+ FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4425+ <*> o .:? "compress" .!= False
4426+ <*> o .:? "chunk_size"
4427+ <*> o .:? "max_restore_bytes_per_sec"
4428+ <*> o .:? "max_snapshot_bytes_per_sec"
4429+ | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4432+parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4433+parseRepo parser = case parseEither (const parser) () of
4434+ Left e -> Left (OtherRepoConversionError (T.pack e))
4438+fsRepoType :: SnapshotRepoType
4439+fsRepoType = SnapshotRepoType "fs"
4441+-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4442+class SnapshotRepo r where
4443+ toGSnapshotRepo :: r -> GenericSnapshotRepo
4444+ fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4447+data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4448+ -- ^ Expected type and actual type
4449+ | OtherRepoConversionError Text
4450+ deriving (Show, Eq, Generic, Typeable)
4453+instance Exception SnapshotRepoConversionError
4456+data SnapshotCreateSettings = SnapshotCreateSettings {
4457+ snapWaitForCompletion :: Bool
4458+ -- ^ Should the API call return immediately after initializing
4459+ -- the snapshot or wait until completed? Note that if this is
4460+ -- enabled it could wait a long time, so you should adjust your
4461+ -- 'ManagerSettings' accordingly to set long timeouts or
4462+ -- explicitly handle timeouts.
4463+ , snapIndices :: Maybe IndexSelection
4464+ -- ^ Nothing will snapshot all indices. Just [] is permissable and
4465+ -- will essentially be a no-op snapshot.
4466+ , snapIgnoreUnavailable :: Bool
4467+ -- ^ If set to True, any matched indices that don't exist will be
4468+ -- ignored. Otherwise it will be an error and fail.
4469+ , snapIncludeGlobalState :: Bool
4470+ , snapPartial :: Bool
4471+ -- ^ If some indices failed to snapshot (e.g. if not all primary
4472+ -- shards are available), should the process proceed?
4473+ } deriving (Eq, Generic, Show, Typeable)
4476+-- | Reasonable defaults for snapshot creation
4478+-- * snapWaitForCompletion False
4479+-- * snapIndices Nothing
4480+-- * snapIgnoreUnavailable False
4481+-- * snapIncludeGlobalState True
4482+-- * snapPartial False
4483+defaultSnapshotCreateSettings :: SnapshotCreateSettings
4484+defaultSnapshotCreateSettings = SnapshotCreateSettings {
4485+ snapWaitForCompletion = False
4486+ , snapIndices = Nothing
4487+ , snapIgnoreUnavailable = False
4488+ , snapIncludeGlobalState = True
4489+ , snapPartial = False
4493+data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4494+ | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4497+-- | Either specifies an exact snapshot name or one with globs in it,
4498+-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4500+data SnapshotPattern = ExactSnap SnapshotName
4502+ deriving (Eq, Generic, Show, Typeable)
4505+-- | General information about the state of a snapshot. Has some
4506+-- redundancies with 'SnapshotStatus'
4507+data SnapshotInfo = SnapshotInfo {
4508+ snapInfoShards :: ShardResult
4509+ , snapInfoFailures :: [SnapshotShardFailure]
4510+ , snapInfoDuration :: NominalDiffTime
4511+ , snapInfoEndTime :: UTCTime
4512+ , snapInfoStartTime :: UTCTime
4513+ , snapInfoState :: SnapshotState
4514+ , snapInfoIndices :: [IndexName]
4515+ , snapInfoName :: SnapshotName
4516+ } deriving (Eq, Generic, Show, Typeable)
4519+instance FromJSON SnapshotInfo where
4520+ parseJSON = withObject "SnapshotInfo" parse
4522+ parse o = SnapshotInfo <$> o .: "shards"
4523+ <*> o .: "failures"
4524+ <*> (unMS <$> o .: "duration_in_millis")
4525+ <*> (posixMS <$> o .: "end_time_in_millis")
4526+ <*> (posixMS <$> o .: "start_time_in_millis")
4529+ <*> o .: "snapshot"
4531+data SnapshotShardFailure = SnapshotShardFailure {
4532+ snapShardFailureIndex :: IndexName
4533+ , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4534+ , snapShardFailureReason :: Text
4535+ , snapShardFailureShardId :: ShardId
4536+ } deriving (Eq, Show, Generic, Typeable)
4539+instance FromJSON SnapshotShardFailure where
4540+ parseJSON = withObject "SnapshotShardFailure" parse
4542+ parse o = SnapshotShardFailure <$> o .: "index"
4543+ <*> o .:? "node_id"
4545+ <*> o .: "shard_id"
4548+newtype ShardId = ShardId { shardId :: Int }
4549+ deriving (Eq, Show, Generic, Typeable, FromJSON)
4552+newtype MS = MS NominalDiffTime
4555+-- keeps the unexported constructor warnings at bay
4556+unMS :: MS -> NominalDiffTime
4560+instance FromJSON MS where
4561+ parseJSON = withScientific "MS" (return . MS . parse)
4563+ parse n = fromInteger ((truncate n) * 1000)
4566+data SnapshotState = SnapshotInit
4573+ deriving (Show, Eq, Generic, Typeable)
4575+instance FromJSON SnapshotState where
4576+ parseJSON = withText "SnapshotState" parse
4578+ parse "INIT" = return SnapshotInit
4579+ parse "STARTED" = return SnapshotStarted
4580+ parse "SUCCESS" = return SnapshotSuccess
4581+ parse "FAILED" = return SnapshotFailed
4582+ parse "ABORTED" = return SnapshotAborted
4583+ parse "MISSING" = return SnapshotMissing
4584+ parse "WAITING" = return SnapshotWaiting
4585+ parse t = fail ("Invalid snapshot state " <> T.unpack t)
4588+newtype SnapshotName = SnapshotName { snapshotName :: Text }
4589+ deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4592+data SnapshotRestoreSettings = SnapshotRestoreSettings {
4593+ snapRestoreWaitForCompletion :: Bool
4594+ -- ^ Should the API call return immediately after initializing
4595+ -- the restore or wait until completed? Note that if this is
4596+ -- enabled, it could wait a long time, so you should adjust your
4597+ -- 'ManagerSettings' accordingly to set long timeouts or
4598+ -- explicitly handle timeouts.
4599+ , snapRestoreIndices :: Maybe IndexSelection
4600+ -- ^ Nothing will restore all indices in the snapshot. Just [] is
4601+ -- permissable and will essentially be a no-op restore.
4602+ , snapRestoreIgnoreUnavailable :: Bool
4603+ -- ^ If set to True, any indices that do not exist will be ignored
4604+ -- during snapshot rather than failing the restore.
4605+ , snapRestoreIncludeGlobalState :: Bool
4606+ -- ^ If set to false, will ignore any global state in the snapshot
4607+ -- and will not restore it.
4608+ , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4609+ -- ^ A regex pattern for matching indices. Used with
4610+ -- 'snapRestoreRenameReplacement', the restore can reference the
4611+ -- matched index and create a new index name upon restore.
4612+ , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4613+ -- ^ Expression of how index renames should be constructed.
4614+ , snapRestorePartial :: Bool
4615+ -- ^ If some indices fail to restore, should the process proceed?
4616+ , snapRestoreIncludeAliases :: Bool
4617+ -- ^ Should the restore also restore the aliases captured in the
4619+ , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4620+ -- ^ Settings to apply during the restore process. __NOTE:__ This
4621+ -- option is not supported in ES < 1.5 and should be set to
4622+ -- Nothing in that case.
4623+ , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4624+ -- ^ This type could be more rich but it isn't clear which
4625+ -- settings are allowed to be ignored during restore, so we're
4626+ -- going with including this feature in a basic form rather than
4627+ -- omitting it. One example here would be
4628+ -- "index.refresh_interval". Any setting specified here will
4629+ -- revert back to the server default during the restore process.
4630+ } deriving (Eq, Generic, Show, Typeable)
4632+-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4633+newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4634+ deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4637+-- | A single token in a index renaming scheme for a restore. These
4638+-- are concatenated into a string before being sent to
4639+-- ElasticSearch. Check out these Java
4640+-- <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.
4641+data RestoreRenameToken = RRTLit Text
4642+ -- ^ Just a literal string of characters
4644+ -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4645+ | RRSubGroup RRGroupRefNum
4646+ -- ^ A specific reference to a group number
4647+ deriving (Show, Eq, Generic, Typeable)
4650+-- | A group number for regex matching. Only values from 1-9 are
4651+-- supported. Construct with 'mkRRGroupRefNum'
4652+newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4653+ deriving (Show, Eq, Generic, Typeable, Ord)
4655+instance Bounded RRGroupRefNum where
4656+ minBound = RRGroupRefNum 1
4657+ maxBound = RRGroupRefNum 9
4660+-- | Only allows valid group number references (1-9).
4661+mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4663+ | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4664+ Just $ RRGroupRefNum i
4665+ | otherwise = Nothing
4668+-- | Reasonable defaults for snapshot restores
4670+-- * snapRestoreWaitForCompletion False
4671+-- * snapRestoreIndices Nothing
4672+-- * snapRestoreIgnoreUnavailable False
4673+-- * snapRestoreIncludeGlobalState True
4674+-- * snapRestoreRenamePattern Nothing
4675+-- * snapRestoreRenameReplacement Nothing
4676+-- * snapRestorePartial False
4677+-- * snapRestoreIncludeAliases True
4678+-- * snapRestoreIndexSettingsOverrides Nothing
4679+-- * snapRestoreIgnoreIndexSettings Nothing
4680+defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4681+defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4682+ snapRestoreWaitForCompletion = False
4683+ , snapRestoreIndices = Nothing
4684+ , snapRestoreIgnoreUnavailable = False
4685+ , snapRestoreIncludeGlobalState = True
4686+ , snapRestoreRenamePattern = Nothing
4687+ , snapRestoreRenameReplacement = Nothing
4688+ , snapRestorePartial = False
4689+ , snapRestoreIncludeAliases = True
4690+ , snapRestoreIndexSettingsOverrides = Nothing
4691+ , snapRestoreIgnoreIndexSettings = Nothing
4695+-- | Index settings that can be overridden. The docs only mention you
4696+-- can update number of replicas, but there may be more. You
4697+-- definitely cannot override shard count.
4698+data RestoreIndexSettings = RestoreIndexSettings {
4699+ restoreOverrideReplicas :: Maybe ReplicaCount
4700+ } deriving (Show, Eq, Generic, Typeable)
4703+instance ToJSON RestoreIndexSettings where
4704+ toJSON RestoreIndexSettings {..} = object prs
4706+ prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
4709+instance FromJSON NodesInfo where
4710+ parseJSON = withObject "NodesInfo" parse
4713+ nodes <- o .: "nodes"
4714+ infos <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4715+ node <- parseJSON v
4716+ parseNodeInfo (FullNodeId fullNID) node
4717+ cn <- o .: "cluster_name"
4718+ return (NodesInfo infos cn)
4720+instance FromJSON NodesStats where
4721+ parseJSON = withObject "NodesStats" parse
4724+ nodes <- o .: "nodes"
4725+ stats <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4726+ node <- parseJSON v
4727+ parseNodeStats (FullNodeId fullNID) node
4728+ cn <- o .: "cluster_name"
4729+ return (NodesStats stats cn)
4731+instance FromJSON NodeBreakerStats where
4732+ parseJSON = withObject "NodeBreakerStats" parse
4734+ parse o = NodeBreakerStats <$> o .: "tripped"
4735+ <*> o .: "overhead"
4736+ <*> o .: "estimated_size_in_bytes"
4737+ <*> o .: "limit_size_in_bytes"
4739+instance FromJSON NodeHTTPStats where
4740+ parseJSON = withObject "NodeHTTPStats" parse
4742+ parse o = NodeHTTPStats <$> o .: "total_opened"
4743+ <*> o .: "current_open"
4745+instance FromJSON NodeTransportStats where
4746+ parseJSON = withObject "NodeTransportStats" parse
4748+ parse o = NodeTransportStats <$> o .: "tx_size_in_bytes"
4749+ <*> o .: "tx_count"
4750+ <*> o .: "rx_size_in_bytes"
4751+ <*> o .: "rx_count"
4752+ <*> o .: "server_open"
4754+instance FromJSON NodeFSStats where
4755+ parseJSON = withObject "NodeFSStats" parse
4757+ parse o = NodeFSStats <$> o .: "data"
4759+ <*> (posixMS <$> o .: "timestamp")
4761+instance FromJSON NodeDataPathStats where
4762+ parseJSON = withObject "NodeDataPathStats" parse
4765+ NodeDataPathStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4766+ <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4767+ <*> o .:? "disk_io_size_in_bytes"
4768+ <*> o .:? "disk_write_size_in_bytes"
4769+ <*> o .:? "disk_read_size_in_bytes"
4770+ <*> o .:? "disk_io_op"
4771+ <*> o .:? "disk_writes"
4772+ <*> o .:? "disk_reads"
4773+ <*> o .: "available_in_bytes"
4774+ <*> o .: "free_in_bytes"
4775+ <*> o .: "total_in_bytes"
4781+newtype StringlyTypedDouble = StringlyTypedDouble { unStringlyTypedDouble :: Double }
4784+instance FromJSON StringlyTypedDouble where
4785+ parseJSON = fmap StringlyTypedDouble . parseJSON . unStringlyTypeJSON
4788+instance FromJSON NodeFSTotalStats where
4789+ parseJSON = withObject "NodeFSTotalStats" parse
4791+ parse o = NodeFSTotalStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4792+ <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4793+ <*> o .:? "disk_io_size_in_bytes"
4794+ <*> o .:? "disk_write_size_in_bytes"
4795+ <*> o .:? "disk_read_size_in_bytes"
4796+ <*> o .:? "disk_io_op"
4797+ <*> o .:? "disk_writes"
4798+ <*> o .:? "disk_reads"
4799+ <*> o .: "available_in_bytes"
4800+ <*> o .: "free_in_bytes"
4801+ <*> o .: "total_in_bytes"
4803+instance FromJSON NodeNetworkStats where
4804+ parseJSON = withObject "NodeNetworkStats" parse
4808+ NodeNetworkStats <$> tcp .: "out_rsts"
4809+ <*> tcp .: "in_errs"
4810+ <*> tcp .: "attempt_fails"
4811+ <*> tcp .: "estab_resets"
4812+ <*> tcp .: "retrans_segs"
4813+ <*> tcp .: "out_segs"
4814+ <*> tcp .: "in_segs"
4815+ <*> tcp .: "curr_estab"
4816+ <*> tcp .: "passive_opens"
4817+ <*> tcp .: "active_opens"
4819+instance FromJSON NodeThreadPoolsStats where
4820+ parseJSON = withObject "NodeThreadPoolsStats" parse
4822+ parse o = NodeThreadPoolsStats <$> o .: "snapshot"
4826+ <*> o .: "management"
4827+ <*> o .:? "fetch_shard_store"
4828+ <*> o .: "optimize"
4836+ <*> o .:? "listener"
4837+ <*> o .:? "fetch_shard_started"
4838+ <*> o .: "percolate"
4839+instance FromJSON NodeThreadPoolStats where
4840+ parseJSON = withObject "NodeThreadPoolStats" parse
4842+ parse o = NodeThreadPoolStats <$> o .: "completed"
4844+ <*> o .: "rejected"
4849+instance FromJSON NodeJVMStats where
4850+ parseJSON = withObject "NodeJVMStats" parse
4853+ bufferPools <- o .: "buffer_pools"
4854+ mapped <- bufferPools .: "mapped"
4855+ direct <- bufferPools .: "direct"
4857+ collectors <- gc .: "collectors"
4858+ oldC <- collectors .: "old"
4859+ youngC <- collectors .: "young"
4860+ threads <- o .: "threads"
4862+ pools <- mem .: "pools"
4863+ oldM <- pools .: "old"
4864+ survivorM <- pools .: "survivor"
4865+ youngM <- pools .: "young"
4866+ NodeJVMStats <$> pure mapped
4870+ <*> threads .: "peak_count"
4871+ <*> threads .: "count"
4875+ <*> mem .: "non_heap_committed_in_bytes"
4876+ <*> mem .: "non_heap_used_in_bytes"
4877+ <*> mem .: "heap_max_in_bytes"
4878+ <*> mem .: "heap_committed_in_bytes"
4879+ <*> mem .: "heap_used_percent"
4880+ <*> mem .: "heap_used_in_bytes"
4881+ <*> (unMS <$> o .: "uptime_in_millis")
4882+ <*> (posixMS <$> o .: "timestamp")
4884+instance FromJSON JVMBufferPoolStats where
4885+ parseJSON = withObject "JVMBufferPoolStats" parse
4887+ parse o = JVMBufferPoolStats <$> o .: "total_capacity_in_bytes"
4888+ <*> o .: "used_in_bytes"
4891+instance FromJSON JVMGCStats where
4892+ parseJSON = withObject "JVMGCStats" parse
4894+ parse o = JVMGCStats <$> (unMS <$> o .: "collection_time_in_millis")
4895+ <*> o .: "collection_count"
4897+instance FromJSON JVMPoolStats where
4898+ parseJSON = withObject "JVMPoolStats" parse
4900+ parse o = JVMPoolStats <$> o .: "peak_max_in_bytes"
4901+ <*> o .: "peak_used_in_bytes"
4902+ <*> o .: "max_in_bytes"
4903+ <*> o .: "used_in_bytes"
4905+instance FromJSON NodeProcessStats where
4906+ parseJSON = withObject "NodeProcessStats" parse
4911+ NodeProcessStats <$> mem .: "total_virtual_in_bytes"
4912+ <*> mem .: "share_in_bytes"
4913+ <*> mem .: "resident_in_bytes"
4914+ <*> (unMS <$> cpu .: "total_in_millis")
4915+ <*> (unMS <$> cpu .: "user_in_millis")
4916+ <*> (unMS <$> cpu .: "sys_in_millis")
4917+ <*> cpu .: "percent"
4918+ <*> o .: "open_file_descriptors"
4919+ <*> (posixMS <$> o .: "timestamp")
4921+instance FromJSON NodeOSStats where
4922+ parseJSON = withObject "NodeOSStats" parse
4925+ swap <- o .: "swap"
4928+ load <- o .:? "load_average"
4929+ NodeOSStats <$> swap .: "free_in_bytes"
4930+ <*> swap .: "used_in_bytes"
4931+ <*> mem .: "actual_used_in_bytes"
4932+ <*> mem .: "actual_free_in_bytes"
4933+ <*> mem .: "used_percent"
4934+ <*> mem .: "free_percent"
4935+ <*> mem .: "used_in_bytes"
4936+ <*> mem .: "free_in_bytes"
4937+ <*> cpu .: "stolen"
4943+ <*> (unMS <$> o .: "uptime_in_millis")
4944+ <*> (posixMS <$> o .: "timestamp")
4946+instance FromJSON LoadAvgs where
4947+ parseJSON = withArray "LoadAvgs" parse
4949+ parse v = case V.toList v of
4950+ [one, five, fifteen] -> LoadAvgs <$> parseJSON one
4952+ <*> parseJSON fifteen
4953+ _ -> fail "Expecting a triple of Doubles"
4955+instance FromJSON NodeIndicesStats where
4956+ parseJSON = withObject "NodeIndicesStats" parse
4959+ let (.::) mv k = case mv of
4960+ Just v -> Just <$> v .: k
4961+ Nothing -> pure Nothing
4962+ mRecovery <- o .:? "recovery"
4963+ mQueryCache <- o .:? "query_cache"
4964+ suggest <- o .: "suggest"
4965+ translog <- o .: "translog"
4966+ segments <- o .: "segments"
4967+ completion <- o .: "completion"
4968+ percolate <- o .: "percolate"
4969+ fielddata <- o .: "fielddata"
4970+ idCache <- o .: "id_cache"
4971+ filterCache <- o .: "filter_cache"
4972+ warmer <- o .: "warmer"
4973+ flush <- o .: "flush"
4974+ refresh <- o .: "refresh"
4975+ merges <- o .: "merges"
4976+ search <- o .: "search"
4977+ getStats <- o .: "get"
4978+ indexing <- o .: "indexing"
4979+ store <- o .: "store"
4980+ docs <- o .: "docs"
4981+ NodeIndicesStats <$> (fmap unMS <$> mRecovery .:: "throttle_time_in_millis")
4982+ <*> mRecovery .:: "current_as_target"
4983+ <*> mRecovery .:: "current_as_source"
4984+ <*> mQueryCache .:: "miss_count"
4985+ <*> mQueryCache .:: "hit_count"
4986+ <*> mQueryCache .:: "evictions"
4987+ <*> mQueryCache .:: "memory_size_in_bytes"
4988+ <*> suggest .: "current"
4989+ <*> (unMS <$> suggest .: "time_in_millis")
4990+ <*> suggest .: "total"
4991+ <*> translog .: "size_in_bytes"
4992+ <*> translog .: "operations"
4993+ <*> segments .:? "fixed_bit_set_memory_in_bytes"
4994+ <*> segments .: "version_map_memory_in_bytes"
4995+ <*> segments .:? "index_writer_max_memory_in_bytes"
4996+ <*> segments .: "index_writer_memory_in_bytes"
4997+ <*> segments .: "memory_in_bytes"
4998+ <*> segments .: "count"
4999+ <*> completion .: "size_in_bytes"
5000+ <*> percolate .: "queries"
5001+ <*> percolate .: "memory_size_in_bytes"
5002+ <*> percolate .: "current"
5003+ <*> (unMS <$> percolate .: "time_in_millis")
5004+ <*> percolate .: "total"
5005+ <*> fielddata .: "evictions"
5006+ <*> fielddata .: "memory_size_in_bytes"
5007+ <*> idCache .: "memory_size_in_bytes"
5008+ <*> filterCache .: "evictions"
5009+ <*> filterCache .: "memory_size_in_bytes"
5010+ <*> (unMS <$> warmer .: "total_time_in_millis")
5011+ <*> warmer .: "total"
5012+ <*> warmer .: "current"
5013+ <*> (unMS <$> flush .: "total_time_in_millis")
5014+ <*> flush .: "total"
5015+ <*> (unMS <$> refresh .: "total_time_in_millis")
5016+ <*> refresh .: "total"
5017+ <*> merges .: "total_size_in_bytes"
5018+ <*> merges .: "total_docs"
5019+ <*> (unMS <$> merges .: "total_time_in_millis")
5020+ <*> merges .: "total"
5021+ <*> merges .: "current_size_in_bytes"
5022+ <*> merges .: "current_docs"
5023+ <*> merges .: "current"
5024+ <*> search .: "fetch_current"
5025+ <*> (unMS <$> search .: "fetch_time_in_millis")
5026+ <*> search .: "fetch_total"
5027+ <*> search .: "query_current"
5028+ <*> (unMS <$> search .: "query_time_in_millis")
5029+ <*> search .: "query_total"
5030+ <*> search .: "open_contexts"
5031+ <*> getStats .: "current"
5032+ <*> (unMS <$> getStats .: "missing_time_in_millis")
5033+ <*> getStats .: "missing_total"
5034+ <*> (unMS <$> getStats .: "exists_time_in_millis")
5035+ <*> getStats .: "exists_total"
5036+ <*> (unMS <$> getStats .: "time_in_millis")
5037+ <*> getStats .: "total"
5038+ <*> (fmap unMS <$> indexing .:? "throttle_time_in_millis")
5039+ <*> indexing .:? "is_throttled"
5040+ <*> indexing .:? "noop_update_total"
5041+ <*> indexing .: "delete_current"
5042+ <*> (unMS <$> indexing .: "delete_time_in_millis")
5043+ <*> indexing .: "delete_total"
5044+ <*> indexing .: "index_current"
5045+ <*> (unMS <$> indexing .: "index_time_in_millis")
5046+ <*> indexing .: "index_total"
5047+ <*> (unMS <$> store .: "throttle_time_in_millis")
5048+ <*> store .: "size_in_bytes"
5049+ <*> docs .: "deleted"
5050+ <*> docs .: "count"
5052+instance FromJSON NodeBreakersStats where
5053+ parseJSON = withObject "NodeBreakersStats" parse
5055+ parse o = NodeBreakersStats <$> o .: "parent"
5057+ <*> o .: "fielddata"
5059+parseNodeStats :: FullNodeId -> Object -> Parser NodeStats
5060+parseNodeStats fnid o = do
5061+ NodeStats <$> o .: "name"
5063+ <*> o .:? "breakers"
5065+ <*> o .: "transport"
5068+ <*> o .: "thread_pool"
5074+parseNodeInfo :: FullNodeId -> Object -> Parser NodeInfo
5075+parseNodeInfo nid o =
5076+ NodeInfo <$> o .: "http_address"
5081+ <*> o .: "transport_address"
5086+ <*> o .: "transport"
5088+ <*> o .: "thread_pool"
5092+ <*> o .: "settings"
5094+instance FromJSON NodePluginInfo where
5095+ parseJSON = withObject "NodePluginInfo" parse
5097+ parse o = NodePluginInfo <$> o .: "site"
5099+ <*> o .: "description"
5103+instance FromJSON NodeHTTPInfo where
5104+ parseJSON = withObject "NodeHTTPInfo" parse
5106+ parse o = NodeHTTPInfo <$> o .: "max_content_length_in_bytes"
5107+ <*> parseJSON (Object o)
5109+instance FromJSON BoundTransportAddress where
5110+ parseJSON = withObject "BoundTransportAddress" parse
5112+ parse o = BoundTransportAddress <$> o .: "publish_address"
5113+ <*> o .: "bound_address"
5115+instance FromJSON NodeOSInfo where
5116+ parseJSON = withObject "NodeOSInfo" parse
5119+ swap <- o .: "swap"
5121+ NodeOSInfo <$> swap .: "total_in_bytes"
5122+ <*> mem .: "total_in_bytes"
5124+ <*> o .: "available_processors"
5125+ <*> (unMS <$> o .: "refresh_interval_in_millis")
5128+instance FromJSON CPUInfo where
5129+ parseJSON = withObject "CPUInfo" parse
5131+ parse o = CPUInfo <$> o .: "cache_size_in_bytes"
5132+ <*> o .: "cores_per_socket"
5133+ <*> o .: "total_sockets"
5134+ <*> o .: "total_cores"
5139+instance FromJSON NodeProcessInfo where
5140+ parseJSON = withObject "NodeProcessInfo" parse
5142+ parse o = NodeProcessInfo <$> o .: "mlockall"
5143+ <*> o .: "max_file_descriptors"
5145+ <*> (unMS <$> o .: "refresh_interval_in_millis")
5147+instance FromJSON NodeJVMInfo where
5148+ parseJSON = withObject "NodeJVMInfo" parse
5150+ parse o = NodeJVMInfo <$> o .: "memory_pools"
5151+ <*> o .: "gc_collectors"
5153+ <*> (posixMS <$> o .: "start_time_in_millis")
5154+ <*> o .: "vm_vendor"
5155+ <*> o .: "vm_version"
5157+ <*> (unJVMVersion <$> o .: "version")
5160+instance FromJSON JVMVersion where
5161+ parseJSON (String t) =
5162+ JVMVersion <$> parseJSON (String (T.replace "_" "." t))
5163+ parseJSON v = JVMVersion <$> parseJSON v
5165+instance FromJSON JVMMemoryInfo where
5166+ parseJSON = withObject "JVMMemoryInfo" parse
5168+ parse o = JVMMemoryInfo <$> o .: "direct_max_in_bytes"
5169+ <*> o .: "non_heap_max_in_bytes"
5170+ <*> o .: "non_heap_init_in_bytes"
5171+ <*> o .: "heap_max_in_bytes"
5172+ <*> o .: "heap_init_in_bytes"
5174+instance FromJSON NodeThreadPoolsInfo where
5175+ parseJSON = withObject "NodeThreadPoolsInfo" parse
5177+ parse o = NodeThreadPoolsInfo <$> o .: "refresh"
5178+ <*> o .: "management"
5179+ <*> o .: "percolate"
5180+ <*> o .:? "listener"
5181+ <*> o .:? "fetch_shard_started"
5185+ <*> o .: "optimize"
5189+ <*> o .: "snapshot"
5191+ <*> o .:? "fetch_shard_store"
5195+instance FromJSON NodeThreadPoolInfo where
5196+ parseJSON = withObject "NodeThreadPoolInfo" parse
5199+ ka <- maybe (return Nothing) (fmap Just . parseStringInterval) =<< o .:? "keep_alive"
5200+ NodeThreadPoolInfo <$> (parseJSON . unStringlyTypeJSON =<< o .: "queue_size")
5206+parseStringInterval :: (Monad m) => String -> m NominalDiffTime
5207+parseStringInterval s = case span isNumber s of
5208+ ("", _) -> fail "Invalid interval"
5209+ (nS, unitS) -> case (readMay nS, readMay unitS) of
5210+ (Just n, Just unit) -> return (fromInteger (n * unitNDT unit))
5211+ (Nothing, _) -> fail "Invalid interval number"
5212+ (_, Nothing) -> fail "Invalid interval unit"
5214+ unitNDT Seconds = 1
5215+ unitNDT Minutes = 60
5216+ unitNDT Hours = 60 * 60
5217+ unitNDT Days = 24 * 60 * 60
5218+ unitNDT Weeks = 7 * 24 * 60 * 60
5220+instance FromJSON ThreadPoolSize where
5221+ parseJSON v = parseAsNumber v <|> parseAsString v
5223+ parseAsNumber = parseAsInt <=< parseJSON
5224+ parseAsInt (-1) = return ThreadPoolUnbounded
5226+ | n >= 0 = return (ThreadPoolBounded n)
5227+ | otherwise = fail "Thread pool size must be >= -1."
5228+ parseAsString = withText "ThreadPoolSize" $ \t ->
5229+ case first (readMay . T.unpack) (T.span isNumber t) of
5230+ (Just n, "k") -> return (ThreadPoolBounded (n * 1000))
5231+ (Just n, "") -> return (ThreadPoolBounded n)
5232+ _ -> fail ("Invalid thread pool size " <> T.unpack t)
5234+instance FromJSON ThreadPoolType where
5235+ parseJSON = withText "ThreadPoolType" parse
5237+ parse "scaling" = return ThreadPoolScaling
5238+ parse "fixed" = return ThreadPoolFixed
5239+ parse "cached" = return ThreadPoolCached
5240+ parse e = fail ("Unexpected thread pool type" <> T.unpack e)
5242+instance FromJSON NodeTransportInfo where
5243+ parseJSON = withObject "NodeTransportInfo" parse
5245+ parse o = NodeTransportInfo <$> (maybe (return mempty) parseProfiles =<< o .:? "profiles")
5246+ <*> parseJSON (Object o)
5247+ parseProfiles (Object o) | HM.null o = return []
5248+ parseProfiles v@(Array _) = parseJSON v
5249+ parseProfiles Null = return []
5250+ parseProfiles _ = fail "Could not parse profiles"
5252+instance FromJSON NodeNetworkInfo where
5253+ parseJSON = withObject "NodeNetworkInfo" parse
5255+ parse o = NodeNetworkInfo <$> o .: "primary_interface"
5256+ <*> (unMS <$> o .: "refresh_interval_in_millis")
5259+instance FromJSON NodeNetworkInterface where
5260+ parseJSON = withObject "NodeNetworkInterface" parse
5262+ parse o = NodeNetworkInterface <$> o .: "mac_address"
5266+newtype MaybeNA a = MaybeNA { unMaybeNA :: Maybe a }
5267+ deriving (Show, Eq)
5269+instance FromJSON a => FromJSON (MaybeNA a) where
5270+ parseJSON (String "NA") = pure $ MaybeNA Nothing
5271+ parseJSON o = MaybeNA . Just <$> parseJSON o