@@ -1,5279 +0,0 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveGeneric #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−-- {-# LANGUAGE NoMonomorphismRestriction #-}
8−{-# LANGUAGE NamedFieldPuns #-}
9−{-# LANGUAGE OverloadedStrings #-}
10−{-# LANGUAGE RecordWildCards #-}
11−{-# LANGUAGE UndecidableInstances #-}
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 (MonadReader (..),
374−import Control.Monad.State (MonadState)
375−import Control.Monad.Writer (MonadWriter)
377−import Data.Aeson.Types (Pair, Parser,
379− parseEither, parseMaybe)
380−import qualified Data.ByteString.Lazy.Char8 as L
382−import Data.Hashable (Hashable)
383−import qualified Data.HashMap.Strict as HM
384−import Data.List (foldl', intercalate,
386−import Data.List.NonEmpty (NonEmpty (..), toList)
387−import qualified Data.Map.Strict as M
389−import Data.Scientific (Scientific)
390−import Data.Semigroup
391−import Data.Text (Text)
392−import qualified Data.Text as T
393−import Data.Time.Calendar
394−import Data.Time.Clock (NominalDiffTime,
396−import Data.Time.Clock.POSIX
397−import qualified Data.Traversable as DT
398−import Data.Typeable (Typeable)
399−import qualified Data.Vector as V
400−import qualified Data.Version as Vers
402−import GHC.Generics (Generic)
403−import Network.HTTP.Client
404−import qualified Network.HTTP.Types.Method as NHTM
405−import qualified Text.ParserCombinators.ReadP as RP
406−import qualified Text.Read as TR
408−import Database.V1.Bloodhound.Types.Class
409−import Database.V1.Bloodhound.Types.Internal
412−-- >>> :set -XOverloadedStrings
413−-- >>> import Data.Aeson
414−-- >>> import Database.V1.Bloodhound
415−-- >>> let testServer = (Server "http://localhost:9200")
416−-- >>> let testIndex = IndexName "twitter"
417−-- >>> let testMapping = MappingName "tweet"
418−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
420−-- defaultIndexSettings is exported by Database.Bloodhound as well
421−-- no trailing slashes in servers, library handles building the path.
423−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
424−-- will be a noop. You can use the exported fields to customize it further, e.g.:
426−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
427−mkBHEnv :: Server -> Manager -> BHEnv
428−mkBHEnv s m = BHEnv s m return
430−newtype BH m a = BH {
431− unBH :: ReaderT BHEnv m a
432− } deriving ( Functor
446−instance MonadTrans BH where
449−instance (MonadReader r m) => MonadReader r (BH m) where
451− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
454−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
455− getBHEnv = BH getBHEnv
457−runBH :: BHEnv -> BH m a -> m a
458−runBH e f = runReaderT (unBH f) e
460−{-| 'Version' is embedded in 'Status' -}
461−data Version = Version { number :: VersionNumber
462− , build_hash :: BuildHash
463− , build_timestamp :: UTCTime
464− , build_snapshot :: Bool
465− , lucene_version :: VersionNumber } deriving (Eq, Read, Show, Generic, Typeable)
467−-- | Traditional software versioning number
468−newtype VersionNumber = VersionNumber { versionNumber :: Vers.Version
469− } deriving (Eq, Read, Show, Generic, Typeable, Ord)
471−{-| 'Status' is a data type for describing the JSON body returned by
472− Elasticsearch when you query its status. This was deprecated in 1.2.0.
474− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
477−data Status = Status { ok :: Maybe Bool
480− , version :: Version
481− , tagline :: Text } deriving (Eq, Read, Show, Generic)
483−{-| 'IndexSettings' is used to configure the shards and replicas when you create
484− an Elasticsearch Index.
486− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
490− IndexSettings { indexShards :: ShardCount
491− , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
493−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
494−defaultIndexSettings :: IndexSettings
495−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
498−{-| 'IndexOptimizationSettings' is used to configure index optimization. See
499− <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
502−data IndexOptimizationSettings =
503− IndexOptimizationSettings { maxNumSegments :: Maybe Int
504− -- ^ 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.
505− , onlyExpungeDeletes :: Bool
506− -- ^ 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.
507− , flushAfterOptimize :: Bool
508− -- ^ Should a flush be performed after the optimize.
509− } deriving (Eq, Show, Generic, Typeable)
512−{-| 'defaultIndexOptimizationSettings' implements the default settings that
513− ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
514− 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
516−defaultIndexOptimizationSettings :: IndexOptimizationSettings
517−defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
519−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
521− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
523−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
524− -- ^ The number of replicas each shard has.
525− | AutoExpandReplicas ReplicaBounds
526− | BlocksReadOnly Bool
527− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
529− -- ^ Set to True to disable read operations against the index.
531− -- ^ Set to True to disable write operations against the index.
532− | BlocksMetaData Bool
533− -- ^ Set to True to disable metadata operations against the index.
534− | RefreshInterval NominalDiffTime
535− -- ^ The async refresh interval of a shard
536− | IndexConcurrency Int
537− | FailOnMergeFailure Bool
538− | TranslogFlushThresholdOps Int
539− -- ^ When to flush on operations.
540− | TranslogFlushThresholdSize Bytes
541− -- ^ When to flush based on translog (bytes) size.
542− | TranslogFlushThresholdPeriod NominalDiffTime
543− -- ^ When to flush based on a period of not flushing.
544− | TranslogDisableFlush Bool
545− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
546− | CacheFilterMaxSize (Maybe Bytes)
547− -- ^ The maximum size of filter cache (per segment in shard).
548− | CacheFilterExpire (Maybe NominalDiffTime)
549− -- ^ The expire after access time for filter cache.
550− | GatewaySnapshotInterval NominalDiffTime
551− -- ^ The gateway snapshot interval (only applies to shared gateways).
552− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
553− -- ^ A node matching any rule will be allowed to host shards from the index.
554− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
555− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
556− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
557− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
558− | RoutingAllocationEnable AllocationPolicy
559− -- ^ Enables shard allocation for a specific index.
560− | RoutingAllocationShardsPerNode ShardCount
561− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
562− | RecoveryInitialShards InitialShardCount
563− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
564− | GCDeletes NominalDiffTime
565− | TTLDisablePurge Bool
566− -- ^ Disables temporarily the purge of expired docs.
567− | TranslogFSType FSType
568− | IndexCompoundFormat CompoundFormat
569− | IndexCompoundOnFlush Bool
570− | WarmerEnabled Bool
571− deriving (Eq, Show, Generic, Typeable)
573−data AllocationPolicy = AllocAll
574− -- ^ Allows shard allocation for all shards.
576− -- ^ Allows shard allocation only for primary shards.
578− -- ^ Allows shard allocation only for primary shards for new indices.
580− -- ^ No shard allocation is allowed
581− deriving (Eq, Read, Show, Generic, Typeable)
583−data ReplicaBounds = ReplicasBounded Int Int
584− | ReplicasLowerBounded Int
586− deriving (Eq, Read, Show, Generic, Typeable)
588−-- | A measure of bytes used for various configurations. You may want
589−-- to use smart constructors like 'gigabytes' for larger values.
599−newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
601−gigabytes :: Int -> Bytes
602−gigabytes n = megabytes (1000 * n)
605−megabytes :: Int -> Bytes
606−megabytes n = kilobytes (1000 * n)
609−kilobytes :: Int -> Bytes
610−kilobytes n = Bytes (1000 * n)
613−data FSType = FSSimple
614− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
616−data InitialShardCount = QuorumShards
617− | QuorumMinus1Shards
620− | ExplicitShards Int
621− deriving (Eq, Read, Show, Generic, Typeable)
623−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
624− , nodeAttrFilterValues :: NonEmpty Text}
625− deriving (Eq, Read, Show, Generic, Ord, Typeable)
627−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
629−data CompoundFormat = CompoundFileFormat Bool
630− | MergeSegmentVsTotalIndex Double
631− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
632− deriving (Eq, Read, Show, Generic, Typeable)
634−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
636−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
637− , sSummaryFixedSettings :: IndexSettings
638− , sSummaryUpdateable :: [UpdatableIndexSetting]}
639− deriving (Eq, Show, Generic, Typeable)
641−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
642−type Reply = Network.HTTP.Client.Response L.ByteString
643−type Method = NHTM.Method
645−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
647− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
649−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
651−data FieldType = GeoPointType
657− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
659−data FieldDefinition =
660− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
662−{-| An 'IndexTemplate' defines a template that will automatically be
663− applied to new indices created. The templates include both
664− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
665− controls if the template will be applied to the index created.
666− Specify mappings as follows: @[toJSON TweetMapping, ...]@
668− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
671− IndexTemplate { templatePattern :: TemplatePattern
672− , templateSettings :: Maybe IndexSettings
673− , templateMappings :: [Value]
677− MappingField { mappingFieldName :: FieldName
678− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
680−{-| Support for type reification of 'Mapping's is currently incomplete, for
681− now the mapping API verbiage expects a 'ToJSON'able blob.
683− Indexes have mappings, mappings are schemas for the documents contained in the
684− index. I'd recommend having only one mapping per index, always having a mapping,
685− and keeping different kinds of documents separated if possible.
687−data Mapping = Mapping { typeName :: TypeName
688− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
690−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
691− operation index, create, delete, and update. 'BulkIndex' behaves like an
692− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
694− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
697− BulkIndex IndexName MappingName DocId Value
698− | BulkCreate IndexName MappingName DocId Value
699− | BulkDelete IndexName MappingName DocId
700− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
702−{-| 'EsResult' describes the standard wrapper JSON document that you see in
703− successful Elasticsearch lookups or lookups that couldn't find the document.
705−data EsResult a = EsResult { _index :: Text
708− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
710−{-| 'EsResultFound' contains the document and its metadata inside of an
711− 'EsResult' when the document was successfully found.
713−data EsResultFound a = EsResultFound { _version :: DocVersion
714− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
716−{-| 'EsError' is the generic type that will be returned when there was a
717− problem. If you can't parse the expected response, its a good idea to
720−data EsError = EsError { errorStatus :: Int
721− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
723−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
724−returned by the ElasticSearch server. If you encounter this error, please
725−verify that your domain data types and FromJSON instances are working properly
726−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
727−sure that your mappings are correct, then this error may be an indication of an
728−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
729−and be sure to include the exception body.
731−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
732− deriving (Eq, Read, Show, Generic, Typeable)
734−instance Exception EsProtocolException
736−data IndexAlias = IndexAlias { srcIndex :: IndexName
737− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
739−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
741−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
742− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
744−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
745− , aliasCreateFilter :: Maybe Filter}
746− deriving (Read, Show, Eq, Generic, Typeable)
748−data AliasRouting = AllAliasRouting RoutingValue
749− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
750− deriving (Read, Show, Eq, Generic, Typeable)
752−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
754−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
756−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
758−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
760−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
761−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
762− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
764−{-| 'DocVersion' is an integer version number for a document between 1
765−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
767−newtype DocVersion = DocVersion {
768− docVersionNumber :: Int
769− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
771−-- | Smart constructor for in-range doc version
772−mkDocVersion :: Int -> Maybe DocVersion
774− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
776− | otherwise = Nothing
779−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
780−own version numbers instead of ones from ES.
782−newtype ExternalDocVersion = ExternalDocVersion DocVersion
783− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
785−{-| 'VersionControl' is specified when indexing documents as a
786−optimistic concurrency control.
788−data VersionControl = NoVersionControl
789− -- ^ Don't send a version. This is a pure overwrite.
790− | InternalVersion DocVersion
791− -- ^ Use the default ES versioning scheme. Only
792− -- index the document if the version is the same
793− -- as the one specified. Only applicable to
794− -- updates, as you should be getting Version from
796− | ExternalGT ExternalDocVersion
797− -- ^ Use your own version numbering. Only index
798− -- the document if the version is strictly higher
799− -- OR the document doesn't exist. The given
800− -- version will be used as the new version number
801− -- for the stored document. N.B. All updates must
802− -- increment this number, meaning there is some
803− -- global, external ordering of updates.
804− | ExternalGTE ExternalDocVersion
805− -- ^ Use your own version numbering. Only index
806− -- the document if the version is equal or higher
807− -- than the stored version. Will succeed if there
808− -- is no existing document. The given version will
809− -- be used as the new version number for the
810− -- stored document. Use with care, as this could
811− -- result in data loss.
812− | ForceVersion ExternalDocVersion
813− -- ^ The document will always be indexed and the
814− -- given version will be the new version. This is
815− -- typically used for correcting errors. Use with
816− -- care, as this could result in data loss.
817− deriving (Read, Show, Eq, Generic, Ord)
819−{-| 'DocumentParent' is used to specify a parent document.
821−newtype DocumentParent = DocumentParent DocId
822− deriving (Eq, Read, Show, Generic, Typeable)
824−{-| 'IndexDocumentSettings' are special settings supplied when indexing
825−a document. For the best backwards compatiblity when new fields are
826−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
828−data IndexDocumentSettings =
829− IndexDocumentSettings { idsVersionControl :: VersionControl
830− , idsParent :: Maybe DocumentParent
831− } deriving (Eq, Read, Show, Generic, Typeable)
833−{-| Reasonable default settings. Chooses no version control and no parent.
835−defaultIndexDocumentSettings :: IndexDocumentSettings
836−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
838−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
839− dependent with later sorts acting as tie-breakers for earlier sorts.
841−type Sort = [SortSpec]
843−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
844− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
845− 'DistanceUnit' to express "nearness" to a single geographical point as a
848−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
850−data SortSpec = DefaultSortSpec DefaultSort
851− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
853−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
854− 'mkSort' convenience function for when you want to specify only the most
857−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
860− DefaultSort { sortFieldName :: FieldName
861− , sortOrder :: SortOrder
863− , ignoreUnmapped :: Bool
864− , sortMode :: Maybe SortMode
865− , missingSort :: Maybe Missing
866− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
868−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
869− encoded into "asc" or "desc" when turned into JSON.
871−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
873−data SortOrder = Ascending
874− | Descending deriving (Eq, Read, Show, Generic, Typeable)
876−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
877− sorted last, first, or using a custom value as a substitute.
879−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
881−data Missing = LastMissing
883− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
885−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
887−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
889−data SortMode = SortMin
892− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
894−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
895− that you can concisely describe the usual kind of 'SortSpec's you want.
897−mkSort :: FieldName -> SortOrder -> DefaultSort
898−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
900−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
901− 'Query's cannot be cached.
903−type Cache = Bool -- caching on/off
904−defaultCache :: Cache
907−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
909−type PrefixValue = Text
911−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
912− JSON encoding baked in. Used all over the place.
914−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
916−{-| 'ShardCount' is part of 'IndexSettings'
918−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
920−{-| 'ReplicaCount' is part of 'IndexSettings'
922−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
924−{-| 'IndexName' is used to describe which index to query/create/delete
926−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
928−{-| 'IndexSelection' is used for APIs which take a single index, a list of
929− indexes, or the special @_all@ index.
931−--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.
932−data IndexSelection = IndexList (NonEmpty IndexName)
933− | AllIndexes deriving (Eq, Generic, Show, Typeable)
935−{-| '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.
937−data NodeSelection = LocalNode
938− -- ^ Whatever node receives this request
939− | NodeList (NonEmpty NodeSelector)
940− | AllNodes deriving (Eq, Generic, Show, Typeable)
943−-- | An exact match or pattern to identify a node. Note that All of
944−-- these options support wildcarding, so your node name, server, attr
945−-- name can all contain * characters to be a fuzzy match.
946−data NodeSelector = NodeByName NodeName
947− | NodeByFullNodeId FullNodeId
949− -- ^ e.g. 10.0.0.1 or even 10.0.0.*
950− | NodeByAttribute NodeAttrName Text
951− -- ^ NodeAttrName can be a pattern, e.g. rack*. The value can too.
952− deriving (Eq, Generic, Show, Typeable)
954−{-| 'TemplateName' is used to describe which template to query/create/delete
956−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
958−{-| 'TemplatePattern' represents a pattern which is matched against index names
960−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
962−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
963− the data in the indices.
965−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
967−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
968− Can be set by the user or created by ES itself. Often used in client
969− functions for poking at specific documents.
971−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
973−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
975−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
977−{-| 'FieldName' is used all over the place wherever a specific field within
978− a document needs to be specified, usually in 'Query's or 'Filter's.
980−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
983−{-| 'Script' is often used in place of 'FieldName' to specify more
984−complex ways of extracting a value from a document.
986−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
988−{-| 'CacheName' is used in 'RegexpFilter' for describing the
989− 'CacheKey' keyed caching behavior.
991−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
993−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
996− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
998− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1000− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1001−newtype CutoffFrequency =
1002− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1004− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1005−newtype MaxExpansions =
1006− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1008−{-| 'Lenient', if set to true, will cause format based failures to be
1009− ignored. I don't know what the bloody default is, Elasticsearch
1010− documentation didn't say what it was. Let me know if you figure it out.
1013− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1014−newtype Tiebreaker =
1015− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1017− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1018−newtype BoostTerms =
1019− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1021−{-| 'MinimumMatch' controls how many should clauses in the bool query should
1022− match. Can be an absolute value (2) or a percentage (30%) or a
1023− combination of both.
1025−newtype MinimumMatch =
1026− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1027−newtype DisableCoord =
1028− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1029−newtype IgnoreTermFrequency =
1030− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1031−newtype MinimumTermFrequency =
1032− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1033−newtype MaxQueryTerms =
1034− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1036− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1038−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
1039−newtype PrefixLength =
1040− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1042− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1043−newtype PercentMatch =
1044− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1046− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1048− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1050−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
1051− heavy, because all terms in the index need to be examined, just in case
1052− they match. Leading wildcards can be disabled by setting
1053− 'AllowLeadingWildcard' to false. -}
1054−newtype AllowLeadingWildcard =
1055− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1056−newtype LowercaseExpanded =
1057− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1058−newtype EnablePositionIncrements =
1059− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1061−{-| By default, wildcard terms in a query are not analyzed.
1062− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
1064−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1066−{-| 'GeneratePhraseQueries' defaults to false.
1068−newtype GeneratePhraseQueries =
1069− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1071−{-| 'Locale' is used for string conversions - defaults to ROOT.
1073−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1074−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1075−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1077−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
1078− phrase matches. Default is 0.
1080−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1081−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1082−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1084−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
1085−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
1087−{-| 'unpackId' is a silly convenience function that gets used once.
1089−unpackId :: DocId -> Text
1090−unpackId (DocId docId) = docId
1092−type TrackSortScores = Bool
1093−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1094−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
1096−data Search = Search { queryBody :: Maybe Query
1097− , filterBody :: Maybe Filter
1098− , sortBody :: Maybe Sort
1099− , aggBody :: Maybe Aggregations
1100− , highlight :: Maybe Highlights
1102− , trackSortScores :: TrackSortScores
1105− , searchType :: SearchType
1106− , fields :: Maybe [FieldName]
1107− , source :: Maybe Source } deriving (Eq, Read, Show, Generic, Typeable)
1109−data SearchType = SearchTypeQueryThenFetch
1110− | SearchTypeDfsQueryThenFetch
1113− | SearchTypeQueryAndFetch
1114− | SearchTypeDfsQueryAndFetch
1115− deriving (Eq, Read, Show, Generic, Typeable)
1119− | SourcePatterns PatternOrPatterns
1120− | SourceIncludeExclude Include Exclude
1121− deriving (Read, Show, Eq, Generic, Typeable)
1123−data PatternOrPatterns = PopPattern Pattern
1124− | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1126−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1127−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1129−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
1131−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1132− , highlightFields :: [FieldHighlight]
1133− } deriving (Read, Show, Eq, Generic, Typeable)
1135−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1136− deriving (Read, Show, Eq, Generic, Typeable)
1139−data HighlightSettings = Plain PlainHighlight
1140− | Postings PostingsHighlight
1141− | FastVector FastVectorHighlight
1142− deriving (Read, Show, Eq, Generic, Typeable)
1143−data PlainHighlight =
1144− PlainHighlight { plainCommon :: Maybe CommonHighlight
1145− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1147− -- This requires that index_options are set to 'offset' in the mapping.
1148−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1150−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1151−data FastVectorHighlight =
1152− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1153− , fvNonPostSettings :: Maybe NonPostings
1154− , boundaryChars :: Maybe Text
1155− , boundaryMaxScan :: Maybe Int
1156− , fragmentOffset :: Maybe Int
1157− , matchedFields :: [Text]
1158− , phraseLimit :: Maybe Int
1159− } deriving (Read, Show, Eq, Generic, Typeable)
1161−data CommonHighlight =
1162− CommonHighlight { order :: Maybe Text
1163− , forceSource :: Maybe Bool
1164− , tag :: Maybe HighlightTag
1165− , encoder :: Maybe HighlightEncoder
1166− , noMatchSize :: Maybe Int
1167− , highlightQuery :: Maybe Query
1168− , requireFieldMatch :: Maybe Bool
1169− } deriving (Read, Show, Eq, Generic, Typeable)
1171−-- Settings that are only applicable to FastVector and Plain highlighters.
1173− NonPostings { fragmentSize :: Maybe Int
1174− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1176−data HighlightEncoder = DefaultEncoder
1178− deriving (Read, Show, Eq, Generic, Typeable)
1180−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1181−data HighlightTag = TagSchema Text
1182− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1183− deriving (Read, Show, Eq, Generic, Typeable)
1187− TermQuery Term (Maybe Boost)
1188− | TermsQuery Text (NonEmpty Text)
1189− | QueryMatchQuery MatchQuery
1190− | QueryMultiMatchQuery MultiMatchQuery
1191− | QueryBoolQuery BoolQuery
1192− | QueryBoostingQuery BoostingQuery
1193− | QueryCommonTermsQuery CommonTermsQuery
1194− | ConstantScoreFilter Filter Boost
1195− | ConstantScoreQuery Query Boost
1196− | QueryDisMaxQuery DisMaxQuery
1197− | QueryFilteredQuery FilteredQuery
1198− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1199− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1200− | QueryFuzzyQuery FuzzyQuery
1201− | QueryHasChildQuery HasChildQuery
1202− | QueryHasParentQuery HasParentQuery
1203− | IdsQuery MappingName [DocId]
1204− | QueryIndicesQuery IndicesQuery
1205− | MatchAllQuery (Maybe Boost)
1206− | QueryMoreLikeThisQuery MoreLikeThisQuery
1207− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1208− | QueryNestedQuery NestedQuery
1209− | QueryPrefixQuery PrefixQuery
1210− | QueryQueryStringQuery QueryStringQuery
1211− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1212− | QueryRangeQuery RangeQuery
1213− | QueryRegexpQuery RegexpQuery
1214− deriving (Eq, Read, Show, Generic, Typeable)
1217− RegexpQuery { regexpQueryField :: FieldName
1218− , regexpQuery :: Regexp
1219− , regexpQueryFlags :: RegexpFlags
1220− , regexpQueryBoost :: Maybe Boost
1221− } deriving (Eq, Read, Show, Generic, Typeable)
1224− RangeQuery { rangeQueryField :: FieldName
1225− , rangeQueryRange :: RangeValue
1226− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1228−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1229−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1231−data SimpleQueryStringQuery =
1232− SimpleQueryStringQuery
1233− { simpleQueryStringQuery :: QueryString
1234− , simpleQueryStringField :: Maybe FieldOrFields
1235− , simpleQueryStringOperator :: Maybe BooleanOperator
1236− , simpleQueryStringAnalyzer :: Maybe Analyzer
1237− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1238− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1239− , simpleQueryStringLocale :: Maybe Locale
1240− } deriving (Eq, Read, Show, Generic, Typeable)
1242−data SimpleQueryFlag =
1247− | SimpleQueryPrefix
1248− | SimpleQueryPhrase
1249− | SimpleQueryPrecedence
1250− | SimpleQueryEscape
1251− | SimpleQueryWhitespace
1254− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1256−-- use_dis_max and tie_breaker when fields are plural?
1257−data QueryStringQuery =
1259− { queryStringQuery :: QueryString
1260− , queryStringDefaultField :: Maybe FieldName
1261− , queryStringOperator :: Maybe BooleanOperator
1262− , queryStringAnalyzer :: Maybe Analyzer
1263− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1264− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1265− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1266− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1267− , queryStringFuzziness :: Maybe Fuzziness
1268− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1269− , queryStringPhraseSlop :: Maybe PhraseSlop
1270− , queryStringBoost :: Maybe Boost
1271− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1272− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1273− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1274− , queryStringLenient :: Maybe Lenient
1275− , queryStringLocale :: Maybe Locale
1276− } deriving (Eq, Read, Show, Generic, Typeable)
1278−mkQueryStringQuery :: QueryString -> QueryStringQuery
1279−mkQueryStringQuery qs =
1280− QueryStringQuery qs Nothing Nothing
1281− Nothing Nothing Nothing Nothing
1282− Nothing Nothing Nothing Nothing
1283− Nothing Nothing Nothing Nothing
1286−data FieldOrFields = FofField FieldName
1287− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1291− { prefixQueryField :: FieldName
1292− , prefixQueryPrefixValue :: Text
1293− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1297− { nestedQueryPath :: QueryPath
1298− , nestedQueryScoreType :: ScoreType
1299− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1301−data MoreLikeThisFieldQuery =
1302− MoreLikeThisFieldQuery
1303− { moreLikeThisFieldText :: Text
1304− , moreLikeThisFieldFields :: FieldName
1305− -- default 0.3 (30%)
1306− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1307− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1308− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1309− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1310− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1311− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1312− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1313− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1314− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1315− , moreLikeThisFieldBoost :: Maybe Boost
1316− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1317− } deriving (Eq, Read, Show, Generic, Typeable)
1319−data MoreLikeThisQuery =
1321− { moreLikeThisText :: Text
1322− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1323− -- default 0.3 (30%)
1324− , moreLikeThisPercentMatch :: Maybe PercentMatch
1325− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1326− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1327− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1328− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1329− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1330− , moreLikeThisMinWordLength :: Maybe MinWordLength
1331− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1332− , moreLikeThisBoostTerms :: Maybe BoostTerms
1333− , moreLikeThisBoost :: Maybe Boost
1334− , moreLikeThisAnalyzer :: Maybe Analyzer
1335− } deriving (Eq, Read, Show, Generic, Typeable)
1339− { indicesQueryIndices :: [IndexName]
1340− , indicesQuery :: Query
1342− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1344−data HasParentQuery =
1346− { hasParentQueryType :: TypeName
1347− , hasParentQuery :: Query
1348− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1350−data HasChildQuery =
1352− { hasChildQueryType :: TypeName
1353− , hasChildQuery :: Query
1354− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1360− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1363− FuzzyQuery { fuzzyQueryField :: FieldName
1364− , fuzzyQueryValue :: Text
1365− , fuzzyQueryPrefixLength :: PrefixLength
1366− , fuzzyQueryMaxExpansions :: MaxExpansions
1367− , fuzzyQueryFuzziness :: Fuzziness
1368− , fuzzyQueryBoost :: Maybe Boost
1369− } deriving (Eq, Read, Show, Generic, Typeable)
1371−data FuzzyLikeFieldQuery =
1372− FuzzyLikeFieldQuery
1373− { fuzzyLikeField :: FieldName
1374− -- anaphora is good for the soul.
1375− , fuzzyLikeFieldText :: Text
1376− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1377− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1378− , fuzzyLikeFieldFuzziness :: Fuzziness
1379− , fuzzyLikeFieldPrefixLength :: PrefixLength
1380− , fuzzyLikeFieldBoost :: Boost
1381− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1382− } deriving (Eq, Read, Show, Generic, Typeable)
1384−data FuzzyLikeThisQuery =
1386− { fuzzyLikeFields :: [FieldName]
1387− , fuzzyLikeText :: Text
1388− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1389− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1390− , fuzzyLikeFuzziness :: Fuzziness
1391− , fuzzyLikePrefixLength :: PrefixLength
1392− , fuzzyLikeBoost :: Boost
1393− , fuzzyLikeAnalyzer :: Maybe Analyzer
1394− } deriving (Eq, Read, Show, Generic, Typeable)
1396−data FilteredQuery =
1398− { filteredQuery :: Query
1399− , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1402− DisMaxQuery { disMaxQueries :: [Query]
1404− , disMaxTiebreaker :: Tiebreaker
1405− , disMaxBoost :: Maybe Boost
1406− } deriving (Eq, Read, Show, Generic, Typeable)
1409− MatchQuery { matchQueryField :: FieldName
1410− , matchQueryQueryString :: QueryString
1411− , matchQueryOperator :: BooleanOperator
1412− , matchQueryZeroTerms :: ZeroTermsQuery
1413− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1414− , matchQueryMatchType :: Maybe MatchQueryType
1415− , matchQueryAnalyzer :: Maybe Analyzer
1416− , matchQueryMaxExpansions :: Maybe MaxExpansions
1417− , matchQueryLenient :: Maybe Lenient
1418− , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1420−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1421− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1423−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1424−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1426−data MatchQueryType =
1428− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1430−data MultiMatchQuery =
1431− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1432− , multiMatchQueryString :: QueryString
1433− , multiMatchQueryOperator :: BooleanOperator
1434− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1435− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1436− , multiMatchQueryType :: Maybe MultiMatchQueryType
1437− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1438− , multiMatchQueryAnalyzer :: Maybe Analyzer
1439− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1440− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1442−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1443− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1444− make a 'MultiMatchQuery'.
1447−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1448−mkMultiMatchQuery matchFields query =
1449− MultiMatchQuery matchFields query
1450− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1452−data MultiMatchQueryType =
1453− MultiMatchBestFields
1454− | MultiMatchMostFields
1455− | MultiMatchCrossFields
1457− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1460− BoolQuery { boolQueryMustMatch :: [Query]
1461− , boolQueryMustNotMatch :: [Query]
1462− , boolQueryShouldMatch :: [Query]
1463− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1464− , boolQueryBoost :: Maybe Boost
1465− , boolQueryDisableCoord :: Maybe DisableCoord
1466− } deriving (Eq, Read, Show, Generic, Typeable)
1468−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1469−mkBoolQuery must mustNot should =
1470− BoolQuery must mustNot should Nothing Nothing Nothing
1472−data BoostingQuery =
1473− BoostingQuery { positiveQuery :: Query
1474− , negativeQuery :: Query
1475− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1477−data CommonTermsQuery =
1478− CommonTermsQuery { commonField :: FieldName
1479− , commonQuery :: QueryString
1480− , commonCutoffFrequency :: CutoffFrequency
1481− , commonLowFreqOperator :: BooleanOperator
1482− , commonHighFreqOperator :: BooleanOperator
1483− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1484− , commonBoost :: Maybe Boost
1485− , commonAnalyzer :: Maybe Analyzer
1486− , commonDisableCoord :: Maybe DisableCoord
1487− } deriving (Eq, Read, Show, Generic, Typeable)
1489−data CommonMinimumMatch =
1490− CommonMinimumMatchHighLow MinimumMatchHighLow
1491− | CommonMinimumMatch MinimumMatch
1492− deriving (Eq, Read, Show, Generic, Typeable)
1494−data MinimumMatchHighLow =
1495− MinimumMatchHighLow { lowFreq :: MinimumMatch
1496− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1498−data Filter = AndFilter [Filter] Cache
1499− | OrFilter [Filter] Cache
1500− | NotFilter Filter Cache
1502− | BoolFilter BoolMatch
1503− | ExistsFilter FieldName -- always cached
1504− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1505− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1506− | GeoDistanceRangeFilter GeoPoint DistanceRange
1507− | GeoPolygonFilter FieldName [LatLon]
1508− | IdsFilter MappingName [DocId]
1510− | MissingFilter FieldName Existence NullValue
1511− | PrefixFilter FieldName PrefixValue Cache
1512− | QueryFilter Query Cache
1513− | RangeFilter FieldName RangeValue RangeExecution Cache
1514− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1515− | TermFilter Term Cache
1516− deriving (Eq, Read, Show, Generic, Typeable)
1518−data ZeroTermsQuery = ZeroTermsNone
1519− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1521−data RangeExecution = RangeExecutionIndex
1522− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1524−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1526−data RegexpFlags = AllRegexpFlags
1528− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1530−data RegexpFlag = AnyString
1535− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1537−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1538−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1539−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1540−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1542−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1543−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1544−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1545−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1547−data RangeValue = RangeDateLte LessThanEqD
1548− | RangeDateLt LessThanD
1549− | RangeDateGte GreaterThanEqD
1550− | RangeDateGt GreaterThanD
1551− | RangeDateGtLt GreaterThanD LessThanD
1552− | RangeDateGteLte GreaterThanEqD LessThanEqD
1553− | RangeDateGteLt GreaterThanEqD LessThanD
1554− | RangeDateGtLte GreaterThanD LessThanEqD
1555− | RangeDoubleLte LessThanEq
1556− | RangeDoubleLt LessThan
1557− | RangeDoubleGte GreaterThanEq
1558− | RangeDoubleGt GreaterThan
1559− | RangeDoubleGtLt GreaterThan LessThan
1560− | RangeDoubleGteLte GreaterThanEq LessThanEq
1561− | RangeDoubleGteLt GreaterThanEq LessThan
1562− | RangeDoubleGtLte GreaterThan LessThanEq
1563− deriving (Eq, Read, Show, Generic, Typeable)
1565−rangeValueToPair :: RangeValue -> [Pair]
1566−rangeValueToPair rv = case rv of
1567− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1568− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1569− RangeDateLt (LessThanD t) -> ["lt" .= t]
1570− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1571− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1572− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1573− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1574− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1575− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1576− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1577− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1578− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1579− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1580− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1581− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1582− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1584−data Term = Term { termField :: Text
1585− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1587−data BoolMatch = MustMatch Term Cache
1588− | MustNotMatch Term Cache
1589− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1591−-- "memory" or "indexed"
1592−data GeoFilterType = GeoFilterMemory
1593− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1595−data LatLon = LatLon { lat :: Double
1596− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1598−data GeoBoundingBox =
1599− GeoBoundingBox { topLeft :: LatLon
1600− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1602−data GeoBoundingBoxConstraint =
1603− GeoBoundingBoxConstraint { geoBBField :: FieldName
1604− , constraintBox :: GeoBoundingBox
1605− , bbConstraintcache :: Cache
1606− , geoType :: GeoFilterType
1607− } deriving (Eq, Read, Show, Generic, Typeable)
1610− GeoPoint { geoField :: FieldName
1611− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
1613−data DistanceUnit = Miles
1621− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
1623−data DistanceType = Arc
1624− | SloppyArc -- doesn't exist <1.0
1625− | Plane deriving (Eq, Read, Show, Generic, Typeable)
1627−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1628− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
1631− Distance { coefficient :: Double
1632− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1634−data DistanceRange =
1635− DistanceRange { distanceFrom :: Distance
1636− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
1638−data SearchResult a =
1639− SearchResult { took :: Int
1641− , shards :: ShardResult
1642− , searchHits :: SearchHits a
1643− , aggregations :: Maybe AggregationResults
1644− , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
1646−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
1648−type Score = Maybe Double
1651− SearchHits { hitsTotal :: Int
1652− , maxScore :: Score
1653− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1655−instance Semigroup (SearchHits a) where
1656− (SearchHits ta ma ha) <> (SearchHits tb mb hb) = SearchHits (ta + tb) (max ma mb) (ha <> hb)
1658−instance Monoid (SearchHits a) where
1659− mempty = SearchHits 0 Nothing mempty
1663− Hit { hitIndex :: IndexName
1664− , hitType :: MappingName
1665− , hitDocId :: DocId
1666− , hitScore :: Score
1667− , hitSource :: Maybe a
1668− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1671− ShardResult { shardTotal :: Int
1672− , shardsSuccessful :: Int
1673− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1675−type HitHighlight = M.Map Text [Text]
1677−showText :: Show a => a -> Text
1678−showText = T.pack . show
1680−readMay :: Read a => String -> Maybe a
1681−readMay s = case reads s of
1682− (a, ""):_ -> Just a
1685−parseReadText :: Read a => Text -> Parser a
1686−parseReadText = maybe mzero return . readMay . T.unpack
1688−type Aggregations = M.Map Text Aggregation
1690−emptyAggregations :: Aggregations
1691−emptyAggregations = M.empty
1693−mkAggregations :: Text -> Aggregation -> Aggregations
1694−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1696−data TermOrder = TermOrder{ termSortField :: Text
1697− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1699−data TermInclusion = TermInclusion Text
1700− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1702−data CollectionMode = BreadthFirst
1703− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1705−data ExecutionHint = Ordinals
1707− | GlobalOrdinalsHash
1708− | GlobalOrdinalsLowCardinality
1709− | Map deriving (Eq, Read, Show, Generic, Typeable)
1711−data TimeInterval = Weeks
1715− | Seconds deriving Eq
1717−data Interval = Year
1725− | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1727−data Aggregation = TermsAgg TermsAggregation
1728− | CardinalityAgg CardinalityAggregation
1729− | DateHistogramAgg DateHistogramAggregation
1730− | ValueCountAgg ValueCountAggregation
1731− | FilterAgg FilterAggregation
1732− | DateRangeAgg DateRangeAggregation
1733− | MissingAgg MissingAggregation
1734− | TopHitsAgg TopHitsAggregation
1735− deriving (Eq, Read, Show, Generic, Typeable)
1737−data TopHitsAggregation = TopHitsAggregation
1738− { taFrom :: Maybe From
1739− , taSize :: Maybe Size
1740− , taSort :: Maybe Sort
1741− } deriving (Eq, Read, Show)
1743−data MissingAggregation = MissingAggregation
1745− } deriving (Eq, Read, Show, Generic, Typeable)
1747−data TermsAggregation = TermsAggregation { term :: Either Text Text
1748− , termInclude :: Maybe TermInclusion
1749− , termExclude :: Maybe TermInclusion
1750− , termOrder :: Maybe TermOrder
1751− , termMinDocCount :: Maybe Int
1752− , termSize :: Maybe Int
1753− , termShardSize :: Maybe Int
1754− , termCollectMode :: Maybe CollectionMode
1755− , termExecutionHint :: Maybe ExecutionHint
1756− , termAggs :: Maybe Aggregations
1757− } deriving (Eq, Read, Show, Generic, Typeable)
1759−data CardinalityAggregation = CardinalityAggregation { cardinalityField :: FieldName,
1760− precisionThreshold :: Maybe Int
1761− } deriving (Eq, Read, Show, Generic, Typeable)
1763−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1764− , dateInterval :: Interval
1765− , dateFormat :: Maybe Text
1766− -- pre and post deprecated in 1.5
1767− , datePreZone :: Maybe Text
1768− , datePostZone :: Maybe Text
1769− , datePreOffset :: Maybe Text
1770− , datePostOffset :: Maybe Text
1771− , dateAggs :: Maybe Aggregations
1772− } deriving (Eq, Read, Show, Generic, Typeable)
1775−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1776− , draFormat :: Maybe Text
1777− , draRanges :: NonEmpty DateRangeAggRange
1778− } deriving (Eq, Read, Show, Generic, Typeable)
1780−data DateRangeAggRange = DateRangeFrom DateMathExpr
1781− | DateRangeTo DateMathExpr
1782− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1784−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1785−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1788−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1789−data DateMathAnchor = DMNow
1790− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1792−data DateMathModifier = AddTime Int DateMathUnit
1793− | SubtractTime Int DateMathUnit
1794− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1796−data DateMathUnit = DMYear
1802− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1804−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1805−data ValueCountAggregation = FieldValueCount FieldName
1806− | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1808−-- | 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.
1809−data FilterAggregation = FilterAggregation { faFilter :: Filter
1810− , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1812−mkTermsAggregation :: Text -> TermsAggregation
1813−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1815−mkTermsScriptAggregation :: Text -> TermsAggregation
1816−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1818−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1819−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1821−mkCardinalityAggregation :: FieldName -> CardinalityAggregation
1822−mkCardinalityAggregation t = CardinalityAggregation t Nothing
1824−instance ToJSON Version where
1825− toJSON Version {..} = object ["number" .= number
1826− ,"build_hash" .= build_hash
1827− ,"build_timestamp" .= build_timestamp
1828− ,"build_snapshot" .= build_snapshot
1829− ,"lucene_version" .= lucene_version]
1831−instance FromJSON Version where
1832− parseJSON = withObject "Version" parse
1833− where parse o = Version
1835− <*> o .: "build_hash"
1836− <*> o .: "build_timestamp"
1837− <*> o .: "build_snapshot"
1838− <*> o .: "lucene_version"
1840−instance ToJSON VersionNumber where
1841− toJSON = toJSON . Vers.showVersion . versionNumber
1843−instance FromJSON VersionNumber where
1844− parseJSON = withText "VersionNumber" (parse . T.unpack)
1846− parse s = case filter (null . snd)(RP.readP_to_S Vers.parseVersion s) of
1847− [(v, _)] -> pure (VersionNumber v)
1848− [] -> fail ("Invalid version string " ++ s)
1849− xs -> fail ("Ambiguous version string " ++ s ++ " (" ++ intercalate ", " (Vers.showVersion . fst <$> xs) ++ ")")
1851−instance ToJSON TermOrder where
1852− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1854−instance ToJSON TermInclusion where
1855− toJSON (TermInclusion x) = toJSON x
1856− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1859−instance ToJSON CollectionMode where
1860− toJSON BreadthFirst = "breadth_first"
1861− toJSON DepthFirst = "depth_first"
1863−instance ToJSON ExecutionHint where
1864− toJSON Ordinals = "ordinals"
1865− toJSON GlobalOrdinals = "global_ordinals"
1866− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1867− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1870−instance ToJSON Interval where
1871− toJSON Year = "year"
1872− toJSON Quarter = "quarter"
1873− toJSON Month = "month"
1874− toJSON Week = "week"
1876− toJSON Hour = "hour"
1877− toJSON Minute = "minute"
1878− toJSON Second = "second"
1879− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1881−instance Show TimeInterval where
1888−instance Read TimeInterval where
1889− readPrec = f =<< TR.get
1891− f 'w' = return Weeks
1892− f 'd' = return Days
1893− f 'h' = return Hours
1894− f 'm' = return Minutes
1895− f 's' = return Seconds
1896− f _ = fail "TimeInterval expected one of w, d, h, m, s"
1898−instance ToJSON Aggregation where
1899− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1900− omitNulls ["terms" .= omitNulls [ toJSON' term,
1901− "include" .= include,
1902− "exclude" .= exclude,
1904− "min_doc_count" .= minDocCount,
1906− "shard_size" .= shardSize,
1907− "collect_mode" .= collectMode,
1908− "execution_hint" .= executionHint
1910− "aggs" .= termAggs ]
1912− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1914− toJSON (CardinalityAgg (CardinalityAggregation field precisionThreshold)) =
1915− object ["cardinality" .= omitNulls [ "field" .= field,
1916− "precisionThreshold" .= precisionThreshold
1920− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1921− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1922− "interval" .= interval,
1923− "format" .= format,
1924− "pre_zone" .= preZone,
1925− "post_zone" .= postZone,
1926− "pre_offset" .= preOffset,
1927− "post_offset" .= postOffset
1929− "aggs" .= dateHistoAggs ]
1930− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1931− where v = case a of
1932− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1933− (ScriptValueCount (Script s)) -> object ["script" .= s]
1934− toJSON (FilterAgg (FilterAggregation filt ags)) =
1935− omitNulls [ "filter" .= filt
1937− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1939− toJSON (MissingAgg (MissingAggregation{..})) =
1940− object ["missing" .= object ["field" .= maField]]
1942− toJSON (TopHitsAgg (TopHitsAggregation mfrom msize msort)) =
1943− omitNulls ["top_hits" .= omitNulls [ "size" .= msize
1949−instance ToJSON DateRangeAggregation where
1950− toJSON DateRangeAggregation {..} =
1951− omitNulls [ "field" .= draField
1952− , "format" .= draFormat
1953− , "ranges" .= toList draRanges
1956−instance ToJSON DateRangeAggRange where
1957− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1958− toJSON (DateRangeTo e) = object [ "to" .= e ]
1959− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1961−instance ToJSON DateMathExpr where
1962− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1963− where fmtA DMNow = "now"
1964− fmtA (DMDate date) = (T.pack $ showGregorian date) <> "||"
1965− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1966− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1967− fmtMod (RoundDownTo u) = "/" <> fmtU u
1973− fmtU DMMinute = "m"
1974− fmtU DMSecond = "s"
1977−type AggregationResults = M.Map Text Value
1979−class BucketAggregation a where
1980− key :: a -> BucketValue
1981− docCount :: a -> Int
1982− aggs :: a -> Maybe AggregationResults
1985−data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1987−data BucketValue = TextValue Text
1988− | ScientificValue Scientific
1989− | BoolValue Bool deriving (Read, Show)
1991−data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1993−data TopHitResult a = TopHitResult { tarHits :: (SearchHits a)
1996−data TermsResult = TermsResult { termKey :: BucketValue
1997− , termsDocCount :: Int
1998− , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
2000−data DateHistogramResult = DateHistogramResult { dateKey :: Int
2001− , dateKeyStr :: Maybe Text
2002− , dateDocCount :: Int
2003− , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
2005−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
2006− , dateRangeFrom :: Maybe UTCTime
2007− , dateRangeFromAsString :: Maybe Text
2008− , dateRangeTo :: Maybe UTCTime
2009− , dateRangeToAsString :: Maybe Text
2010− , dateRangeDocCount :: Int
2011− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
2013−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
2014−toTerms = toAggResult
2016−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
2017−toDateHistogram = toAggResult
2019−toMissing :: Text -> AggregationResults -> Maybe MissingResult
2020−toMissing = toAggResult
2022−toTopHits :: (FromJSON a) => Text -> AggregationResults -> Maybe (TopHitResult a)
2023−toTopHits = toAggResult
2025−toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
2026−toAggResult t a = M.lookup t a >>= deserialize
2027− where deserialize = parseMaybe parseJSON
2029−instance BucketAggregation TermsResult where
2031− docCount = termsDocCount
2034−instance BucketAggregation DateHistogramResult where
2035− key = TextValue . showText . dateKey
2036− docCount = dateDocCount
2037− aggs = dateHistogramAggs
2039−instance BucketAggregation DateRangeResult where
2040− key = TextValue . dateRangeKey
2041− docCount = dateRangeDocCount
2042− aggs = dateRangeAggs
2044−instance (FromJSON a) => FromJSON (Bucket a) where
2045− parseJSON (Object v) = Bucket <$>
2047− parseJSON _ = mempty
2049−instance FromJSON BucketValue where
2050− parseJSON (String t) = return $ TextValue t
2051− parseJSON (Number s) = return $ ScientificValue s
2052− parseJSON (Bool b) = return $ BoolValue b
2053− parseJSON _ = mempty
2055−instance FromJSON MissingResult where
2056− parseJSON = withObject "MissingResult" parse
2057− where parse v = MissingResult <$> v .: "doc_count"
2059−instance FromJSON TermsResult where
2060− parseJSON (Object v) = TermsResult <$>
2062− v .: "doc_count" <*>
2063− (pure $ getNamedSubAgg v ["key", "doc_count"])
2064− parseJSON _ = mempty
2066−instance FromJSON DateHistogramResult where
2067− parseJSON (Object v) = DateHistogramResult <$>
2069− v .:? "key_as_string" <*>
2070− v .: "doc_count" <*>
2071− (pure $ getNamedSubAgg v [ "key"
2076− parseJSON _ = mempty
2078−instance FromJSON DateRangeResult where
2079− parseJSON = withObject "DateRangeResult" parse
2080− where parse v = DateRangeResult <$>
2082− (fmap posixMS <$> v .:? "from") <*>
2083− v .:? "from_as_string" <*>
2084− (fmap posixMS <$> v .:? "to") <*>
2085− v .:? "to_as_string" <*>
2086− v .: "doc_count" <*>
2087− (pure $ getNamedSubAgg v [ "key"
2096−instance FromJSON POSIXMS where
2097− parseJSON = withScientific "POSIXMS" (return . parse)
2098− where parse n = let n' = truncate n :: Integer
2099− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
2101−instance (FromJSON a) => FromJSON (TopHitResult a) where
2102− parseJSON (Object v) = TopHitResult <$>
2104− parseJSON _ = fail "Failure in FromJSON (TopHitResult a)"
2106−instance Semigroup Filter where
2107− a <> b = AndFilter [a, b] defaultCache
2109−instance Monoid Filter where
2110− mempty = IdentityFilter
2113−instance Seminearring Filter where
2114− a <||> b = OrFilter [a, b] defaultCache
2116−instance ToJSON Filter where
2117− toJSON (AndFilter filters cache) =
2119− object [ "filters" .= fmap toJSON filters
2120− , "_cache" .= cache]]
2122− toJSON (OrFilter filters cache) =
2124− object [ "filters" .= fmap toJSON filters
2125− , "_cache" .= cache]]
2127− toJSON (NotFilter notFilter cache) =
2129− object ["filter" .= notFilter
2130− , "_cache" .= cache]]
2132− toJSON (IdentityFilter) =
2133− object ["match_all" .= object []]
2135− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
2136− object ["term" .= object base]
2137− where base = [termFilterField .= termFilterValue,
2140− toJSON (ExistsFilter (FieldName fieldName)) =
2141− object ["exists" .= object
2142− ["field" .= fieldName]]
2144− toJSON (BoolFilter boolMatch) =
2145− object ["bool" .= boolMatch]
2147− toJSON (GeoBoundingBoxFilter bbConstraint) =
2148− object ["geo_bounding_box" .= bbConstraint]
2150− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2151− distance distanceType optimizeBbox cache) =
2152− object ["geo_distance" .=
2153− object ["distance" .= distance
2154− , "distance_type" .= distanceType
2155− , "optimize_bbox" .= optimizeBbox
2156− , distanceGeoField .= geoDistLatLon
2157− , "_cache" .= cache]]
2159− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2160− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2161− object ["geo_distance_range" .=
2162− object ["from" .= geoDistRangeDistFrom
2163− , "to" .= drDistanceTo
2164− , gddrField .= drLatLon]]
2166− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2167− object ["geo_polygon" .=
2168− object [geoPolygonFilterField .=
2169− object ["points" .= fmap toJSON latLons]]]
2171− toJSON (IdsFilter (MappingName mappingName) values) =
2173− object ["type" .= mappingName
2174− , "values" .= fmap unpackId values]]
2176− toJSON (LimitFilter limit) =
2177− object ["limit" .= object ["value" .= limit]]
2179− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2180− object ["missing" .=
2181− object ["field" .= fieldName
2182− , "existence" .= existence
2183− , "null_value" .= nullValue]]
2185− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2186− object ["prefix" .=
2187− object [fieldName .= fieldValue
2188− , "_cache" .= cache]]
2190− toJSON (QueryFilter query False) =
2191− object ["query" .= toJSON query ]
2192− toJSON (QueryFilter query True) =
2193− object ["fquery" .=
2194− object [ "query" .= toJSON query
2195− , "_cache" .= True ]]
2197− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2199− object [ fieldName .= object (rangeValueToPair rangeValue)
2200− , "execution" .= rangeExecution
2201− , "_cache" .= cache]]
2203− toJSON (RegexpFilter (FieldName fieldName)
2204− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2205− object ["regexp" .=
2206− object [fieldName .=
2207− object ["value" .= regexText
2208− , "flags" .= flags]
2209− , "_name" .= cacheName
2210− , "_cache" .= cache
2211− , "_cache_key" .= cacheKey]]
2213−instance FromJSON Filter where
2214− parseJSON = withObject "Filter" parse
2215− where parse o = andFilter `taggedWith` "and"
2216− <|> orFilter `taggedWith` "or"
2217− <|> notFilter `taggedWith` "not"
2218− <|> identityFilter `taggedWith` "match_all"
2219− <|> boolFilter `taggedWith` "bool"
2220− <|> existsFilter `taggedWith` "exists"
2221− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2222− <|> geoDistanceFilter `taggedWith` "geo_distance"
2223− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2224− <|> geoPolygonFilter `taggedWith` "geo_polygon"
2225− <|> idsFilter `taggedWith` "ids"
2226− <|> limitFilter `taggedWith` "limit"
2227− <|> missingFilter `taggedWith` "missing"
2228− <|> prefixFilter `taggedWith` "prefix"
2229− <|> queryFilter `taggedWith` "query"
2230− <|> fqueryFilter `taggedWith` "fquery"
2231− <|> rangeFilter `taggedWith` "range"
2232− <|> regexpFilter `taggedWith` "regexp"
2233− <|> termFilter `taggedWith` "term"
2234− where taggedWith parser k = parser =<< o .: k
2235− andFilter o = AndFilter <$> o .: "filters"
2236− <*> o .:? "_cache" .!= defaultCache
2237− orFilter o = OrFilter <$> o .: "filters"
2238− <*> o .:? "_cache" .!= defaultCache
2239− notFilter o = NotFilter <$> o .: "filter"
2240− <*> o .: "_cache" .!= defaultCache
2241− identityFilter :: Object -> Parser Filter
2243− | HM.null m = pure IdentityFilter
2244− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2245− boolFilter = pure . BoolFilter
2246− existsFilter o = ExistsFilter <$> o .: "field"
2247− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2248− geoDistanceFilter o = do
2249− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2251− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2252− GeoDistanceFilter gp <$> o .: "distance"
2253− <*> o .: "distance_type"
2254− <*> o .: "optimize_bbox"
2255− <*> o .:? "_cache" .!= defaultCache
2256− _ -> fail "Could not find GeoDistanceFilter field name"
2257− geoDistanceRangeFilter o = do
2258− case HM.toList (deleteSeveral ["from", "to"] o) of
2260− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2261− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2262− return (GeoDistanceRangeFilter gp rng)
2263− _ -> fail "Could not find GeoDistanceRangeFilter field name"
2264− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2265− idsFilter o = IdsFilter <$> o .: "type"
2267− limitFilter o = LimitFilter <$> o .: "value"
2268− missingFilter o = MissingFilter <$> o .: "field"
2269− <*> o .: "existence"
2270− <*> o .: "null_value"
2271− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2272− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2273− _ -> fail "Could not parse PrefixFilter"
2275− queryFilter q = pure (QueryFilter q False)
2276− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2277− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2278− [(fn, v)] -> RangeFilter (FieldName fn)
2280− <*> o .: "execution"
2281− <*> o .:? "_cache" .!= defaultCache
2282− _ -> fail "Could not find field name for RangeFilter"
2283− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2284− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2288− <*> o .:? "_cache" .!= defaultCache
2289− <*> o .: "_cache_key"
2290− _ -> fail "Could not find field name for RegexpFilter"
2291− termFilter o = case HM.toList (HM.delete "_cache" o) of
2292− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2293− <$> o .:? "_cache" .!= defaultCache
2294− _ -> fail "Could not find term field for TermFilter"
2296−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2297−fieldTagged f o = case HM.toList o of
2298− [(k, Object o')] -> f (FieldName k) o'
2299− _ -> fail "Expected object with 1 field-named key"
2301−-- Try to get an AggregationResults when we don't know the
2302−-- field name. We filter out the known keys to try to minimize the noise.
2303−getNamedSubAgg :: Object -> [Text] -> Maybe AggregationResults
2304−getNamedSubAgg o knownKeys = maggRes
2305− where unknownKeys = HM.filterWithKey (\k _ -> k `notElem` knownKeys) o
2307− | HM.null unknownKeys = Nothing
2308− | otherwise = Just . M.fromList $ HM.toList unknownKeys
2310−instance ToJSON GeoPoint where
2311− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2312− object [ geoPointField .= geoPointLatLon ]
2315−instance ToJSON Query where
2316− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2318− object [termQueryField .= object merged]]
2320− base = [ "value" .= termQueryValue ]
2321− boosted = maybe [] (return . ("boost" .=)) boost
2322− merged = mappend base boosted
2324− toJSON (TermsQuery fieldName terms) =
2325− object [ "terms" .= object conjoined ]
2326− where conjoined = [fieldName .= terms]
2328− toJSON (IdsQuery idsQueryMappingName docIds) =
2329− object [ "ids" .= object conjoined ]
2330− where conjoined = [ "type" .= idsQueryMappingName
2331− , "values" .= fmap toJSON docIds ]
2333− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2334− object [ "query_string" .= qQueryStringQuery ]
2336− toJSON (QueryMatchQuery matchQuery) =
2337− object [ "match" .= matchQuery ]
2339− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2340− toJSON multiMatchQuery
2342− toJSON (QueryBoolQuery boolQuery) =
2343− object [ "bool" .= boolQuery ]
2345− toJSON (QueryBoostingQuery boostingQuery) =
2346− object [ "boosting" .= boostingQuery ]
2348− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2349− object [ "common" .= commonTermsQuery ]
2351− toJSON (ConstantScoreFilter csFilter boost) =
2352− object ["constant_score" .= object ["filter" .= csFilter
2353− , "boost" .= boost]]
2355− toJSON (ConstantScoreQuery query boost) =
2356− object ["constant_score" .= object ["query" .= query
2357− , "boost" .= boost]]
2359− toJSON (QueryDisMaxQuery disMaxQuery) =
2360− object [ "dis_max" .= disMaxQuery ]
2362− toJSON (QueryFilteredQuery qFilteredQuery) =
2363− object [ "filtered" .= qFilteredQuery ]
2365− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2366− object [ "fuzzy_like_this" .= fuzzyQuery ]
2368− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2369− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2371− toJSON (QueryFuzzyQuery fuzzyQuery) =
2372− object [ "fuzzy" .= fuzzyQuery ]
2374− toJSON (QueryHasChildQuery childQuery) =
2375− object [ "has_child" .= childQuery ]
2377− toJSON (QueryHasParentQuery parentQuery) =
2378− object [ "has_parent" .= parentQuery ]
2380− toJSON (QueryIndicesQuery qIndicesQuery) =
2381− object [ "indices" .= qIndicesQuery ]
2383− toJSON (MatchAllQuery boost) =
2384− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2386− toJSON (QueryMoreLikeThisQuery query) =
2387− object [ "more_like_this" .= query ]
2389− toJSON (QueryMoreLikeThisFieldQuery query) =
2390− object [ "more_like_this_field" .= query ]
2392− toJSON (QueryNestedQuery query) =
2393− object [ "nested" .= query ]
2395− toJSON (QueryPrefixQuery query) =
2396− object [ "prefix" .= query ]
2398− toJSON (QueryRangeQuery query) =
2399− object [ "range" .= query ]
2401− toJSON (QueryRegexpQuery query) =
2402− object [ "regexp" .= query ]
2404− toJSON (QuerySimpleQueryStringQuery query) =
2405− object [ "simple_query_string" .= query ]
2407−instance FromJSON Query where
2408− parseJSON v = withObject "Query" parse v
2409− where parse o = termQuery `taggedWith` "term"
2410− <|> termsQuery `taggedWith` "terms"
2411− <|> idsQuery `taggedWith` "ids"
2412− <|> queryQueryStringQuery `taggedWith` "query_string"
2413− <|> queryMatchQuery `taggedWith` "match"
2414− <|> queryMultiMatchQuery
2415− <|> queryBoolQuery `taggedWith` "bool"
2416− <|> queryBoostingQuery `taggedWith` "boosting"
2417− <|> queryCommonTermsQuery `taggedWith` "common"
2418− <|> constantScoreFilter `taggedWith` "constant_score"
2419− <|> constantScoreQuery `taggedWith` "constant_score"
2420− <|> queryDisMaxQuery `taggedWith` "dis_max"
2421− <|> queryFilteredQuery `taggedWith` "filtered"
2422− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2423− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2424− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2425− <|> queryHasChildQuery `taggedWith` "has_child"
2426− <|> queryHasParentQuery `taggedWith` "has_parent"
2427− <|> queryIndicesQuery `taggedWith` "indices"
2428− <|> matchAllQuery `taggedWith` "match_all"
2429− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2430− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2431− <|> queryNestedQuery `taggedWith` "nested"
2432− <|> queryPrefixQuery `taggedWith` "prefix"
2433− <|> queryRangeQuery `taggedWith` "range"
2434− <|> queryRegexpQuery `taggedWith` "regexp"
2435− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2436− where taggedWith parser k = parser =<< o .: k
2437− termQuery = fieldTagged $ \(FieldName fn) o ->
2438− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2439− termsQuery o = case HM.toList o of
2440− [(fn, vs)] -> do vals <- parseJSON vs
2442− x:xs -> return (TermsQuery fn (x :| xs))
2443− _ -> fail "Expected non empty list of values"
2444− _ -> fail "Expected object with 1 field-named key"
2445− idsQuery o = IdsQuery <$> o .: "type"
2447− queryQueryStringQuery = pure . QueryQueryStringQuery
2448− queryMatchQuery = pure . QueryMatchQuery
2449− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2450− queryBoolQuery = pure . QueryBoolQuery
2451− queryBoostingQuery = pure . QueryBoostingQuery
2452− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2453− constantScoreFilter o = case HM.lookup "filter" o of
2454− Just x -> ConstantScoreFilter <$> parseJSON x
2456− _ -> fail "Does not appear to be a ConstantScoreFilter"
2457− constantScoreQuery o = case HM.lookup "query" o of
2458− Just x -> ConstantScoreQuery <$> parseJSON x
2460− _ -> fail "Does not appear to be a ConstantScoreQuery"
2461− queryDisMaxQuery = pure . QueryDisMaxQuery
2462− queryFilteredQuery = pure . QueryFilteredQuery
2463− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2464− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2465− queryFuzzyQuery = pure . QueryFuzzyQuery
2466− queryHasChildQuery = pure . QueryHasChildQuery
2467− queryHasParentQuery = pure . QueryHasParentQuery
2468− queryIndicesQuery = pure . QueryIndicesQuery
2469− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2470− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2471− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2472− queryNestedQuery = pure . QueryNestedQuery
2473− queryPrefixQuery = pure . QueryPrefixQuery
2474− queryRangeQuery = pure . QueryRangeQuery
2475− queryRegexpQuery = pure . QueryRegexpQuery
2476− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2479−omitNulls :: [(Text, Value)] -> Value
2480−omitNulls = object . filter notNull where
2481− notNull (_, Null) = False
2482− notNull (_, Array a) = (not . V.null) a
2486−instance ToJSON SimpleQueryStringQuery where
2487− toJSON SimpleQueryStringQuery {..} =
2488− omitNulls (base ++ maybeAdd)
2489− where base = [ "query" .= simpleQueryStringQuery ]
2490− maybeAdd = [ "fields" .= simpleQueryStringField
2491− , "default_operator" .= simpleQueryStringOperator
2492− , "analyzer" .= simpleQueryStringAnalyzer
2493− , "flags" .= simpleQueryStringFlags
2494− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2495− , "locale" .= simpleQueryStringLocale ]
2497−instance FromJSON SimpleQueryStringQuery where
2498− parseJSON = withObject "SimpleQueryStringQuery" parse
2499− where parse o = SimpleQueryStringQuery <$> o .: "query"
2501− <*> o .:? "default_operator"
2502− <*> o .:? "analyzer"
2503− <*> (parseFlags <$> o .:? "flags")
2504− <*> o .:? "lowercase_expanded_terms"
2506− parseFlags (Just (x:xs)) = Just (x :| xs)
2507− parseFlags _ = Nothing
2509−instance ToJSON FieldOrFields where
2510− toJSON (FofField fieldName) =
2512− toJSON (FofFields fieldNames) =
2515−instance FromJSON FieldOrFields where
2516− parseJSON v = FofField <$> parseJSON v
2517− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2519−instance ToJSON SimpleQueryFlag where
2520− toJSON SimpleQueryAll = "ALL"
2521− toJSON SimpleQueryNone = "NONE"
2522− toJSON SimpleQueryAnd = "AND"
2523− toJSON SimpleQueryOr = "OR"
2524− toJSON SimpleQueryPrefix = "PREFIX"
2525− toJSON SimpleQueryPhrase = "PHRASE"
2526− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2527− toJSON SimpleQueryEscape = "ESCAPE"
2528− toJSON SimpleQueryWhitespace = "WHITESPACE"
2529− toJSON SimpleQueryFuzzy = "FUZZY"
2530− toJSON SimpleQueryNear = "NEAR"
2531− toJSON SimpleQuerySlop = "SLOP"
2533−instance FromJSON SimpleQueryFlag where
2534− parseJSON = withText "SimpleQueryFlag" parse
2535− where parse "ALL" = pure SimpleQueryAll
2536− parse "NONE" = pure SimpleQueryNone
2537− parse "AND" = pure SimpleQueryAnd
2538− parse "OR" = pure SimpleQueryOr
2539− parse "PREFIX" = pure SimpleQueryPrefix
2540− parse "PHRASE" = pure SimpleQueryPhrase
2541− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2542− parse "ESCAPE" = pure SimpleQueryEscape
2543− parse "WHITESPACE" = pure SimpleQueryWhitespace
2544− parse "FUZZY" = pure SimpleQueryFuzzy
2545− parse "NEAR" = pure SimpleQueryNear
2546− parse "SLOP" = pure SimpleQuerySlop
2547− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2549−instance ToJSON RegexpQuery where
2550− toJSON (RegexpQuery (FieldName rqQueryField)
2551− (Regexp regexpQueryQuery) rqQueryFlags
2553− object [ rqQueryField .= omitNulls base ]
2554− where base = [ "value" .= regexpQueryQuery
2555− , "flags" .= rqQueryFlags
2556− , "boost" .= rqQueryBoost ]
2558−instance FromJSON RegexpQuery where
2559− parseJSON = withObject "RegexpQuery" parse
2560− where parse = fieldTagged $ \fn o ->
2566−instance ToJSON QueryStringQuery where
2567− toJSON (QueryStringQuery qsQueryString
2568− qsDefaultField qsOperator
2569− qsAnalyzer qsAllowWildcard
2570− qsLowercaseExpanded qsEnablePositionIncrements
2571− qsFuzzyMaxExpansions qsFuzziness
2572− qsFuzzyPrefixLength qsPhraseSlop
2573− qsBoost qsAnalyzeWildcard
2574− qsGeneratePhraseQueries qsMinimumShouldMatch
2575− qsLenient qsLocale) =
2578− base = [ "query" .= qsQueryString
2579− , "default_field" .= qsDefaultField
2580− , "default_operator" .= qsOperator
2581− , "analyzer" .= qsAnalyzer
2582− , "allow_leading_wildcard" .= qsAllowWildcard
2583− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2584− , "enable_position_increments" .= qsEnablePositionIncrements
2585− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2586− , "fuzziness" .= qsFuzziness
2587− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2588− , "phrase_slop" .= qsPhraseSlop
2589− , "boost" .= qsBoost
2590− , "analyze_wildcard" .= qsAnalyzeWildcard
2591− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2592− , "minimum_should_match" .= qsMinimumShouldMatch
2593− , "lenient" .= qsLenient
2594− , "locale" .= qsLocale ]
2596−instance FromJSON QueryStringQuery where
2597− parseJSON = withObject "QueryStringQuery" parse
2598− where parse o = QueryStringQuery
2600− <*> o .:? "default_field"
2601− <*> o .:? "default_operator"
2602− <*> o .:? "analyzer"
2603− <*> o .:? "allow_leading_wildcard"
2604− <*> o .:? "lowercase_expanded_terms"
2605− <*> o .:? "enable_position_increments"
2606− <*> o .:? "fuzzy_max_expansions"
2607− <*> o .:? "fuzziness"
2608− <*> o .:? "fuzzy_prefix_length"
2609− <*> o .:? "phrase_slop"
2611− <*> o .:? "analyze_wildcard"
2612− <*> o .:? "auto_generate_phrase_queries"
2613− <*> o .:? "minimum_should_match"
2614− <*> o .:? "lenient"
2617−instance ToJSON RangeQuery where
2618− toJSON (RangeQuery (FieldName fieldName) range boost) =
2619− object [ fieldName .= object conjoined ]
2620− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2622−instance FromJSON RangeQuery where
2623− parseJSON = withObject "RangeQuery" parse
2624− where parse = fieldTagged $ \fn o ->
2626− <$> parseJSON (Object o)
2629−instance FromJSON RangeValue where
2630− parseJSON = withObject "RangeValue" parse
2631− where parse o = parseDate o
2633− parseDate o = do lt <- o .:? "lt"
2637− case (lt, lte, gt, gte) of
2638− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2639− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2640− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2641− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2642− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2643− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2644− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2645− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2646− (Nothing, Nothing, Nothing, Nothing) -> mzero
2647− parseDouble o = do lt <- o .:? "lt"
2651− case (lt, lte, gt, gte) of
2652− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2653− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2654− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2655− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2656− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2657− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2658− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2659− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2660− (Nothing, Nothing, Nothing, Nothing) -> mzero
2662−instance ToJSON PrefixQuery where
2663− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2664− object [ fieldName .= omitNulls base ]
2665− where base = [ "value" .= queryValue
2666− , "boost" .= boost ]
2668−instance FromJSON PrefixQuery where
2669− parseJSON = withObject "PrefixQuery" parse
2670− where parse = fieldTagged $ \fn o ->
2675−instance ToJSON NestedQuery where
2676− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2677− object [ "path" .= nqPath
2678− , "score_mode" .= nqScoreType
2679− , "query" .= nqQuery ]
2681−instance FromJSON NestedQuery where
2682− parseJSON = withObject "NestedQuery" parse
2683− where parse o = NestedQuery
2685− <*> o .: "score_mode"
2688−instance ToJSON MoreLikeThisFieldQuery where
2689− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2690− percent mtf mqt stopwords mindf maxdf
2691− minwl maxwl boostTerms boost analyzer) =
2692− object [ fieldName .= omitNulls base ]
2693− where base = [ "like_text" .= text
2694− , "percent_terms_to_match" .= percent
2695− , "min_term_freq" .= mtf
2696− , "max_query_terms" .= mqt
2697− , "stop_words" .= stopwords
2698− , "min_doc_freq" .= mindf
2699− , "max_doc_freq" .= maxdf
2700− , "min_word_length" .= minwl
2701− , "max_word_length" .= maxwl
2702− , "boost_terms" .= boostTerms
2704− , "analyzer" .= analyzer ]
2706−instance FromJSON MoreLikeThisFieldQuery where
2707− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2708− where parse = fieldTagged $ \fn o ->
2709− MoreLikeThisFieldQuery
2710− <$> o .: "like_text"
2712− <*> o .:? "percent_terms_to_match"
2713− <*> o .:? "min_term_freq"
2714− <*> o .:? "max_query_terms"
2715− -- <*> (optionalNE =<< o .:? "stop_words")
2716− <*> o .:? "stop_words"
2717− <*> o .:? "min_doc_freq"
2718− <*> o .:? "max_doc_freq"
2719− <*> o .:? "min_word_length"
2720− <*> o .:? "max_word_length"
2721− <*> o .:? "boost_terms"
2723− <*> o .:? "analyzer"
2724− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2726−instance ToJSON MoreLikeThisQuery where
2727− toJSON (MoreLikeThisQuery text fields percent
2728− mtf mqt stopwords mindf maxdf
2729− minwl maxwl boostTerms boost analyzer) =
2731− where base = [ "like_text" .= text
2732− , "fields" .= fields
2733− , "percent_terms_to_match" .= percent
2734− , "min_term_freq" .= mtf
2735− , "max_query_terms" .= mqt
2736− , "stop_words" .= stopwords
2737− , "min_doc_freq" .= mindf
2738− , "max_doc_freq" .= maxdf
2739− , "min_word_length" .= minwl
2740− , "max_word_length" .= maxwl
2741− , "boost_terms" .= boostTerms
2743− , "analyzer" .= analyzer ]
2745−instance FromJSON MoreLikeThisQuery where
2746− parseJSON = withObject "MoreLikeThisQuery" parse
2747− where parse o = MoreLikeThisQuery
2748− <$> o .: "like_text"
2749− -- <*> (optionalNE =<< o .:? "fields")
2751− <*> o .:? "percent_terms_to_match"
2752− <*> o .:? "min_term_freq"
2753− <*> o .:? "max_query_terms"
2754− -- <*> (optionalNE =<< o .:? "stop_words")
2755− <*> o .:? "stop_words"
2756− <*> o .:? "min_doc_freq"
2757− <*> o .:? "max_doc_freq"
2758− <*> o .:? "min_word_length"
2759− <*> o .:? "max_word_length"
2760− <*> o .:? "boost_terms"
2762− <*> o .:? "analyzer"
2763− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2765−instance ToJSON IndicesQuery where
2766− toJSON (IndicesQuery indices query noMatch) =
2767− omitNulls [ "indices" .= indices
2768− , "no_match_query" .= noMatch
2769− , "query" .= query ]
2771−instance FromJSON IndicesQuery where
2772− parseJSON = withObject "IndicesQuery" parse
2773− where parse o = IndicesQuery
2774− <$> o .:? "indices" .!= []
2776− <*> o .:? "no_match_query"
2778−instance ToJSON HasParentQuery where
2779− toJSON (HasParentQuery queryType query scoreType) =
2780− omitNulls [ "parent_type" .= queryType
2781− , "score_type" .= scoreType
2782− , "query" .= query ]
2784−instance FromJSON HasParentQuery where
2785− parseJSON = withObject "HasParentQuery" parse
2786− where parse o = HasParentQuery
2787− <$> o .: "parent_type"
2789− <*> o .:? "score_type"
2791−instance ToJSON HasChildQuery where
2792− toJSON (HasChildQuery queryType query scoreType) =
2793− omitNulls [ "query" .= query
2794− , "score_type" .= scoreType
2795− , "type" .= queryType ]
2797−instance FromJSON HasChildQuery where
2798− parseJSON = withObject "HasChildQuery" parse
2799− where parse o = HasChildQuery
2802− <*> o .:? "score_type"
2804−instance ToJSON FuzzyQuery where
2805− toJSON (FuzzyQuery (FieldName fieldName) queryText
2806− prefixLength maxEx fuzziness boost) =
2807− object [ fieldName .= omitNulls base ]
2808− where base = [ "value" .= queryText
2809− , "fuzziness" .= fuzziness
2810− , "prefix_length" .= prefixLength
2812− , "max_expansions" .= maxEx ]
2814−instance FromJSON FuzzyQuery where
2815− parseJSON = withObject "FuzzyQuery" parse
2816− where parse = fieldTagged $ \fn o ->
2819− <*> o .: "prefix_length"
2820− <*> o .: "max_expansions"
2821− <*> o .: "fuzziness"
2824−instance ToJSON FuzzyLikeFieldQuery where
2825− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2826− fieldText maxTerms ignoreFreq fuzziness prefixLength
2828− object [ fieldName .=
2829− omitNulls [ "like_text" .= fieldText
2830− , "max_query_terms" .= maxTerms
2831− , "ignore_tf" .= ignoreFreq
2832− , "fuzziness" .= fuzziness
2833− , "prefix_length" .= prefixLength
2834− , "analyzer" .= analyzer
2835− , "boost" .= boost ]]
2837−instance FromJSON FuzzyLikeFieldQuery where
2838− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2839− where parse = fieldTagged $ \fn o ->
2840− FuzzyLikeFieldQuery fn
2841− <$> o .: "like_text"
2842− <*> o .: "max_query_terms"
2843− <*> o .: "ignore_tf"
2844− <*> o .: "fuzziness"
2845− <*> o .: "prefix_length"
2847− <*> o .:? "analyzer"
2849−instance ToJSON FuzzyLikeThisQuery where
2850− toJSON (FuzzyLikeThisQuery fields text maxTerms
2851− ignoreFreq fuzziness prefixLength boost analyzer) =
2853− where base = [ "fields" .= fields
2854− , "like_text" .= text
2855− , "max_query_terms" .= maxTerms
2856− , "ignore_tf" .= ignoreFreq
2857− , "fuzziness" .= fuzziness
2858− , "prefix_length" .= prefixLength
2859− , "analyzer" .= analyzer
2860− , "boost" .= boost ]
2862−instance FromJSON FuzzyLikeThisQuery where
2863− parseJSON = withObject "FuzzyLikeThisQuery" parse
2864− where parse o = FuzzyLikeThisQuery
2865− <$> o .:? "fields" .!= []
2866− <*> o .: "like_text"
2867− <*> o .: "max_query_terms"
2868− <*> o .: "ignore_tf"
2869− <*> o .: "fuzziness"
2870− <*> o .: "prefix_length"
2872− <*> o .:? "analyzer"
2874−instance ToJSON FilteredQuery where
2875− toJSON (FilteredQuery query fFilter) =
2876− object [ "query" .= query
2877− , "filter" .= fFilter ]
2879−instance FromJSON FilteredQuery where
2880− parseJSON = withObject "FilteredQuery" parse
2881− where parse o = FilteredQuery
2885−instance ToJSON DisMaxQuery where
2886− toJSON (DisMaxQuery queries tiebreaker boost) =
2888− where base = [ "queries" .= queries
2890− , "tie_breaker" .= tiebreaker ]
2892−instance FromJSON DisMaxQuery where
2893− parseJSON = withObject "DisMaxQuery" parse
2894− where parse o = DisMaxQuery
2895− <$> o .:? "queries" .!= []
2896− <*> o .: "tie_breaker"
2899−instance ToJSON CommonTermsQuery where
2900− toJSON (CommonTermsQuery (FieldName fieldName)
2901− (QueryString query) cf lfo hfo msm
2902− boost analyzer disableCoord) =
2903− object [fieldName .= omitNulls base ]
2904− where base = [ "query" .= query
2905− , "cutoff_frequency" .= cf
2906− , "low_freq_operator" .= lfo
2907− , "minimum_should_match" .= msm
2909− , "analyzer" .= analyzer
2910− , "disable_coord" .= disableCoord
2911− , "high_freq_operator" .= hfo ]
2913−instance FromJSON CommonTermsQuery where
2914− parseJSON = withObject "CommonTermsQuery" parse
2915− where parse = fieldTagged $ \fn o ->
2916− CommonTermsQuery fn
2918− <*> o .: "cutoff_frequency"
2919− <*> o .: "low_freq_operator"
2920− <*> o .: "high_freq_operator"
2921− <*> o .:? "minimum_should_match"
2923− <*> o .:? "analyzer"
2924− <*> o .:? "disable_coord"
2926−instance ToJSON CommonMinimumMatch where
2927− toJSON (CommonMinimumMatch mm) = toJSON mm
2928− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2929− object [ "low_freq" .= lowF
2930− , "high_freq" .= highF ]
2932−instance FromJSON CommonMinimumMatch where
2933− parseJSON v = parseMinimum v
2934− <|> parseMinimumHighLow v
2935− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2936− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2937− MinimumMatchHighLow
2938− <$> o .: "low_freq"
2939− <*> o .: "high_freq")
2942−instance ToJSON BoostingQuery where
2943− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2944− object [ "positive" .= bqPositiveQuery
2945− , "negative" .= bqNegativeQuery
2946− , "negative_boost" .= bqNegativeBoost ]
2948−instance FromJSON BoostingQuery where
2949− parseJSON = withObject "BoostingQuery" parse
2950− where parse o = BoostingQuery
2951− <$> o .: "positive"
2952− <*> o .: "negative"
2953− <*> o .: "negative_boost"
2955−instance ToJSON BoolQuery where
2956− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2958− where base = [ "must" .= mustM
2959− , "must_not" .= notM
2960− , "should" .= shouldM
2961− , "minimum_should_match" .= bqMin
2963− , "disable_coord" .= disableCoord ]
2965−instance FromJSON BoolQuery where
2966− parseJSON = withObject "BoolQuery" parse
2967− where parse o = BoolQuery
2968− <$> o .:? "must" .!= []
2969− <*> o .:? "must_not" .!= []
2970− <*> o .:? "should" .!= []
2971− <*> o .:? "minimum_should_match"
2973− <*> o .:? "disable_coord"
2975−instance ToJSON MatchQuery where
2976− toJSON (MatchQuery (FieldName fieldName)
2977− (QueryString mqQueryString) booleanOperator
2978− zeroTermsQuery cutoffFrequency matchQueryType
2979− analyzer maxExpansions lenient boost) =
2980− object [ fieldName .= omitNulls base ]
2981− where base = [ "query" .= mqQueryString
2982− , "operator" .= booleanOperator
2983− , "zero_terms_query" .= zeroTermsQuery
2984− , "cutoff_frequency" .= cutoffFrequency
2985− , "type" .= matchQueryType
2986− , "analyzer" .= analyzer
2987− , "max_expansions" .= maxExpansions
2988− , "lenient" .= lenient
2989− , "boost" .= boost ]
2991−instance FromJSON MatchQuery where
2992− parseJSON = withObject "MatchQuery" parse
2993− where parse = fieldTagged $ \fn o ->
2996− <*> o .: "operator"
2997− <*> o .: "zero_terms_query"
2998− <*> o .:? "cutoff_frequency"
3000− <*> o .:? "analyzer"
3001− <*> o .:? "max_expansions"
3002− <*> o .:? "lenient"
3005−instance ToJSON MultiMatchQuery where
3006− toJSON (MultiMatchQuery fields (QueryString query) boolOp
3007− ztQ tb mmqt cf analyzer maxEx lenient) =
3008− object ["multi_match" .= omitNulls base]
3009− where base = [ "fields" .= fmap toJSON fields
3011− , "operator" .= boolOp
3012− , "zero_terms_query" .= ztQ
3013− , "tie_breaker" .= tb
3015− , "cutoff_frequency" .= cf
3016− , "analyzer" .= analyzer
3017− , "max_expansions" .= maxEx
3018− , "lenient" .= lenient ]
3020−instance FromJSON MultiMatchQuery where
3021− parseJSON = withObject "MultiMatchQuery" parse
3022− where parse raw = do o <- raw .: "multi_match"
3024− <$> o .:? "fields" .!= []
3026− <*> o .: "operator"
3027− <*> o .: "zero_terms_query"
3028− <*> o .:? "tie_breaker"
3030− <*> o .:? "cutoff_frequency"
3031− <*> o .:? "analyzer"
3032− <*> o .:? "max_expansions"
3033− <*> o .:? "lenient"
3035−instance ToJSON MultiMatchQueryType where
3036− toJSON MultiMatchBestFields = "best_fields"
3037− toJSON MultiMatchMostFields = "most_fields"
3038− toJSON MultiMatchCrossFields = "cross_fields"
3039− toJSON MultiMatchPhrase = "phrase"
3040− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
3042−instance FromJSON MultiMatchQueryType where
3043− parseJSON = withText "MultiMatchPhrasePrefix" parse
3044− where parse "best_fields" = pure MultiMatchBestFields
3045− parse "most_fields" = pure MultiMatchMostFields
3046− parse "cross_fields" = pure MultiMatchCrossFields
3047− parse "phrase" = pure MultiMatchPhrase
3048− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
3049− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
3051−instance ToJSON BooleanOperator where
3052− toJSON And = String "and"
3053− toJSON Or = String "or"
3055−instance FromJSON BooleanOperator where
3056− parseJSON = withText "BooleanOperator" parse
3057− where parse "and" = pure And
3058− parse "or" = pure Or
3059− parse o = fail ("Unexpected BooleanOperator: " <> show o)
3061−instance ToJSON ZeroTermsQuery where
3062− toJSON ZeroTermsNone = String "none"
3063− toJSON ZeroTermsAll = String "all"
3065−instance FromJSON ZeroTermsQuery where
3066− parseJSON = withText "ZeroTermsQuery" parse
3067− where parse "none" = pure ZeroTermsNone
3068− parse "all" = pure ZeroTermsAll
3069− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
3071−instance ToJSON MatchQueryType where
3072− toJSON MatchPhrase = "phrase"
3073− toJSON MatchPhrasePrefix = "phrase_prefix"
3075−instance FromJSON MatchQueryType where
3076− parseJSON = withText "MatchQueryType" parse
3077− where parse "phrase" = pure MatchPhrase
3078− parse "phrase_prefix" = pure MatchPhrasePrefix
3079− parse t = fail ("Unexpected MatchQueryType: " <> show t)
3081−instance FromJSON Status where
3082− parseJSON (Object v) = Status <$>
3084− (v .:? "status" .!= 200) <*>
3088− parseJSON _ = empty
3091−instance ToJSON IndexSettings where
3092− toJSON (IndexSettings s r) = object ["settings" .=
3094− object ["number_of_shards" .= s, "number_of_replicas" .= r]
3098−instance FromJSON IndexSettings where
3099− parseJSON = withObject "IndexSettings" parse
3100− where parse o = do s <- o .: "settings"
3102− IndexSettings <$> i .: "number_of_shards"
3103− <*> i .: "number_of_replicas"
3105−instance ToJSON UpdatableIndexSetting where
3106− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
3107− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
3108− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
3109− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
3110− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
3111− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
3112− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
3113− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
3114− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
3115− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
3116− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
3117− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
3118− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
3119− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
3120− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
3121− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
3122− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
3123− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
3124− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
3125− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
3126− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
3127− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
3128− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
3129− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
3130− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
3131− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
3132− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
3133− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
3135−instance FromJSON UpdatableIndexSetting where
3136− parseJSON = withObject "UpdatableIndexSetting" parse
3137− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
3138− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
3139− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
3140− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
3141− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
3142− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
3143− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
3144− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
3145− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
3146− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
3147− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
3148− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
3149− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
3150− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
3151− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
3152− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
3153− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
3154− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
3155− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
3156− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
3157− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
3158− <|> compoundFormat `taggedAt` ["index", "compound_format"]
3159− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3160− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3161− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3162− <|> blocksRead `taggedAt` ["blocks", "read"]
3163− <|> blocksWrite `taggedAt` ["blocks", "write"]
3164− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3165− where taggedAt f ks = taggedAt' f (Object o) ks
3166− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3167− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3168− taggedAt' f v' ks) v
3169− numberOfReplicas = pure . NumberOfReplicas
3170− autoExpandReplicas = pure . AutoExpandReplicas
3171− refreshInterval = pure . RefreshInterval . ndtJSON
3172− indexConcurrency = pure . IndexConcurrency
3173− failOnMergeFailure = pure . FailOnMergeFailure
3174− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3175− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3176− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3177− translogDisableFlush = pure . TranslogDisableFlush
3178− cacheFilterMaxSize = pure . CacheFilterMaxSize
3179− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3180− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3181− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3182− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3183− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3184− routingAllocationEnable = pure . RoutingAllocationEnable
3185− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3186− recoveryInitialShards = pure . RecoveryInitialShards
3187− gcDeletes = pure . GCDeletes . ndtJSON
3188− ttlDisablePurge = pure . TTLDisablePurge
3189− translogFSType = pure . TranslogFSType
3190− compoundFormat = pure . IndexCompoundFormat
3191− compoundOnFlush = pure . IndexCompoundOnFlush
3192− warmerEnabled = pure . WarmerEnabled
3193− blocksReadOnly = pure . BlocksReadOnly
3194− blocksRead = pure . BlocksRead
3195− blocksWrite = pure . BlocksWrite
3196− blocksMetaData = pure . BlocksMetaData
3198−instance FromJSON IndexSettingsSummary where
3199− parseJSON = withObject "IndexSettingsSummary" parse
3200− where parse o = case HM.toList o of
3201− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3203− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3204− _ -> fail "Expected single-key object with index name"
3205− redundant (NumberOfReplicas _) = True
3206− redundant _ = False
3208−-- | For some reason in several settings APIs, all leaf values get returned
3209−-- as strings. This function attepmts to recover from this for all
3210−-- non-recursive JSON types. If nothing can be done, the value is left alone.
3211−unStringlyTypeJSON :: Value -> Value
3212−unStringlyTypeJSON (String "true") = Bool True
3213−unStringlyTypeJSON (String "false") = Bool False
3214−unStringlyTypeJSON (String "null") = Null
3215−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3218−unStringlyTypeJSON v = v
3221−parseSettings :: Object -> Parser [UpdatableIndexSetting]
3222−parseSettings o = do
3224− -- slice the index object into singleton hashmaps and try to parse each
3225− parses <- forM (HM.toList o') $ \(k, v) -> do
3226− -- blocks are now nested into the "index" key, which is not how they're serialized
3227− let atRoot = Object (HM.singleton k v)
3228− let atIndex = Object (HM.singleton "index" atRoot)
3229− optional (parseJSON atRoot <|> parseJSON atIndex)
3230− return (catMaybes parses)
3232−oPath :: ToJSON a => NonEmpty Text -> a -> Value
3233−oPath (k :| []) v = object [k .= v]
3234−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3236−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3237−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3238− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3240−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3241−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3242− where parse o = case HM.toList o of
3243− [] -> fail "Expected non-empty list of NodeAttrFilters"
3244− x:xs -> DT.mapM (uncurry parse') (x :| xs)
3245− parse' n = withText "Text" $ \t ->
3246− case T.splitOn "," t of
3247− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3248− [] -> fail "Expected non-empty list of filter values"
3250−instance ToJSON ReplicaBounds where
3251− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3252− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3253− toJSON ReplicasUnbounded = Bool False
3255−instance FromJSON ReplicaBounds where
3256− parseJSON v = withText "ReplicaBounds" parseText v
3257− <|> withBool "ReplicaBounds" parseBool v
3258− where parseText t = case T.splitOn "-" t of
3259− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3260− [a, b] -> ReplicasBounded <$> parseReadText a
3261− <*> parseReadText b
3262− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3263− parseBool False = pure ReplicasUnbounded
3264− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3266−instance ToJSON AllocationPolicy where
3267− toJSON AllocAll = String "all"
3268− toJSON AllocPrimaries = String "primaries"
3269− toJSON AllocNewPrimaries = String "new_primaries"
3270− toJSON AllocNone = String "none"
3272−instance FromJSON AllocationPolicy where
3273− parseJSON = withText "AllocationPolicy" parse
3274− where parse "all" = pure AllocAll
3275− parse "primaries" = pure AllocPrimaries
3276− parse "new_primaries" = pure AllocNewPrimaries
3277− parse "none" = pure AllocNone
3278− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3280−instance ToJSON InitialShardCount where
3281− toJSON QuorumShards = String "quorum"
3282− toJSON QuorumMinus1Shards = String "quorum-1"
3283− toJSON FullShards = String "full"
3284− toJSON FullMinus1Shards = String "full-1"
3285− toJSON (ExplicitShards x) = toJSON x
3287−instance FromJSON InitialShardCount where
3288− parseJSON v = withText "InitialShardCount" parseText v
3289− <|> ExplicitShards <$> parseJSON v
3290− where parseText "quorum" = pure QuorumShards
3291− parseText "quorum-1" = pure QuorumMinus1Shards
3292− parseText "full" = pure FullShards
3293− parseText "full-1" = pure FullMinus1Shards
3294− parseText _ = mzero
3296−instance ToJSON FSType where
3297− toJSON FSSimple = "simple"
3298− toJSON FSBuffered = "buffered"
3300−instance FromJSON FSType where
3301− parseJSON = withText "FSType" parse
3302− where parse "simple" = pure FSSimple
3303− parse "buffered" = pure FSBuffered
3304− parse t = fail ("Invalid FSType: " <> show t)
3306−instance ToJSON CompoundFormat where
3307− toJSON (CompoundFileFormat x) = Bool x
3308− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3310−instance FromJSON CompoundFormat where
3311− parseJSON v = CompoundFileFormat <$> parseJSON v
3312− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3314−instance ToJSON NominalDiffTimeJSON where
3315− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3317−instance FromJSON NominalDiffTimeJSON where
3318− parseJSON = withText "NominalDiffTime" parse
3319− where parse t = case T.takeEnd 1 t of
3320− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3321− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3323−instance ToJSON IndexTemplate where
3324− toJSON (IndexTemplate p s m) = merge
3325− (object [ "template" .= p
3326− , "mappings" .= foldl' merge (object []) m
3330− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3332− merge _ _ = undefined
3334−instance (FromJSON a) => FromJSON (EsResult a) where
3335− parseJSON jsonVal@(Object v) = do
3336− found <- v .:? "found" .!= False
3338− then parseJSON jsonVal
3339− else return Nothing
3340− EsResult <$> v .: "_index" <*>
3344− parseJSON _ = empty
3346−instance (FromJSON a) => FromJSON (EsResultFound a) where
3347− parseJSON (Object v) = EsResultFound <$>
3348− v .: "_version" <*>
3350− parseJSON _ = empty
3352−instance FromJSON EsError where
3353− parseJSON (Object v) = EsError <$>
3355− (v .: "error" <|> (v .: "error" >>= (.: "reason")))
3356− parseJSON _ = empty
3358−instance FromJSON IndexAliasesSummary where
3359− parseJSON = withObject "IndexAliasesSummary" parse
3360− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3361− go ixn = withObject "index aliases" $ \ia -> do
3362− aliases <- ia .:? "aliases" .!= mempty
3363− forM (HM.toList aliases) $ \(aName, v) -> do
3364− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3365− IndexAliasSummary indexAlias <$> parseJSON v
3368−instance ToJSON IndexAliasAction where
3369− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3370− where Object iaObj = toJSON ia
3371− Object optsObj = toJSON opts
3372− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3373− where Object iaObj = toJSON ia
3375−instance ToJSON IndexAlias where
3376− toJSON IndexAlias {..} = object ["index" .= srcIndex
3377− , "alias" .= indexAlias
3380−instance ToJSON IndexAliasCreate where
3381− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3382− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3383− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3385−instance ToJSON AliasRouting where
3386− toJSON (AllAliasRouting v) = object ["routing" .= v]
3387− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3388− where prs = [("search_routing" .=) <$> srch
3389− ,("index_routing" .=) <$> idx]
3391−instance FromJSON AliasRouting where
3392− parseJSON = withObject "AliasRouting" parse
3393− where parse o = parseAll o <|> parseGranular o
3394− parseAll o = AllAliasRouting <$> o .: "routing"
3395− parseGranular o = do
3396− sr <- o .:? "search_routing"
3397− ir <- o .:? "index_routing"
3398− if isNothing sr && isNothing ir
3399− then fail "Both search_routing and index_routing can't be blank"
3400− else return (GranularAliasRouting sr ir)
3402−instance FromJSON IndexAliasCreate where
3403− parseJSON v = withObject "IndexAliasCreate" parse v
3404− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3407−instance ToJSON SearchAliasRouting where
3408− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3410−instance FromJSON SearchAliasRouting where
3411− parseJSON = withText "SearchAliasRouting" parse
3412− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3414−instance ToJSON Search where
3415− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3416− omitNulls [ "query" .= query
3417− , "filter" .= sFilter
3419− , "aggregations" .= searchAggs
3420− , "highlight" .= highlight
3423− , "track_scores" .= sTrackSortScores
3424− , "fields" .= sFields
3425− , "_source" .= sSource]
3428−instance ToJSON Source where
3429− toJSON NoSource = toJSON False
3430− toJSON (SourcePatterns patterns) = toJSON patterns
3431− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3433−instance ToJSON PatternOrPatterns where
3434− toJSON (PopPattern pattern) = toJSON pattern
3435− toJSON (PopPatterns patterns) = toJSON patterns
3437−instance ToJSON Include where
3438− toJSON (Include patterns) = toJSON patterns
3440−instance ToJSON Exclude where
3441− toJSON (Exclude patterns) = toJSON patterns
3443−instance ToJSON Pattern where
3444− toJSON (Pattern pattern) = toJSON pattern
3447−instance ToJSON FieldHighlight where
3448− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3449− object [ fName .= fSettings ]
3450− toJSON (FieldHighlight (FieldName fName) Nothing) =
3451− object [ fName .= emptyObject ]
3453−instance ToJSON Highlights where
3454− toJSON (Highlights global fields) =
3455− omitNulls (("fields" .= fields)
3456− : highlightSettingsPairs global)
3458−instance ToJSON HighlightSettings where
3459− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3461−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3462−highlightSettingsPairs Nothing = []
3463−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3464−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3465−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3468−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3469−plainHighPairs Nothing = []
3470−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3471− [ "type" .= String "plain"]
3472− ++ commonHighlightPairs plCom
3473− ++ nonPostingsToPairs plNonPost
3475−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3476−postHighPairs Nothing = []
3477−postHighPairs (Just (PostingsHighlight pCom)) =
3478− ("type" .= String "postings")
3479− : commonHighlightPairs pCom
3481−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3482−fastVectorHighPairs Nothing = []
3483−fastVectorHighPairs (Just
3484− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3485− fvBoundMaxScan fvFragOff fvMatchedFields
3487− [ "type" .= String "fvh"
3488− , "boundary_chars" .= fvBoundChars
3489− , "boundary_max_scan" .= fvBoundMaxScan
3490− , "fragment_offset" .= fvFragOff
3491− , "matched_fields" .= fvMatchedFields
3492− , "phraseLimit" .= fvPhraseLim]
3493− ++ commonHighlightPairs fvCom
3494− ++ nonPostingsToPairs fvNonPostSettings
3496−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3497−deleteSeveral ks hm = foldr HM.delete hm ks
3499−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3500−commonHighlightPairs Nothing = []
3501−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3502− chNoMatchSize chHighlightQuery
3503− chRequireFieldMatch)) =
3504− [ "order" .= chScore
3505− , "force_source" .= chForceSource
3506− , "encoder" .= chEncoder
3507− , "no_match_size" .= chNoMatchSize
3508− , "highlight_query" .= chHighlightQuery
3509− , "require_fieldMatch" .= chRequireFieldMatch]
3510− ++ highlightTagToPairs chTag
3513−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3514−nonPostingsToPairs Nothing = []
3515−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3516− [ "fragment_size" .= npFragSize
3517− , "number_of_fragments" .= npNumOfFrags]
3519−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3520−parseNEJSON [] = fail "Expected non-empty list"
3521−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3524−instance ToJSON HighlightEncoder where
3525− toJSON DefaultEncoder = String "default"
3526− toJSON HTMLEncoder = String "html"
3528−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3529−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3530−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3531− , "post_tags" .= post]
3532−highlightTagToPairs Nothing = []
3534−instance ToJSON SortSpec where
3535− toJSON (DefaultSortSpec
3536− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3537− dsSortMode dsMissingSort dsNestedFilter)) =
3538− object [dsSortFieldName .= omitNulls base] where
3539− base = [ "order" .= dsSortOrder
3540− , "ignore_unmapped" .= dsIgnoreUnmapped
3541− , "mode" .= dsSortMode
3542− , "missing" .= dsMissingSort
3543− , "nested_filter" .= dsNestedFilter ]
3545− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3546− object [ "unit" .= units
3547− , field .= gdsLatLon
3548− , "order" .= gdsSortOrder ]
3551−instance ToJSON SortOrder where
3552− toJSON Ascending = String "asc"
3553− toJSON Descending = String "desc"
3556−instance ToJSON SortMode where
3557− toJSON SortMin = String "min"
3558− toJSON SortMax = String "max"
3559− toJSON SortSum = String "sum"
3560− toJSON SortAvg = String "avg"
3563−instance ToJSON Missing where
3564− toJSON LastMissing = String "_last"
3565− toJSON FirstMissing = String "_first"
3566− toJSON (CustomMissing txt) = String txt
3569−instance ToJSON ScoreType where
3570− toJSON ScoreTypeMax = "max"
3571− toJSON ScoreTypeAvg = "avg"
3572− toJSON ScoreTypeSum = "sum"
3573− toJSON ScoreTypeNone = "none"
3575−instance FromJSON ScoreType where
3576− parseJSON = withText "ScoreType" parse
3577− where parse "max" = pure ScoreTypeMax
3578− parse "avg" = pure ScoreTypeAvg
3579− parse "sum" = pure ScoreTypeSum
3580− parse "none" = pure ScoreTypeNone
3581− parse t = fail ("Unexpected ScoreType: " <> show t)
3583−instance ToJSON Distance where
3584− toJSON (Distance dCoefficient dUnit) =
3585− String boltedTogether where
3586− coefText = showText dCoefficient
3587− (String unitText) = toJSON dUnit
3588− boltedTogether = mappend coefText unitText
3590−instance FromJSON Distance where
3591− parseJSON = withText "Distance" parse
3592− where parse t = Distance <$> parseCoeff nT
3593− <*> parseJSON (String unitT)
3594− where (nT, unitT) = T.span validForNumber t
3595− -- may be a better way to do this
3596− validForNumber '-' = True
3597− validForNumber '.' = True
3598− validForNumber 'e' = True
3599− validForNumber c = isNumber c
3600− parseCoeff "" = fail "Empty string cannot be parsed as number"
3601− parseCoeff s = return (read (T.unpack s))
3603−instance ToJSON DistanceUnit where
3604− toJSON Miles = String "mi"
3605− toJSON Yards = String "yd"
3606− toJSON Feet = String "ft"
3607− toJSON Inches = String "in"
3608− toJSON Kilometers = String "km"
3609− toJSON Meters = String "m"
3610− toJSON Centimeters = String "cm"
3611− toJSON Millimeters = String "mm"
3612− toJSON NauticalMiles = String "nmi"
3615−instance FromJSON DistanceUnit where
3616− parseJSON = withText "DistanceUnit" parse
3617− where parse "mi" = pure Miles
3618− parse "yd" = pure Yards
3619− parse "ft" = pure Feet
3620− parse "in" = pure Inches
3621− parse "km" = pure Kilometers
3622− parse "m" = pure Meters
3623− parse "cm" = pure Centimeters
3624− parse "mm" = pure Millimeters
3625− parse "nmi" = pure NauticalMiles
3626− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3628−instance ToJSON DistanceType where
3629− toJSON Arc = String "arc"
3630− toJSON SloppyArc = String "sloppy_arc"
3631− toJSON Plane = String "plane"
3633−instance FromJSON DistanceType where
3634− parseJSON = withText "DistanceType" parse
3635− where parse "arc" = pure Arc
3636− parse "sloppy_arc" = pure SloppyArc
3637− parse "plane" = pure Plane
3638− parse t = fail ("Unrecognized DistanceType: " <> show t)
3641−instance ToJSON OptimizeBbox where
3642− toJSON NoOptimizeBbox = String "none"
3643− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3645−instance FromJSON OptimizeBbox where
3646− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3647− <|> parseOptimize v
3648− where parseNoOptimize "none" = pure NoOptimizeBbox
3649− parseNoOptimize _ = mzero
3650− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3652−instance ToJSON GeoBoundingBoxConstraint where
3653− toJSON (GeoBoundingBoxConstraint
3654− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3655− object [gbbcGeoBBField .= gbbcConstraintBox
3656− , "_cache" .= cache
3659−instance FromJSON GeoBoundingBoxConstraint where
3660− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3661− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3662− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3664− <*> o .:? "_cache" .!= defaultCache
3666− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3668−instance ToJSON GeoFilterType where
3669− toJSON GeoFilterMemory = String "memory"
3670− toJSON GeoFilterIndexed = String "indexed"
3672−instance FromJSON GeoFilterType where
3673− parseJSON = withText "GeoFilterType" parse
3674− where parse "memory" = pure GeoFilterMemory
3675− parse "indexed" = pure GeoFilterIndexed
3676− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3678−instance ToJSON GeoBoundingBox where
3679− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3680− object ["top_left" .= gbbTopLeft
3681− , "bottom_right" .= gbbBottomRight]
3683−instance FromJSON GeoBoundingBox where
3684− parseJSON = withObject "GeoBoundingBox" parse
3685− where parse o = GeoBoundingBox
3686− <$> o .: "top_left"
3687− <*> o .: "bottom_right"
3689−instance ToJSON LatLon where
3690− toJSON (LatLon lLat lLon) =
3691− object ["lat" .= lLat
3694−instance FromJSON LatLon where
3695− parseJSON = withObject "LatLon" parse
3696− where parse o = LatLon <$> o .: "lat"
3699−-- index for smaller ranges, fielddata for longer ranges
3700−instance ToJSON RangeExecution where
3701− toJSON RangeExecutionIndex = "index"
3702− toJSON RangeExecutionFielddata = "fielddata"
3705−instance FromJSON RangeExecution where
3706− parseJSON = withText "RangeExecution" parse
3707− where parse "index" = pure RangeExecutionIndex
3708− parse "fielddata" = pure RangeExecutionFielddata
3709− parse t = error ("Unrecognized RangeExecution " <> show t)
3711−instance ToJSON RegexpFlags where
3712− toJSON AllRegexpFlags = String "ALL"
3713− toJSON NoRegexpFlags = String "NONE"
3714− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3715− where flagStrs = map flagStr . nub $ h:fs
3716− flagStr AnyString = "ANYSTRING"
3717− flagStr Automaton = "AUTOMATON"
3718− flagStr Complement = "COMPLEMENT"
3719− flagStr Empty = "EMPTY"
3720− flagStr Intersection = "INTERSECTION"
3721− flagStr Interval = "INTERVAL"
3723−instance FromJSON RegexpFlags where
3724− parseJSON = withText "RegexpFlags" parse
3725− where parse "ALL" = pure AllRegexpFlags
3726− parse "NONE" = pure NoRegexpFlags
3727− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3729−instance FromJSON RegexpFlag where
3730− parseJSON = withText "RegexpFlag" parse
3731− where parse "ANYSTRING" = pure AnyString
3732− parse "AUTOMATON" = pure Automaton
3733− parse "COMPLEMENT" = pure Complement
3734− parse "EMPTY" = pure Empty
3735− parse "INTERSECTION" = pure Intersection
3736− parse "INTERVAL" = pure Interval
3737− parse f = fail ("Unknown RegexpFlag: " <> show f)
3739−instance ToJSON Term where
3740− toJSON (Term field value) = object ["term" .= object
3743−instance FromJSON Term where
3744− parseJSON = withObject "Term" parse
3745− where parse o = do termObj <- o .: "term"
3746− case HM.toList termObj of
3747− [(fn, v)] -> Term fn <$> parseJSON v
3748− _ -> fail "Expected object with 1 field-named key"
3750−instance ToJSON BoolMatch where
3751− toJSON (MustMatch term cache) = object ["must" .= term,
3753− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3755− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3758−instance FromJSON BoolMatch where
3759− parseJSON = withObject "BoolMatch" parse
3760− where parse o = mustMatch `taggedWith` "must"
3761− <|> mustNotMatch `taggedWith` "must_not"
3762− <|> shouldMatch `taggedWith` "should"
3763− where taggedWith parser k = parser =<< o .: k
3764− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3765− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3766− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3768−instance (FromJSON a) => FromJSON (SearchResult a) where
3769− parseJSON (Object v) = SearchResult <$>
3771− v .: "timed_out" <*>
3774− v .:? "aggregations" <*>
3776− parseJSON _ = empty
3778−instance (FromJSON a) => FromJSON (SearchHits a) where
3779− parseJSON (Object v) = SearchHits <$>
3781− v .: "max_score" <*>
3783− parseJSON _ = empty
3785−instance (FromJSON a) => FromJSON (Hit a) where
3786− parseJSON (Object v) = Hit <$>
3791− v .:? "_source" <*>
3793− parseJSON _ = empty
3795−instance FromJSON ShardResult where
3796− parseJSON (Object v) = ShardResult <$>
3798− v .: "successful" <*>
3800− parseJSON _ = empty
3803−instance FromJSON DocVersion where
3806− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3808−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3809−instance FromJSON ReplicaCount where
3810− parseJSON v = parseAsInt v
3811− <|> parseAsString v
3812− where parseAsInt = fmap ReplicaCount . parseJSON
3813− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3815−instance FromJSON ShardCount where
3816− parseJSON v = parseAsInt v
3817− <|> parseAsString v
3818− where parseAsInt = fmap ShardCount . parseJSON
3819− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3821−instance Bounded DocVersion where
3822− minBound = DocVersion 1
3823− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3825−instance Enum DocVersion where
3827− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3828− | otherwise = succError "DocVersion"
3830− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3831− | otherwise = predError "DocVersion"
3833− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3834− fromEnum = docVersionNumber
3835− enumFrom = boundedEnumFrom
3836− enumFromThen = boundedEnumFromThen
3838−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3839−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3841−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3842−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3845−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3846− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3849−-- | Either specifies an exact repo name or one with globs in it,
3850−-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3851−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3853− deriving (Eq, Generic, Show, Typeable)
3855−-- | The unique name of a snapshot repository.
3856−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3857− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3860−-- | A generic representation of a snapshot repo. This is what gets
3861−-- sent to and parsed from the server. For repo types enabled by
3862−-- plugins that aren't exported by this library, consider making a
3863−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3864−-- type, consider submitting a pull request to have it included in the
3866−data GenericSnapshotRepo = GenericSnapshotRepo {
3867− gSnapshotRepoName :: SnapshotRepoName
3868− , gSnapshotRepoType :: SnapshotRepoType
3869− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3870− } deriving (Eq, Generic, Show, Typeable)
3873−instance SnapshotRepo GenericSnapshotRepo where
3874− toGSnapshotRepo = id
3875− fromGSnapshotRepo = Right
3878−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3879− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3882−-- | Opaque representation of snapshot repo settings. Instances of
3883−-- 'SnapshotRepo' will produce this.
3884−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3885− deriving (Eq, Generic, Show, Typeable, ToJSON)
3888− -- Regardless of whether you send strongly typed json, my version of
3889− -- ES sends back stringly typed json in the settings, e.g. booleans
3890− -- as strings, so we'll try to convert them.
3891−instance FromJSON GenericSnapshotRepoSettings where
3892− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3894−-- | The result of running 'verifySnapshotRepo'.
3895−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3896− deriving (Eq, Generic, Show, Typeable)
3899−instance FromJSON SnapshotVerification where
3900− parseJSON = withObject "SnapshotVerification" parse
3904− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3905− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3906− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3909−-- | A node that has verified a snapshot
3910−data SnapshotNodeVerification = SnapshotNodeVerification {
3911− snvFullId :: FullNodeId
3912− , snvNodeName :: NodeName
3913− } deriving (Eq, Generic, Show, Typeable)
3916−-- | Unique, automatically-generated name assigned to nodes that are
3917−-- usually returned in node-oriented APIs.
3918−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3919− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3922−-- | A human-readable node name that is supplied by the user in the
3923−-- node config or automatically generated by ElasticSearch.
3924−newtype NodeName = NodeName { nodeName :: Text }
3925− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3927−newtype ClusterName = ClusterName { clusterName :: Text }
3928− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3930−data NodesInfo = NodesInfo {
3931− nodesInfo :: [NodeInfo]
3932− , nodesClusterName :: ClusterName
3933− } deriving (Eq, Show, Generic, Typeable)
3935−data NodesStats = NodesStats {
3936− nodesStats :: [NodeStats]
3937− , nodesStatsClusterName :: ClusterName
3938− } deriving (Eq, Show, Generic, Typeable)
3940−data NodeStats = NodeStats {
3941− nodeStatsName :: NodeName
3942− , nodeStatsFullId :: FullNodeId
3943− , nodeStatsBreakersStats :: Maybe NodeBreakersStats
3944− , nodeStatsHTTP :: NodeHTTPStats
3945− , nodeStatsTransport :: NodeTransportStats
3946− , nodeStatsFS :: NodeFSStats
3947− , nodeStatsNetwork :: NodeNetworkStats
3948− , nodeStatsThreadPool :: NodeThreadPoolsStats
3949− , nodeStatsJVM :: NodeJVMStats
3950− , nodeStatsProcess :: NodeProcessStats
3951− , nodeStatsOS :: NodeOSStats
3952− , nodeStatsIndices :: NodeIndicesStats
3953− } deriving (Eq, Show, Generic, Typeable)
3955−data NodeBreakersStats = NodeBreakersStats {
3956− nodeStatsParentBreaker :: NodeBreakerStats
3957− , nodeStatsRequestBreaker :: NodeBreakerStats
3958− , nodeStatsFieldDataBreaker :: NodeBreakerStats
3959− } deriving (Eq, Show, Generic, Typeable)
3961−data NodeBreakerStats = NodeBreakerStats {
3962− nodeBreakersTripped :: Int
3963− , nodeBreakersOverhead :: Double
3964− , nodeBreakersEstSize :: Bytes
3965− , nodeBreakersLimitSize :: Bytes
3966− } deriving (Eq, Show, Generic, Typeable)
3968−data NodeHTTPStats = NodeHTTPStats {
3969− nodeHTTPTotalOpened :: Int
3970− , nodeHTTPCurrentOpen :: Int
3971− } deriving (Eq, Show, Generic, Typeable)
3973−data NodeTransportStats = NodeTransportStats {
3974− nodeTransportTXSize :: Bytes
3975− , nodeTransportCount :: Int
3976− , nodeTransportRXSize :: Bytes
3977− , nodeTransportRXCount :: Int
3978− , nodeTransportServerOpen :: Int
3979− } deriving (Eq, Show, Generic, Typeable)
3981−data NodeFSStats = NodeFSStats {
3982− nodeFSDataPaths :: [NodeDataPathStats]
3983− , nodeFSTotal :: NodeFSTotalStats
3984− , nodeFSTimestamp :: UTCTime
3985− } deriving (Eq, Show, Generic, Typeable)
3987−data NodeDataPathStats = NodeDataPathStats {
3988− nodeDataPathDiskServiceTime :: Maybe Double
3989− , nodeDataPathDiskQueue :: Maybe Double
3990− , nodeDataPathIOSize :: Maybe Bytes
3991− , nodeDataPathWriteSize :: Maybe Bytes
3992− , nodeDataPathReadSize :: Maybe Bytes
3993− , nodeDataPathIOOps :: Maybe Int
3994− , nodeDataPathWrites :: Maybe Int
3995− , nodeDataPathReads :: Maybe Int
3996− , nodeDataPathAvailable :: Bytes
3997− , nodeDataPathFree :: Bytes
3998− , nodeDataPathTotal :: Bytes
3999− , nodeDataPathType :: Maybe Text
4000− , nodeDataPathDevice :: Text
4001− , nodeDataPathMount :: Text
4002− , nodeDataPathPath :: Text
4003− } deriving (Eq, Show, Generic, Typeable)
4005−data NodeFSTotalStats = NodeFSTotalStats {
4006− nodeFSTotalDiskServiceTime :: Maybe Double
4007− , nodeFSTotalDiskQueue :: Maybe Double
4008− , nodeFSTotalIOSize :: Maybe Bytes
4009− , nodeFSTotalWriteSize :: Maybe Bytes
4010− , nodeFSTotalReadSize :: Maybe Bytes
4011− , nodeFSTotalIOOps :: Maybe Int
4012− , nodeFSTotalWrites :: Maybe Int
4013− , nodeFSTotalReads :: Maybe Int
4014− , nodeFSTotalAvailable :: Bytes
4015− , nodeFSTotalFree :: Bytes
4016− , nodeFSTotalTotal :: Bytes
4017− } deriving (Eq, Show, Generic, Typeable)
4019−data NodeNetworkStats = NodeNetworkStats {
4020− nodeNetTCPOutRSTs :: Int
4021− , nodeNetTCPInErrs :: Int
4022− , nodeNetTCPAttemptFails :: Int
4023− , nodeNetTCPEstabResets :: Int
4024− , nodeNetTCPRetransSegs :: Int
4025− , nodeNetTCPOutSegs :: Int
4026− , nodeNetTCPInSegs :: Int
4027− , nodeNetTCPCurrEstab :: Int
4028− , nodeNetTCPPassiveOpens :: Int
4029− , nodeNetTCPActiveOpens :: Int
4030− } deriving (Eq, Show, Generic, Typeable)
4032−data NodeThreadPoolsStats = NodeThreadPoolsStats {
4033− nodeThreadPoolsStatsSnapshot :: NodeThreadPoolStats
4034− , nodeThreadPoolsStatsBulk :: NodeThreadPoolStats
4035− , nodeThreadPoolsStatsMerge :: NodeThreadPoolStats
4036− , nodeThreadPoolsStatsGet :: NodeThreadPoolStats
4037− , nodeThreadPoolsStatsManagement :: NodeThreadPoolStats
4038− , nodeThreadPoolsStatsFetchShardStore :: Maybe NodeThreadPoolStats
4039− , nodeThreadPoolsStatsOptimize :: NodeThreadPoolStats
4040− , nodeThreadPoolsStatsFlush :: NodeThreadPoolStats
4041− , nodeThreadPoolsStatsSearch :: NodeThreadPoolStats
4042− , nodeThreadPoolsStatsWarmer :: NodeThreadPoolStats
4043− , nodeThreadPoolsStatsGeneric :: NodeThreadPoolStats
4044− , nodeThreadPoolsStatsSuggest :: NodeThreadPoolStats
4045− , nodeThreadPoolsStatsRefresh :: NodeThreadPoolStats
4046− , nodeThreadPoolsStatsIndex :: NodeThreadPoolStats
4047− , nodeThreadPoolsStatsListener :: Maybe NodeThreadPoolStats
4048− , nodeThreadPoolsStatsFetchShardStarted :: Maybe NodeThreadPoolStats
4049− , nodeThreadPoolsStatsPercolate :: NodeThreadPoolStats
4050− } deriving (Eq, Show, Generic, Typeable)
4052−data NodeThreadPoolStats = NodeThreadPoolStats {
4053− nodeThreadPoolCompleted :: Int
4054− , nodeThreadPoolLargest :: Int
4055− , nodeThreadPoolRejected :: Int
4056− , nodeThreadPoolActive :: Int
4057− , nodeThreadPoolQueue :: Int
4058− , nodeThreadPoolThreads :: Int
4059− } deriving (Eq, Show, Generic, Typeable)
4061−data NodeJVMStats = NodeJVMStats {
4062− nodeJVMStatsMappedBufferPool :: JVMBufferPoolStats
4063− , nodeJVMStatsDirectBufferPool :: JVMBufferPoolStats
4064− , nodeJVMStatsGCOldCollector :: JVMGCStats
4065− , nodeJVMStatsGCYoungCollector :: JVMGCStats
4066− , nodeJVMStatsPeakThreadsCount :: Int
4067− , nodeJVMStatsThreadsCount :: Int
4068− , nodeJVMStatsOldPool :: JVMPoolStats
4069− , nodeJVMStatsSurvivorPool :: JVMPoolStats
4070− , nodeJVMStatsYoungPool :: JVMPoolStats
4071− , nodeJVMStatsNonHeapCommitted :: Bytes
4072− , nodeJVMStatsNonHeapUsed :: Bytes
4073− , nodeJVMStatsHeapMax :: Bytes
4074− , nodeJVMStatsHeapCommitted :: Bytes
4075− , nodeJVMStatsHeapUsedPercent :: Int
4076− , nodeJVMStatsHeapUsed :: Bytes
4077− , nodeJVMStatsUptime :: NominalDiffTime
4078− , nodeJVMStatsTimestamp :: UTCTime
4079− } deriving (Eq, Show, Generic, Typeable)
4081−data JVMBufferPoolStats = JVMBufferPoolStats {
4082− jvmBufferPoolStatsTotalCapacity :: Bytes
4083− , jvmBufferPoolStatsUsed :: Bytes
4084− , jvmBufferPoolStatsCount :: Int
4085− } deriving (Eq, Show, Generic, Typeable)
4087−data JVMGCStats = JVMGCStats {
4088− jvmGCStatsCollectionTime :: NominalDiffTime
4089− , jvmGCStatsCollectionCount :: Int
4090− } deriving (Eq, Show, Generic, Typeable)
4092−data JVMPoolStats = JVMPoolStats {
4093− jvmPoolStatsPeakMax :: Bytes
4094− , jvmPoolStatsPeakUsed :: Bytes
4095− , jvmPoolStatsMax :: Bytes
4096− , jvmPoolStatsUsed :: Bytes
4097− } deriving (Eq, Show, Generic, Typeable)
4099−data NodeProcessStats = NodeProcessStats {
4100− nodeProcessMemTotalVirtual :: Bytes
4101− , nodeProcessMemShare :: Bytes
4102− , nodeProcessMemResident :: Bytes
4103− , nodeProcessCPUTotal :: NominalDiffTime
4104− , nodeProcessCPUUser :: NominalDiffTime
4105− , nodeProcessCPUSys :: NominalDiffTime
4106− , nodeProcessCPUPercent :: Int
4107− , nodeProcessOpenFDs :: Int
4108− , nodeProcessTimestamp :: UTCTime
4109− } deriving (Eq, Show, Generic, Typeable)
4111−data NodeOSStats = NodeOSStats {
4112− nodeOSSwapFree :: Bytes
4113− , nodeOSSwapUsed :: Bytes
4114− , nodeOSMemActualUsed :: Bytes
4115− , nodeOSMemActualFree :: Bytes
4116− , nodeOSMemUsedPercent :: Int
4117− , nodeOSMemFreePercent :: Int
4118− , nodeOSMemUsed :: Bytes
4119− , nodeOSMemFree :: Bytes
4120− , nodeOSCPUStolen :: Int
4121− , nodeOSCPUUsage :: Int
4122− , nodeOSCPUIdle :: Int
4123− , nodeOSCPUUser :: Int
4124− , nodeOSCPUSys :: Int
4125− , nodeOSLoad :: Maybe LoadAvgs
4126− , nodeOSUptime :: NominalDiffTime
4127− , nodeOSTimestamp :: UTCTime
4128− } deriving (Eq, Show, Generic, Typeable)
4130−data LoadAvgs = LoadAvgs {
4131− loadAvg1Min :: Double
4132− , loadAvg5Min :: Double
4133− , loadAvg15Min :: Double
4134− } deriving (Eq, Show, Generic, Typeable)
4136−data NodeIndicesStats = NodeIndicesStats {
4137− nodeIndicesStatsRecoveryThrottleTime :: Maybe NominalDiffTime
4138− , nodeIndicesStatsRecoveryCurrentAsTarget :: Maybe Int
4139− , nodeIndicesStatsRecoveryCurrentAsSource :: Maybe Int
4140− , nodeIndicesStatsQueryCacheMisses :: Maybe Int
4141− , nodeIndicesStatsQueryCacheHits :: Maybe Int
4142− , nodeIndicesStatsQueryCacheEvictions :: Maybe Int
4143− , nodeIndicesStatsQueryCacheSize :: Maybe Bytes
4144− , nodeIndicesStatsSuggestCurrent :: Int
4145− , nodeIndicesStatsSuggestTime :: NominalDiffTime
4146− , nodeIndicesStatsSuggestTotal :: Int
4147− , nodeIndicesStatsTranslogSize :: Bytes
4148− , nodeIndicesStatsTranslogOps :: Int
4149− , nodeIndicesStatsSegFixedBitSetMemory :: Maybe Bytes
4150− , nodeIndicesStatsSegVersionMapMemory :: Bytes
4151− , nodeIndicesStatsSegIndexWriterMaxMemory :: Maybe Bytes
4152− , nodeIndicesStatsSegIndexWriterMemory :: Bytes
4153− , nodeIndicesStatsSegMemory :: Bytes
4154− , nodeIndicesStatsSegCount :: Int
4155− , nodeIndicesStatsCompletionSize :: Bytes
4156− , nodeIndicesStatsPercolateQueries :: Int
4157− , nodeIndicesStatsPercolateMemory :: Bytes
4158− , nodeIndicesStatsPercolateCurrent :: Int
4159− , nodeIndicesStatsPercolateTime :: NominalDiffTime
4160− , nodeIndicesStatsPercolateTotal :: Int
4161− , nodeIndicesStatsFieldDataEvictions :: Int
4162− , nodeIndicesStatsFieldDataMemory :: Bytes
4163− , nodeIndicesStatsIDCacheMemory :: Bytes
4164− , nodeIndicesStatsFilterCacheEvictions :: Int
4165− , nodeIndicesStatsFilterCacheMemory :: Bytes
4166− , nodeIndicesStatsWarmerTotalTime :: NominalDiffTime
4167− , nodeIndicesStatsWarmerTotal :: Int
4168− , nodeIndicesStatsWarmerCurrent :: Int
4169− , nodeIndicesStatsFlushTotalTime :: NominalDiffTime
4170− , nodeIndicesStatsFlushTotal :: Int
4171− , nodeIndicesStatsRefreshTotalTime :: NominalDiffTime
4172− , nodeIndicesStatsRefreshTotal :: Int
4173− , nodeIndicesStatsMergesTotalSize :: Bytes
4174− , nodeIndicesStatsMergesTotalDocs :: Int
4175− , nodeIndicesStatsMergesTotalTime :: NominalDiffTime
4176− , nodeIndicesStatsMergesTotal :: Int
4177− , nodeIndicesStatsMergesCurrentSize :: Bytes
4178− , nodeIndicesStatsMergesCurrentDocs :: Int
4179− , nodeIndicesStatsMergesCurrent :: Int
4180− , nodeIndicesStatsSearchFetchCurrent :: Int
4181− , nodeIndicesStatsSearchFetchTime :: NominalDiffTime
4182− , nodeIndicesStatsSearchFetchTotal :: Int
4183− , nodeIndicesStatsSearchQueryCurrent :: Int
4184− , nodeIndicesStatsSearchQueryTime :: NominalDiffTime
4185− , nodeIndicesStatsSearchQueryTotal :: Int
4186− , nodeIndicesStatsSearchOpenContexts :: Int
4187− , nodeIndicesStatsGetCurrent :: Int
4188− , nodeIndicesStatsGetMissingTime :: NominalDiffTime
4189− , nodeIndicesStatsGetMissingTotal :: Int
4190− , nodeIndicesStatsGetExistsTime :: NominalDiffTime
4191− , nodeIndicesStatsGetExistsTotal :: Int
4192− , nodeIndicesStatsGetTime :: NominalDiffTime
4193− , nodeIndicesStatsGetTotal :: Int
4194− , nodeIndicesStatsIndexingThrottleTime :: Maybe NominalDiffTime
4195− , nodeIndicesStatsIndexingIsThrottled :: Maybe Bool
4196− , nodeIndicesStatsIndexingNoopUpdateTotal :: Maybe Int
4197− , nodeIndicesStatsIndexingDeleteCurrent :: Int
4198− , nodeIndicesStatsIndexingDeleteTime :: NominalDiffTime
4199− , nodeIndicesStatsIndexingDeleteTotal :: Int
4200− , nodeIndicesStatsIndexingIndexCurrent :: Int
4201− , nodeIndicesStatsIndexingIndexTime :: NominalDiffTime
4202− , nodeIndicesStatsIndexingTotal :: Int
4203− , nodeIndicesStatsStoreThrottleTime :: NominalDiffTime
4204− , nodeIndicesStatsStoreSize :: Bytes
4205− , nodeIndicesStatsDocsDeleted :: Int
4206− , nodeIndicesStatsDocsCount :: Int
4207− } deriving (Eq, Show, Generic, Typeable)
4209−-- | A quirky address format used throughout ElasticSearch. An example
4210−-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
4211−-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
4212−newtype EsAddress = EsAddress { esAddress :: Text }
4213− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4215−-- | Typically a 7 character hex string.
4216−newtype BuildHash = BuildHash { buildHash :: Text }
4217− deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
4219−newtype PluginName = PluginName { pluginName :: Text }
4220− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4222−data NodeInfo = NodeInfo {
4223− nodeInfoHTTPAddress :: EsAddress
4224− , nodeInfoBuild :: BuildHash
4225− , nodeInfoESVersion :: VersionNumber
4226− , nodeInfoIP :: Server
4227− , nodeInfoHost :: Server
4228− , nodeInfoTransportAddress :: EsAddress
4229− , nodeInfoName :: NodeName
4230− , nodeInfoFullId :: FullNodeId
4231− , nodeInfoPlugins :: [NodePluginInfo]
4232− , nodeInfoHTTP :: NodeHTTPInfo
4233− , nodeInfoTransport :: NodeTransportInfo
4234− , nodeInfoNetwork :: NodeNetworkInfo
4235− , nodeInfoThreadPool :: NodeThreadPoolsInfo
4236− , nodeInfoJVM :: NodeJVMInfo
4237− , nodeInfoProcess :: NodeProcessInfo
4238− , nodeInfoOS :: NodeOSInfo
4239− , nodeInfoSettings :: Object
4240− -- ^ The members of the settings objects are not consistent,
4241− -- dependent on plugins, etc.
4242− } deriving (Eq, Show, Generic, Typeable)
4244−data NodePluginInfo = NodePluginInfo {
4245− nodePluginSite :: Bool
4246− -- ^ Is this a site plugin?
4247− , nodePluginJVM :: Bool
4248− -- ^ Is this plugin running on the JVM
4249− , nodePluginDescription :: Text
4250− , nodePluginVersion :: MaybeNA VersionNumber
4251− , nodePluginName :: PluginName
4252− } deriving (Eq, Show, Generic, Typeable)
4254−data NodeHTTPInfo = NodeHTTPInfo {
4255− nodeHTTPMaxContentLength :: Bytes
4256− , nodeHTTPTransportAddress :: BoundTransportAddress
4257− } deriving (Eq, Show, Generic, Typeable)
4259−data NodeTransportInfo = NodeTransportInfo {
4260− nodeTransportProfiles :: [BoundTransportAddress]
4261− , nodeTransportAddress :: BoundTransportAddress
4262− } deriving (Eq, Show, Generic, Typeable)
4264−data BoundTransportAddress = BoundTransportAddress {
4265− publishAddress :: EsAddress
4266− , boundAddress :: EsAddress
4267− } deriving (Eq, Show, Generic, Typeable)
4269−data NodeNetworkInfo = NodeNetworkInfo {
4270− nodeNetworkPrimaryInterface :: NodeNetworkInterface
4271− , nodeNetworkRefreshInterval :: NominalDiffTime
4272− } deriving (Eq, Show, Generic, Typeable)
4274−newtype MacAddress = MacAddress { macAddress :: Text }
4275− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4277−newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
4278− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4280−data NodeNetworkInterface = NodeNetworkInterface {
4281− nodeNetIfaceMacAddress :: MacAddress
4282− , nodeNetIfaceName :: NetworkInterfaceName
4283− , nodeNetIfaceAddress :: Server
4284− } deriving (Eq, Show, Generic, Typeable)
4286−data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
4287− nodeThreadPoolsRefresh :: NodeThreadPoolInfo
4288− , nodeThreadPoolsManagement :: NodeThreadPoolInfo
4289− , nodeThreadPoolsPercolate :: NodeThreadPoolInfo
4290− , nodeThreadPoolsListener :: Maybe NodeThreadPoolInfo
4291− , nodeThreadPoolsFetchShardStarted :: Maybe NodeThreadPoolInfo
4292− , nodeThreadPoolsSearch :: NodeThreadPoolInfo
4293− , nodeThreadPoolsFlush :: NodeThreadPoolInfo
4294− , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
4295− , nodeThreadPoolsOptimize :: NodeThreadPoolInfo
4296− , nodeThreadPoolsBulk :: NodeThreadPoolInfo
4297− , nodeThreadPoolsSuggest :: NodeThreadPoolInfo
4298− , nodeThreadPoolsMerge :: NodeThreadPoolInfo
4299− , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
4300− , nodeThreadPoolsGet :: NodeThreadPoolInfo
4301− , nodeThreadPoolsFetchShardStore :: Maybe NodeThreadPoolInfo
4302− , nodeThreadPoolsIndex :: NodeThreadPoolInfo
4303− , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
4304− } deriving (Eq, Show, Generic, Typeable)
4306−data NodeThreadPoolInfo = NodeThreadPoolInfo {
4307− nodeThreadPoolQueueSize :: ThreadPoolSize
4308− , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
4309− , nodeThreadPoolMin :: Maybe Int
4310− , nodeThreadPoolMax :: Maybe Int
4311− , nodeThreadPoolType :: ThreadPoolType
4312− } deriving (Eq, Show, Generic, Typeable)
4314−data ThreadPoolSize = ThreadPoolBounded Int
4315− | ThreadPoolUnbounded
4316− deriving (Eq, Show, Generic, Typeable)
4318−data ThreadPoolType = ThreadPoolScaling
4321− deriving (Eq, Show, Generic, Typeable)
4323−data NodeJVMInfo = NodeJVMInfo {
4324− nodeJVMInfoMemoryPools :: [JVMMemoryPool]
4325− , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
4326− , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
4327− , nodeJVMInfoStartTime :: UTCTime
4328− , nodeJVMInfoVMVendor :: Text
4329− , nodeJVMVMVersion :: VersionNumber
4330− -- ^ JVM doesn't seme to follow normal version conventions
4331− , nodeJVMVMName :: Text
4332− , nodeJVMVersion :: VersionNumber
4333− , nodeJVMPID :: PID
4334− } deriving (Eq, Show, Generic, Typeable)
4336−-- | Handles quirks in the way JVM versions are rendered (1.7.0_101 -> 1.7.0.101)
4337−newtype JVMVersion = JVMVersion { unJVMVersion :: VersionNumber }
4339−data JVMMemoryInfo = JVMMemoryInfo {
4340− jvmMemoryInfoDirectMax :: Bytes
4341− , jvmMemoryInfoNonHeapMax :: Bytes
4342− , jvmMemoryInfoNonHeapInit :: Bytes
4343− , jvmMemoryInfoHeapMax :: Bytes
4344− , jvmMemoryInfoHeapInit :: Bytes
4345− } deriving (Eq, Show, Generic, Typeable)
4347−newtype JVMMemoryPool = JVMMemoryPool {
4348− jvmMemoryPool :: Text
4349− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4351−newtype JVMGCCollector = JVMGCCollector {
4352− jvmGCCollector :: Text
4353− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4357− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4359−data NodeOSInfo = NodeOSInfo {
4360− nodeOSSwap :: Bytes
4361− , nodeOSMem :: Bytes
4362− , nodeOSCPUInfo :: CPUInfo
4363− , nodeOSAvailableProcessors :: Int
4364− , nodeOSRefreshInterval :: NominalDiffTime
4365− } deriving (Eq, Show, Generic, Typeable)
4367−data CPUInfo = CPUInfo {
4368− cpuCacheSize :: Bytes
4369− , cpuCoresPerSocket :: Int
4370− , cpuTotalSockets :: Int
4371− , cpuTotalCores :: Int
4374− , cpuVendor :: Text
4375− } deriving (Eq, Show, Generic, Typeable)
4377−data NodeProcessInfo = NodeProcessInfo {
4378− nodeProcessMLockAll :: Bool
4379− -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
4380− , nodeProcessMaxFileDescriptors :: Int
4381− , nodeProcessId :: PID
4382− , nodeProcessRefreshInterval :: NominalDiffTime
4383− } deriving (Eq, Show, Generic, Typeable)
4385−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
4386− repoUpdateVerify :: Bool
4387− -- ^ After creation/update, synchronously check that nodes can
4388− -- write to this repo. Defaults to True. You may use False if you
4389− -- need a faster response and plan on verifying manually later
4390− -- with 'verifySnapshotRepo'.
4391− } deriving (Eq, Show, Generic, Typeable)
4394−-- | Reasonable defaults for repo creation/update
4396−-- * repoUpdateVerify True
4397−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4398−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4401−-- | A filesystem-based snapshot repo that ships with
4402−-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4403−-- used with 'updateSnapshotRepo'
4404−data FsSnapshotRepo = FsSnapshotRepo {
4405− fsrName :: SnapshotRepoName
4406− , fsrLocation :: FilePath
4407− , fsrCompressMetadata :: Bool
4408− , fsrChunkSize :: Maybe Bytes
4409− -- ^ Size by which to split large files during snapshotting.
4410− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4411− -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4412− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4413− -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4414− } deriving (Eq, Generic, Show, Typeable)
4417−instance SnapshotRepo FsSnapshotRepo where
4418− toGSnapshotRepo FsSnapshotRepo {..} =
4419− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4421− Object settings = object $ [ "location" .= fsrLocation
4422− , "compress" .= fsrCompressMetadata
4424− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4425− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4426− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4428− fromGSnapshotRepo GenericSnapshotRepo {..}
4429− | gSnapshotRepoType == fsRepoType = do
4430− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4432− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4433− <*> o .:? "compress" .!= False
4434− <*> o .:? "chunk_size"
4435− <*> o .:? "max_restore_bytes_per_sec"
4436− <*> o .:? "max_snapshot_bytes_per_sec"
4437− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4440−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4441−parseRepo parser = case parseEither (const parser) () of
4442− Left e -> Left (OtherRepoConversionError (T.pack e))
4446−fsRepoType :: SnapshotRepoType
4447−fsRepoType = SnapshotRepoType "fs"
4449−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4450−class SnapshotRepo r where
4451− toGSnapshotRepo :: r -> GenericSnapshotRepo
4452− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4455−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4456− -- ^ Expected type and actual type
4457− | OtherRepoConversionError Text
4458− deriving (Show, Eq, Generic, Typeable)
4461−instance Exception SnapshotRepoConversionError
4464−data SnapshotCreateSettings = SnapshotCreateSettings {
4465− snapWaitForCompletion :: Bool
4466− -- ^ Should the API call return immediately after initializing
4467− -- the snapshot or wait until completed? Note that if this is
4468− -- enabled it could wait a long time, so you should adjust your
4469− -- 'ManagerSettings' accordingly to set long timeouts or
4470− -- explicitly handle timeouts.
4471− , snapIndices :: Maybe IndexSelection
4472− -- ^ Nothing will snapshot all indices. Just [] is permissable and
4473− -- will essentially be a no-op snapshot.
4474− , snapIgnoreUnavailable :: Bool
4475− -- ^ If set to True, any matched indices that don't exist will be
4476− -- ignored. Otherwise it will be an error and fail.
4477− , snapIncludeGlobalState :: Bool
4478− , snapPartial :: Bool
4479− -- ^ If some indices failed to snapshot (e.g. if not all primary
4480− -- shards are available), should the process proceed?
4481− } deriving (Eq, Generic, Show, Typeable)
4484−-- | Reasonable defaults for snapshot creation
4486−-- * snapWaitForCompletion False
4487−-- * snapIndices Nothing
4488−-- * snapIgnoreUnavailable False
4489−-- * snapIncludeGlobalState True
4490−-- * snapPartial False
4491−defaultSnapshotCreateSettings :: SnapshotCreateSettings
4492−defaultSnapshotCreateSettings = SnapshotCreateSettings {
4493− snapWaitForCompletion = False
4494− , snapIndices = Nothing
4495− , snapIgnoreUnavailable = False
4496− , snapIncludeGlobalState = True
4497− , snapPartial = False
4501−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4502− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4505−-- | Either specifies an exact snapshot name or one with globs in it,
4506−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4508−data SnapshotPattern = ExactSnap SnapshotName
4510− deriving (Eq, Generic, Show, Typeable)
4513−-- | General information about the state of a snapshot. Has some
4514−-- redundancies with 'SnapshotStatus'
4515−data SnapshotInfo = SnapshotInfo {
4516− snapInfoShards :: ShardResult
4517− , snapInfoFailures :: [SnapshotShardFailure]
4518− , snapInfoDuration :: NominalDiffTime
4519− , snapInfoEndTime :: UTCTime
4520− , snapInfoStartTime :: UTCTime
4521− , snapInfoState :: SnapshotState
4522− , snapInfoIndices :: [IndexName]
4523− , snapInfoName :: SnapshotName
4524− } deriving (Eq, Generic, Show, Typeable)
4527−instance FromJSON SnapshotInfo where
4528− parseJSON = withObject "SnapshotInfo" parse
4530− parse o = SnapshotInfo <$> o .: "shards"
4531− <*> o .: "failures"
4532− <*> (unMS <$> o .: "duration_in_millis")
4533− <*> (posixMS <$> o .: "end_time_in_millis")
4534− <*> (posixMS <$> o .: "start_time_in_millis")
4537− <*> o .: "snapshot"
4539−data SnapshotShardFailure = SnapshotShardFailure {
4540− snapShardFailureIndex :: IndexName
4541− , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4542− , snapShardFailureReason :: Text
4543− , snapShardFailureShardId :: ShardId
4544− } deriving (Eq, Show, Generic, Typeable)
4547−instance FromJSON SnapshotShardFailure where
4548− parseJSON = withObject "SnapshotShardFailure" parse
4550− parse o = SnapshotShardFailure <$> o .: "index"
4551− <*> o .:? "node_id"
4553− <*> o .: "shard_id"
4556−newtype ShardId = ShardId { shardId :: Int }
4557− deriving (Eq, Show, Generic, Typeable, FromJSON)
4560−newtype MS = MS NominalDiffTime
4563−-- keeps the unexported constructor warnings at bay
4564−unMS :: MS -> NominalDiffTime
4568−instance FromJSON MS where
4569− parseJSON = withScientific "MS" (return . MS . parse)
4571− parse n = fromInteger ((truncate n) * 1000)
4574−data SnapshotState = SnapshotInit
4581− deriving (Show, Eq, Generic, Typeable)
4583−instance FromJSON SnapshotState where
4584− parseJSON = withText "SnapshotState" parse
4586− parse "INIT" = return SnapshotInit
4587− parse "STARTED" = return SnapshotStarted
4588− parse "SUCCESS" = return SnapshotSuccess
4589− parse "FAILED" = return SnapshotFailed
4590− parse "ABORTED" = return SnapshotAborted
4591− parse "MISSING" = return SnapshotMissing
4592− parse "WAITING" = return SnapshotWaiting
4593− parse t = fail ("Invalid snapshot state " <> T.unpack t)
4596−newtype SnapshotName = SnapshotName { snapshotName :: Text }
4597− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4600−data SnapshotRestoreSettings = SnapshotRestoreSettings {
4601− snapRestoreWaitForCompletion :: Bool
4602− -- ^ Should the API call return immediately after initializing
4603− -- the restore or wait until completed? Note that if this is
4604− -- enabled, it could wait a long time, so you should adjust your
4605− -- 'ManagerSettings' accordingly to set long timeouts or
4606− -- explicitly handle timeouts.
4607− , snapRestoreIndices :: Maybe IndexSelection
4608− -- ^ Nothing will restore all indices in the snapshot. Just [] is
4609− -- permissable and will essentially be a no-op restore.
4610− , snapRestoreIgnoreUnavailable :: Bool
4611− -- ^ If set to True, any indices that do not exist will be ignored
4612− -- during snapshot rather than failing the restore.
4613− , snapRestoreIncludeGlobalState :: Bool
4614− -- ^ If set to false, will ignore any global state in the snapshot
4615− -- and will not restore it.
4616− , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4617− -- ^ A regex pattern for matching indices. Used with
4618− -- 'snapRestoreRenameReplacement', the restore can reference the
4619− -- matched index and create a new index name upon restore.
4620− , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4621− -- ^ Expression of how index renames should be constructed.
4622− , snapRestorePartial :: Bool
4623− -- ^ If some indices fail to restore, should the process proceed?
4624− , snapRestoreIncludeAliases :: Bool
4625− -- ^ Should the restore also restore the aliases captured in the
4627− , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4628− -- ^ Settings to apply during the restore process. __NOTE:__ This
4629− -- option is not supported in ES < 1.5 and should be set to
4630− -- Nothing in that case.
4631− , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4632− -- ^ This type could be more rich but it isn't clear which
4633− -- settings are allowed to be ignored during restore, so we're
4634− -- going with including this feature in a basic form rather than
4635− -- omitting it. One example here would be
4636− -- "index.refresh_interval". Any setting specified here will
4637− -- revert back to the server default during the restore process.
4638− } deriving (Eq, Generic, Show, Typeable)
4640−-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4641−newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4642− deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4645−-- | A single token in a index renaming scheme for a restore. These
4646−-- are concatenated into a string before being sent to
4647−-- ElasticSearch. Check out these Java
4648−-- <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.
4649−data RestoreRenameToken = RRTLit Text
4650− -- ^ Just a literal string of characters
4652− -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4653− | RRSubGroup RRGroupRefNum
4654− -- ^ A specific reference to a group number
4655− deriving (Show, Eq, Generic, Typeable)
4658−-- | A group number for regex matching. Only values from 1-9 are
4659−-- supported. Construct with 'mkRRGroupRefNum'
4660−newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4661− deriving (Show, Eq, Generic, Typeable, Ord)
4663−instance Bounded RRGroupRefNum where
4664− minBound = RRGroupRefNum 1
4665− maxBound = RRGroupRefNum 9
4668−-- | Only allows valid group number references (1-9).
4669−mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4671− | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4672− Just $ RRGroupRefNum i
4673− | otherwise = Nothing
4676−-- | Reasonable defaults for snapshot restores
4678−-- * snapRestoreWaitForCompletion False
4679−-- * snapRestoreIndices Nothing
4680−-- * snapRestoreIgnoreUnavailable False
4681−-- * snapRestoreIncludeGlobalState True
4682−-- * snapRestoreRenamePattern Nothing
4683−-- * snapRestoreRenameReplacement Nothing
4684−-- * snapRestorePartial False
4685−-- * snapRestoreIncludeAliases True
4686−-- * snapRestoreIndexSettingsOverrides Nothing
4687−-- * snapRestoreIgnoreIndexSettings Nothing
4688−defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4689−defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4690− snapRestoreWaitForCompletion = False
4691− , snapRestoreIndices = Nothing
4692− , snapRestoreIgnoreUnavailable = False
4693− , snapRestoreIncludeGlobalState = True
4694− , snapRestoreRenamePattern = Nothing
4695− , snapRestoreRenameReplacement = Nothing
4696− , snapRestorePartial = False
4697− , snapRestoreIncludeAliases = True
4698− , snapRestoreIndexSettingsOverrides = Nothing
4699− , snapRestoreIgnoreIndexSettings = Nothing
4703−-- | Index settings that can be overridden. The docs only mention you
4704−-- can update number of replicas, but there may be more. You
4705−-- definitely cannot override shard count.
4706−data RestoreIndexSettings = RestoreIndexSettings {
4707− restoreOverrideReplicas :: Maybe ReplicaCount
4708− } deriving (Show, Eq, Generic, Typeable)
4711−instance ToJSON RestoreIndexSettings where
4712− toJSON RestoreIndexSettings {..} = object prs
4714− prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
4717−instance FromJSON NodesInfo where
4718− parseJSON = withObject "NodesInfo" parse
4721− nodes <- o .: "nodes"
4722− infos <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4723− node <- parseJSON v
4724− parseNodeInfo (FullNodeId fullNID) node
4725− cn <- o .: "cluster_name"
4726− return (NodesInfo infos cn)
4728−instance FromJSON NodesStats where
4729− parseJSON = withObject "NodesStats" parse
4732− nodes <- o .: "nodes"
4733− stats <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4734− node <- parseJSON v
4735− parseNodeStats (FullNodeId fullNID) node
4736− cn <- o .: "cluster_name"
4737− return (NodesStats stats cn)
4739−instance FromJSON NodeBreakerStats where
4740− parseJSON = withObject "NodeBreakerStats" parse
4742− parse o = NodeBreakerStats <$> o .: "tripped"
4743− <*> o .: "overhead"
4744− <*> o .: "estimated_size_in_bytes"
4745− <*> o .: "limit_size_in_bytes"
4747−instance FromJSON NodeHTTPStats where
4748− parseJSON = withObject "NodeHTTPStats" parse
4750− parse o = NodeHTTPStats <$> o .: "total_opened"
4751− <*> o .: "current_open"
4753−instance FromJSON NodeTransportStats where
4754− parseJSON = withObject "NodeTransportStats" parse
4756− parse o = NodeTransportStats <$> o .: "tx_size_in_bytes"
4757− <*> o .: "tx_count"
4758− <*> o .: "rx_size_in_bytes"
4759− <*> o .: "rx_count"
4760− <*> o .: "server_open"
4762−instance FromJSON NodeFSStats where
4763− parseJSON = withObject "NodeFSStats" parse
4765− parse o = NodeFSStats <$> o .: "data"
4767− <*> (posixMS <$> o .: "timestamp")
4769−instance FromJSON NodeDataPathStats where
4770− parseJSON = withObject "NodeDataPathStats" parse
4773− NodeDataPathStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4774− <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4775− <*> o .:? "disk_io_size_in_bytes"
4776− <*> o .:? "disk_write_size_in_bytes"
4777− <*> o .:? "disk_read_size_in_bytes"
4778− <*> o .:? "disk_io_op"
4779− <*> o .:? "disk_writes"
4780− <*> o .:? "disk_reads"
4781− <*> o .: "available_in_bytes"
4782− <*> o .: "free_in_bytes"
4783− <*> o .: "total_in_bytes"
4789−newtype StringlyTypedDouble = StringlyTypedDouble { unStringlyTypedDouble :: Double }
4792−instance FromJSON StringlyTypedDouble where
4793− parseJSON = fmap StringlyTypedDouble . parseJSON . unStringlyTypeJSON
4796−instance FromJSON NodeFSTotalStats where
4797− parseJSON = withObject "NodeFSTotalStats" parse
4799− parse o = NodeFSTotalStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4800− <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4801− <*> o .:? "disk_io_size_in_bytes"
4802− <*> o .:? "disk_write_size_in_bytes"
4803− <*> o .:? "disk_read_size_in_bytes"
4804− <*> o .:? "disk_io_op"
4805− <*> o .:? "disk_writes"
4806− <*> o .:? "disk_reads"
4807− <*> o .: "available_in_bytes"
4808− <*> o .: "free_in_bytes"
4809− <*> o .: "total_in_bytes"
4811−instance FromJSON NodeNetworkStats where
4812− parseJSON = withObject "NodeNetworkStats" parse
4816− NodeNetworkStats <$> tcp .: "out_rsts"
4817− <*> tcp .: "in_errs"
4818− <*> tcp .: "attempt_fails"
4819− <*> tcp .: "estab_resets"
4820− <*> tcp .: "retrans_segs"
4821− <*> tcp .: "out_segs"
4822− <*> tcp .: "in_segs"
4823− <*> tcp .: "curr_estab"
4824− <*> tcp .: "passive_opens"
4825− <*> tcp .: "active_opens"
4827−instance FromJSON NodeThreadPoolsStats where
4828− parseJSON = withObject "NodeThreadPoolsStats" parse
4830− parse o = NodeThreadPoolsStats <$> o .: "snapshot"
4834− <*> o .: "management"
4835− <*> o .:? "fetch_shard_store"
4836− <*> o .: "optimize"
4844− <*> o .:? "listener"
4845− <*> o .:? "fetch_shard_started"
4846− <*> o .: "percolate"
4847−instance FromJSON NodeThreadPoolStats where
4848− parseJSON = withObject "NodeThreadPoolStats" parse
4850− parse o = NodeThreadPoolStats <$> o .: "completed"
4852− <*> o .: "rejected"
4857−instance FromJSON NodeJVMStats where
4858− parseJSON = withObject "NodeJVMStats" parse
4861− bufferPools <- o .: "buffer_pools"
4862− mapped <- bufferPools .: "mapped"
4863− direct <- bufferPools .: "direct"
4865− collectors <- gc .: "collectors"
4866− oldC <- collectors .: "old"
4867− youngC <- collectors .: "young"
4868− threads <- o .: "threads"
4870− pools <- mem .: "pools"
4871− oldM <- pools .: "old"
4872− survivorM <- pools .: "survivor"
4873− youngM <- pools .: "young"
4874− NodeJVMStats <$> pure mapped
4878− <*> threads .: "peak_count"
4879− <*> threads .: "count"
4883− <*> mem .: "non_heap_committed_in_bytes"
4884− <*> mem .: "non_heap_used_in_bytes"
4885− <*> mem .: "heap_max_in_bytes"
4886− <*> mem .: "heap_committed_in_bytes"
4887− <*> mem .: "heap_used_percent"
4888− <*> mem .: "heap_used_in_bytes"
4889− <*> (unMS <$> o .: "uptime_in_millis")
4890− <*> (posixMS <$> o .: "timestamp")
4892−instance FromJSON JVMBufferPoolStats where
4893− parseJSON = withObject "JVMBufferPoolStats" parse
4895− parse o = JVMBufferPoolStats <$> o .: "total_capacity_in_bytes"
4896− <*> o .: "used_in_bytes"
4899−instance FromJSON JVMGCStats where
4900− parseJSON = withObject "JVMGCStats" parse
4902− parse o = JVMGCStats <$> (unMS <$> o .: "collection_time_in_millis")
4903− <*> o .: "collection_count"
4905−instance FromJSON JVMPoolStats where
4906− parseJSON = withObject "JVMPoolStats" parse
4908− parse o = JVMPoolStats <$> o .: "peak_max_in_bytes"
4909− <*> o .: "peak_used_in_bytes"
4910− <*> o .: "max_in_bytes"
4911− <*> o .: "used_in_bytes"
4913−instance FromJSON NodeProcessStats where
4914− parseJSON = withObject "NodeProcessStats" parse
4919− NodeProcessStats <$> mem .: "total_virtual_in_bytes"
4920− <*> mem .: "share_in_bytes"
4921− <*> mem .: "resident_in_bytes"
4922− <*> (unMS <$> cpu .: "total_in_millis")
4923− <*> (unMS <$> cpu .: "user_in_millis")
4924− <*> (unMS <$> cpu .: "sys_in_millis")
4925− <*> cpu .: "percent"
4926− <*> o .: "open_file_descriptors"
4927− <*> (posixMS <$> o .: "timestamp")
4929−instance FromJSON NodeOSStats where
4930− parseJSON = withObject "NodeOSStats" parse
4933− swap <- o .: "swap"
4936− load <- o .:? "load_average"
4937− NodeOSStats <$> swap .: "free_in_bytes"
4938− <*> swap .: "used_in_bytes"
4939− <*> mem .: "actual_used_in_bytes"
4940− <*> mem .: "actual_free_in_bytes"
4941− <*> mem .: "used_percent"
4942− <*> mem .: "free_percent"
4943− <*> mem .: "used_in_bytes"
4944− <*> mem .: "free_in_bytes"
4945− <*> cpu .: "stolen"
4951− <*> (unMS <$> o .: "uptime_in_millis")
4952− <*> (posixMS <$> o .: "timestamp")
4954−instance FromJSON LoadAvgs where
4955− parseJSON = withArray "LoadAvgs" parse
4957− parse v = case V.toList v of
4958− [one, five, fifteen] -> LoadAvgs <$> parseJSON one
4960− <*> parseJSON fifteen
4961− _ -> fail "Expecting a triple of Doubles"
4963−instance FromJSON NodeIndicesStats where
4964− parseJSON = withObject "NodeIndicesStats" parse
4967− let (.::) mv k = case mv of
4968− Just v -> Just <$> v .: k
4969− Nothing -> pure Nothing
4970− mRecovery <- o .:? "recovery"
4971− mQueryCache <- o .:? "query_cache"
4972− suggest <- o .: "suggest"
4973− translog <- o .: "translog"
4974− segments <- o .: "segments"
4975− completion <- o .: "completion"
4976− percolate <- o .: "percolate"
4977− fielddata <- o .: "fielddata"
4978− idCache <- o .: "id_cache"
4979− filterCache <- o .: "filter_cache"
4980− warmer <- o .: "warmer"
4981− flush <- o .: "flush"
4982− refresh <- o .: "refresh"
4983− merges <- o .: "merges"
4984− search <- o .: "search"
4985− getStats <- o .: "get"
4986− indexing <- o .: "indexing"
4987− store <- o .: "store"
4988− docs <- o .: "docs"
4989− NodeIndicesStats <$> (fmap unMS <$> mRecovery .:: "throttle_time_in_millis")
4990− <*> mRecovery .:: "current_as_target"
4991− <*> mRecovery .:: "current_as_source"
4992− <*> mQueryCache .:: "miss_count"
4993− <*> mQueryCache .:: "hit_count"
4994− <*> mQueryCache .:: "evictions"
4995− <*> mQueryCache .:: "memory_size_in_bytes"
4996− <*> suggest .: "current"
4997− <*> (unMS <$> suggest .: "time_in_millis")
4998− <*> suggest .: "total"
4999− <*> translog .: "size_in_bytes"
5000− <*> translog .: "operations"
5001− <*> segments .:? "fixed_bit_set_memory_in_bytes"
5002− <*> segments .: "version_map_memory_in_bytes"
5003− <*> segments .:? "index_writer_max_memory_in_bytes"
5004− <*> segments .: "index_writer_memory_in_bytes"
5005− <*> segments .: "memory_in_bytes"
5006− <*> segments .: "count"
5007− <*> completion .: "size_in_bytes"
5008− <*> percolate .: "queries"
5009− <*> percolate .: "memory_size_in_bytes"
5010− <*> percolate .: "current"
5011− <*> (unMS <$> percolate .: "time_in_millis")
5012− <*> percolate .: "total"
5013− <*> fielddata .: "evictions"
5014− <*> fielddata .: "memory_size_in_bytes"
5015− <*> idCache .: "memory_size_in_bytes"
5016− <*> filterCache .: "evictions"
5017− <*> filterCache .: "memory_size_in_bytes"
5018− <*> (unMS <$> warmer .: "total_time_in_millis")
5019− <*> warmer .: "total"
5020− <*> warmer .: "current"
5021− <*> (unMS <$> flush .: "total_time_in_millis")
5022− <*> flush .: "total"
5023− <*> (unMS <$> refresh .: "total_time_in_millis")
5024− <*> refresh .: "total"
5025− <*> merges .: "total_size_in_bytes"
5026− <*> merges .: "total_docs"
5027− <*> (unMS <$> merges .: "total_time_in_millis")
5028− <*> merges .: "total"
5029− <*> merges .: "current_size_in_bytes"
5030− <*> merges .: "current_docs"
5031− <*> merges .: "current"
5032− <*> search .: "fetch_current"
5033− <*> (unMS <$> search .: "fetch_time_in_millis")
5034− <*> search .: "fetch_total"
5035− <*> search .: "query_current"
5036− <*> (unMS <$> search .: "query_time_in_millis")
5037− <*> search .: "query_total"
5038− <*> search .: "open_contexts"
5039− <*> getStats .: "current"
5040− <*> (unMS <$> getStats .: "missing_time_in_millis")
5041− <*> getStats .: "missing_total"
5042− <*> (unMS <$> getStats .: "exists_time_in_millis")
5043− <*> getStats .: "exists_total"
5044− <*> (unMS <$> getStats .: "time_in_millis")
5045− <*> getStats .: "total"
5046− <*> (fmap unMS <$> indexing .:? "throttle_time_in_millis")
5047− <*> indexing .:? "is_throttled"
5048− <*> indexing .:? "noop_update_total"
5049− <*> indexing .: "delete_current"
5050− <*> (unMS <$> indexing .: "delete_time_in_millis")
5051− <*> indexing .: "delete_total"
5052− <*> indexing .: "index_current"
5053− <*> (unMS <$> indexing .: "index_time_in_millis")
5054− <*> indexing .: "index_total"
5055− <*> (unMS <$> store .: "throttle_time_in_millis")
5056− <*> store .: "size_in_bytes"
5057− <*> docs .: "deleted"
5058− <*> docs .: "count"
5060−instance FromJSON NodeBreakersStats where
5061− parseJSON = withObject "NodeBreakersStats" parse
5063− parse o = NodeBreakersStats <$> o .: "parent"
5065− <*> o .: "fielddata"
5067−parseNodeStats :: FullNodeId -> Object -> Parser NodeStats
5068−parseNodeStats fnid o = do
5069− NodeStats <$> o .: "name"
5071− <*> o .:? "breakers"
5073− <*> o .: "transport"
5076− <*> o .: "thread_pool"
5082−parseNodeInfo :: FullNodeId -> Object -> Parser NodeInfo
5083−parseNodeInfo nid o =
5084− NodeInfo <$> o .: "http_address"
5089− <*> o .: "transport_address"
5094− <*> o .: "transport"
5096− <*> o .: "thread_pool"
5100− <*> o .: "settings"
5102−instance FromJSON NodePluginInfo where
5103− parseJSON = withObject "NodePluginInfo" parse
5105− parse o = NodePluginInfo <$> o .: "site"
5107− <*> o .: "description"
5111−instance FromJSON NodeHTTPInfo where
5112− parseJSON = withObject "NodeHTTPInfo" parse
5114− parse o = NodeHTTPInfo <$> o .: "max_content_length_in_bytes"
5115− <*> parseJSON (Object o)
5117−instance FromJSON BoundTransportAddress where
5118− parseJSON = withObject "BoundTransportAddress" parse
5120− parse o = BoundTransportAddress <$> o .: "publish_address"
5121− <*> o .: "bound_address"
5123−instance FromJSON NodeOSInfo where
5124− parseJSON = withObject "NodeOSInfo" parse
5127− swap <- o .: "swap"
5129− NodeOSInfo <$> swap .: "total_in_bytes"
5130− <*> mem .: "total_in_bytes"
5132− <*> o .: "available_processors"
5133− <*> (unMS <$> o .: "refresh_interval_in_millis")
5136−instance FromJSON CPUInfo where
5137− parseJSON = withObject "CPUInfo" parse
5139− parse o = CPUInfo <$> o .: "cache_size_in_bytes"
5140− <*> o .: "cores_per_socket"
5141− <*> o .: "total_sockets"
5142− <*> o .: "total_cores"
5147−instance FromJSON NodeProcessInfo where
5148− parseJSON = withObject "NodeProcessInfo" parse
5150− parse o = NodeProcessInfo <$> o .: "mlockall"
5151− <*> o .: "max_file_descriptors"
5153− <*> (unMS <$> o .: "refresh_interval_in_millis")
5155−instance FromJSON NodeJVMInfo where
5156− parseJSON = withObject "NodeJVMInfo" parse
5158− parse o = NodeJVMInfo <$> o .: "memory_pools"
5159− <*> o .: "gc_collectors"
5161− <*> (posixMS <$> o .: "start_time_in_millis")
5162− <*> o .: "vm_vendor"
5163− <*> o .: "vm_version"
5165− <*> (unJVMVersion <$> o .: "version")
5168−instance FromJSON JVMVersion where
5169− parseJSON (String t) =
5170− JVMVersion <$> parseJSON (String (T.replace "_" "." t))
5171− parseJSON v = JVMVersion <$> parseJSON v
5173−instance FromJSON JVMMemoryInfo where
5174− parseJSON = withObject "JVMMemoryInfo" parse
5176− parse o = JVMMemoryInfo <$> o .: "direct_max_in_bytes"
5177− <*> o .: "non_heap_max_in_bytes"
5178− <*> o .: "non_heap_init_in_bytes"
5179− <*> o .: "heap_max_in_bytes"
5180− <*> o .: "heap_init_in_bytes"
5182−instance FromJSON NodeThreadPoolsInfo where
5183− parseJSON = withObject "NodeThreadPoolsInfo" parse
5185− parse o = NodeThreadPoolsInfo <$> o .: "refresh"
5186− <*> o .: "management"
5187− <*> o .: "percolate"
5188− <*> o .:? "listener"
5189− <*> o .:? "fetch_shard_started"
5193− <*> o .: "optimize"
5197− <*> o .: "snapshot"
5199− <*> o .:? "fetch_shard_store"
5203−instance FromJSON NodeThreadPoolInfo where
5204− parseJSON = withObject "NodeThreadPoolInfo" parse
5207− ka <- maybe (return Nothing) (fmap Just . parseStringInterval) =<< o .:? "keep_alive"
5208− NodeThreadPoolInfo <$> (parseJSON . unStringlyTypeJSON =<< o .: "queue_size")
5214−parseStringInterval :: (Monad m) => String -> m NominalDiffTime
5215−parseStringInterval s = case span isNumber s of
5216− ("", _) -> fail "Invalid interval"
5217− (nS, unitS) -> case (readMay nS, readMay unitS) of
5218− (Just n, Just unit) -> return (fromInteger (n * unitNDT unit))
5219− (Nothing, _) -> fail "Invalid interval number"
5220− (_, Nothing) -> fail "Invalid interval unit"
5222− unitNDT Seconds = 1
5223− unitNDT Minutes = 60
5224− unitNDT Hours = 60 * 60
5225− unitNDT Days = 24 * 60 * 60
5226− unitNDT Weeks = 7 * 24 * 60 * 60
5228−instance FromJSON ThreadPoolSize where
5229− parseJSON v = parseAsNumber v <|> parseAsString v
5231− parseAsNumber = parseAsInt <=< parseJSON
5232− parseAsInt (-1) = return ThreadPoolUnbounded
5234− | n >= 0 = return (ThreadPoolBounded n)
5235− | otherwise = fail "Thread pool size must be >= -1."
5236− parseAsString = withText "ThreadPoolSize" $ \t ->
5237− case first (readMay . T.unpack) (T.span isNumber t) of
5238− (Just n, "k") -> return (ThreadPoolBounded (n * 1000))
5239− (Just n, "") -> return (ThreadPoolBounded n)
5240− _ -> fail ("Invalid thread pool size " <> T.unpack t)
5242−instance FromJSON ThreadPoolType where
5243− parseJSON = withText "ThreadPoolType" parse
5245− parse "scaling" = return ThreadPoolScaling
5246− parse "fixed" = return ThreadPoolFixed
5247− parse "cached" = return ThreadPoolCached
5248− parse e = fail ("Unexpected thread pool type" <> T.unpack e)
5250−instance FromJSON NodeTransportInfo where
5251− parseJSON = withObject "NodeTransportInfo" parse
5253− parse o = NodeTransportInfo <$> (maybe (return mempty) parseProfiles =<< o .:? "profiles")
5254− <*> parseJSON (Object o)
5255− parseProfiles (Object o) | HM.null o = return []
5256− parseProfiles v@(Array _) = parseJSON v
5257− parseProfiles Null = return []
5258− parseProfiles _ = fail "Could not parse profiles"
5260−instance FromJSON NodeNetworkInfo where
5261− parseJSON = withObject "NodeNetworkInfo" parse
5263− parse o = NodeNetworkInfo <$> o .: "primary_interface"
5264− <*> (unMS <$> o .: "refresh_interval_in_millis")
5267−instance FromJSON NodeNetworkInterface where
5268− parseJSON = withObject "NodeNetworkInterface" parse
5270− parse o = NodeNetworkInterface <$> o .: "mac_address"
5274−newtype MaybeNA a = MaybeNA { unMaybeNA :: Maybe a }
5275− deriving (Show, Eq)
5277−instance FromJSON a => FromJSON (MaybeNA a) where
5278− parseJSON (String "NA") = pure $ MaybeNA Nothing
5279− parseJSON o = MaybeNA . Just <$> parseJSON o