@@ -1,10 +1,7 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveGeneric #-}
31{-# LANGUAGE FlexibleContexts #-}
42{-# LANGUAGE FlexibleInstances #-}
53{-# LANGUAGE GeneralizedNewtypeDeriving #-}
64{-# LANGUAGE MultiParamTypeClasses #-}
7−-- {-# LANGUAGE NoMonomorphismRestriction #-}
85{-# LANGUAGE NamedFieldPuns #-}
96{-# LANGUAGE OverloadedStrings #-}
107{-# LANGUAGE RecordWildCards #-}
@@ -13,11 +10,11 @@
1310-------------------------------------------------------------------------------
1411-- |
1512-- Module : Database.Bloodhound.Types
16−-- Copyright : (C) 2014, 2015, 2016 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
1714-- License : BSD-style (see the file LICENSE)
1815-- Maintainer : Chris Allen <cma@bitemyapp.com
1916-- Stability : provisional
20−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
2118--
2219-- Data types for describing actions and data structures performed to interact
2320-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -45,11 +42,15 @@ module Database.Bloodhound.Types
4542 , mkTermsAggregation
4643 , mkTermsScriptAggregation
4744 , mkDateHistogram
45+ , mkCardinalityAggregation
4846 , mkDocVersion
47+ , mkStatsAggregation
48+ , mkExtendedStatsAggregation
4949 , docVersionNumber
5050 , toMissing
5151 , toTerms
5252 , toDateHistogram
53+ , toTopHits
5354 , omitNulls
5455 , BH(..)
5556 , runBH
@@ -61,6 +62,7 @@ module Database.Bloodhound.Types
6162 , MonadBH(..)
6263 , Version(..)
6364 , VersionNumber(..)
65+ , MaybeNA(..)
6466 , BuildHash(..)
6567 , Status(..)
6668 , Existence(..)
@@ -69,6 +71,7 @@ module Database.Bloodhound.Types
6971 , UpdatableIndexSetting(..)
7072 , IndexSettingsSummary(..)
7173 , AllocationPolicy(..)
74+ , Compression(..)
7275 , ReplicaBounds(..)
7376 , Bytes(..)
7477 , gigabytes
@@ -117,8 +120,8 @@ module Database.Bloodhound.Types
117120 , Pattern(..)
118121 , ShardResult(..)
119122 , Hit(..)
123+ , HitFields(..)
120124 , Filter(..)
121− , Seminearring(..)
122125 , BoolMatch(..)
123126 , Term(..)
124127 , GeoPoint(..)
@@ -145,11 +148,22 @@ module Database.Bloodhound.Types
145148 , RegexpFlags(..)
146149 , RegexpFlag(..)
147150 , FieldName(..)
151+ , ScriptFields(..)
152+ , ScriptFieldName
153+ , ScriptFieldValue
148154 , Script(..)
155+ , ScriptLanguage(..)
156+ , ScriptInline(..)
157+ , ScriptId(..)
158+ , ScriptParams(..)
159+ , ScriptParamName
160+ , ScriptParamValue
149161 , IndexName(..)
150162 , IndexSelection(..)
151− , IndexOptimizationSettings(..)
152− , defaultIndexOptimizationSettings
163+ , NodeSelection(..)
164+ , NodeSelector(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
153167 , TemplateName(..)
154168 , TemplatePattern(..)
155169 , MappingName(..)
@@ -173,8 +187,19 @@ module Database.Bloodhound.Types
173187 , BoolQuery(..)
174188 , BoostingQuery(..)
175189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
191+ , BoostMode(..)
192+ , ScoreMode(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
196+ , Weight(..)
197+ , Seed(..)
198+ , FieldValueFactor(..)
199+ , Factor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
176202 , DisMaxQuery(..)
177− , FilteredQuery(..)
178203 , FuzzyLikeThisQuery(..)
179204 , FuzzyLikeFieldQuery(..)
180205 , FuzzyQuery(..)
@@ -190,10 +215,16 @@ module Database.Bloodhound.Types
190215 , RangeQuery(..)
191216 , RegexpQuery(..)
192217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
220+ , WildcardQuery(..)
193221 , BooleanOperator(..)
194222 , ZeroTermsQuery(..)
195223 , CutoffFrequency(..)
196224 , Analyzer(..)
225+ , Tokenizer(..)
226+ , TokenFilter(..)
227+ , CharFilter(..)
197228 , MaxExpansions(..)
198229 , Lenient(..)
199230 , MatchQueryType(..)
@@ -256,6 +287,26 @@ module Database.Bloodhound.Types
256287 , NodeName(..)
257288 , ClusterName(..)
258289 , NodesInfo(..)
290+ , NodesStats(..)
291+ , NodeStats(..)
292+ , NodeBreakersStats(..)
293+ , NodeBreakerStats(..)
294+ , NodeHTTPStats(..)
295+ , NodeTransportStats(..)
296+ , NodeFSStats(..)
297+ , NodeDataPathStats(..)
298+ , NodeFSTotalStats(..)
299+ , NodeNetworkStats(..)
300+ , NodeThreadPoolsStats(..)
301+ , NodeThreadPoolStats(..)
302+ , NodeJVMStats(..)
303+ , JVMBufferPoolStats(..)
304+ , JVMGCStats(..)
305+ , JVMPoolStats(..)
306+ , NodeProcessStats(..)
307+ , NodeOSStats(..)
308+ , LoadAvgs(..)
309+ , NodeIndicesStats(..)
259310 , EsAddress(..)
260311 , PluginName(..)
261312 , NodeInfo(..)
@@ -297,6 +348,18 @@ module Database.Bloodhound.Types
297348 , rrGroupRefNum
298349 , mkRRGroupRefNum
299350 , RestoreIndexSettings(..)
351+ , Suggest(..)
352+ , SuggestType(..)
353+ , PhraseSuggester(..)
354+ , PhraseSuggesterHighlighter(..)
355+ , PhraseSuggesterCollate(..)
356+ , mkPhraseSuggester
357+ , SuggestOptions(..)
358+ , SuggestResponse(..)
359+ , NamedSuggestionResponse(..)
360+ , DirectGenerators(..)
361+ , mkDirectGenerators
362+ , DirectGeneratorSuggestModeTypes (..)
300363
301364 , Aggregation(..)
302365 , Aggregations
@@ -308,6 +371,8 @@ module Database.Bloodhound.Types
308371 , MissingAggregation(..)
309372 , ValueCountAggregation(..)
310373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
311376 , DateHistogramAggregation(..)
312377 , DateRangeAggregation(..)
313378 , DateRangeAggRange(..)
@@ -315,6 +380,9 @@ module Database.Bloodhound.Types
315380 , DateMathAnchor(..)
316381 , DateMathModifier(..)
317382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
385+ , SearchAfterKey
318386
319387 , Highlights(..)
320388 , FieldHighlight(..)
@@ -332,704 +400,32 @@ module Database.Bloodhound.Types
332400 , TermsResult(..)
333401 , DateHistogramResult(..)
334402 , DateRangeResult(..)
403+ , TopHitResult(..)
335404
336405 , EsUsername(..)
337406 , EsPassword(..)
338− ) where
339407
340−import Control.Applicative as A
341−import Control.Monad.Catch
342−import Control.Monad.Except
343−import Control.Monad.Reader
344−import Control.Monad.State
345−import Control.Monad.Writer
346−import Data.Aeson
347−import Data.Aeson.Types (Pair, Parser, emptyObject,
348− parseEither, parseMaybe)
349−import qualified Data.ByteString.Lazy.Char8 as L
350−import Data.Char
351−import Data.Hashable (Hashable)
352−import qualified Data.HashMap.Strict as HM
353−import Data.List (foldl', intercalate, nub)
354−import Data.List.NonEmpty (NonEmpty (..), toList)
355−import qualified Data.Map.Strict as M
356−import Data.Maybe
357−import Data.Scientific (Scientific)
358−import Data.Text (Text)
359−import qualified Data.Text as T
360−import Data.Time.Calendar
361−import Data.Time.Clock (NominalDiffTime, UTCTime)
362−import Data.Time.Clock.POSIX
363−import qualified Data.Traversable as DT
364−import Data.Typeable (Typeable)
365−import qualified Data.Vector as V
366−import qualified Data.Version as Vers
367−import GHC.Enum
368−import GHC.Generics (Generic)
369−import Network.HTTP.Client
370−import qualified Network.HTTP.Types.Method as NHTM
371−import qualified Text.ParserCombinators.ReadP as RP
372−import qualified Text.Read as TR
373−
374−import Database.Bloodhound.Types.Class
375−import Database.Bloodhound.Types.Internal
376−
377−-- $setup
378−-- >>> :set -XOverloadedStrings
379−-- >>> import Data.Aeson
380−-- >>> import Database.Bloodhound
381−-- >>> let testServer = (Server "http://localhost:9200")
382−-- >>> let testIndex = IndexName "twitter"
383−-- >>> let testMapping = MappingName "tweet"
384−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
385−
386−-- defaultIndexSettings is exported by Database.Bloodhound as well
387−-- no trailing slashes in servers, library handles building the path.
388−
389−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
390−-- will be a noop. You can use the exported fields to customize it further, e.g.:
391−--
392−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
393−mkBHEnv :: Server -> Manager -> BHEnv
394−mkBHEnv s m = BHEnv s m return
395−
396−newtype BH m a = BH {
397− unBH :: ReaderT BHEnv m a
398− } deriving ( Functor
399− , A.Applicative
400− , Monad
401− , MonadIO
402− , MonadState s
403− , MonadWriter w
404− , MonadError e
405− , Alternative
406− , MonadPlus
407− , MonadFix
408− , MonadThrow
409− , MonadCatch
410− , MonadMask)
411−
412−instance MonadTrans BH where
413− lift = BH . lift
414−
415−instance (MonadReader r m) => MonadReader r (BH m) where
416− ask = lift ask
417− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
418− local f (m r)
419−
420−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
421− getBHEnv = BH getBHEnv
422−
423−runBH :: BHEnv -> BH m a -> m a
424−runBH e f = runReaderT (unBH f) e
425−
426−{-| 'Version' is embedded in 'Status' -}
427−data Version = Version { number :: VersionNumber
428− , build_hash :: BuildHash
429− , build_timestamp :: UTCTime
430− , build_snapshot :: Bool
431− , lucene_version :: VersionNumber } deriving (Eq, Read, Show, Generic, Typeable)
432−
433−-- | Traditional software versioning number
434−newtype VersionNumber = VersionNumber { versionNumber :: Vers.Version
435− } deriving (Eq, Read, Show, Generic, Typeable, Ord)
436−
437−{-| 'Status' is a data type for describing the JSON body returned by
438− Elasticsearch when you query its status. This was deprecated in 1.2.0.
439−
440− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
441−-}
442−
443−data Status = Status { ok :: Maybe Bool
444− , status :: Int
445− , name :: Text
446− , version :: Version
447− , tagline :: Text } deriving (Eq, Read, Show, Generic)
448−
449−{-| 'IndexSettings' is used to configure the shards and replicas when you create
450− an Elasticsearch Index.
451−
452− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
453−-}
454−
455−data IndexSettings =
456− IndexSettings { indexShards :: ShardCount
457− , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
458−
459−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
460−defaultIndexSettings :: IndexSettings
461−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
462−
463−
464−{-| 'IndexOptimizationSettings' is used to configure index optimization. See
465− <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html>
466− for more info.
467−-}
468−data IndexOptimizationSettings =
469− IndexOptimizationSettings { maxNumSegments :: Maybe Int
470− -- ^ 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.
471− , onlyExpungeDeletes :: Bool
472− -- ^ 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.
473− , flushAfterOptimize :: Bool
474− -- ^ Should a flush be performed after the optimize.
475− } deriving (Eq, Show, Generic, Typeable)
476−
477−
478−{-| 'defaultIndexOptimizationSettings' implements the default settings that
479− ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
480− 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
481−-}
482−defaultIndexOptimizationSettings :: IndexOptimizationSettings
483−defaultIndexOptimizationSettings = IndexOptimizationSettings Nothing False True
484−
485−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
486−
487− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
488−-}
489−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
490− -- ^ The number of replicas each shard has.
491− | AutoExpandReplicas ReplicaBounds
492− | BlocksReadOnly Bool
493− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
494− | BlocksRead Bool
495− -- ^ Set to True to disable read operations against the index.
496− | BlocksWrite Bool
497− -- ^ Set to True to disable write operations against the index.
498− | BlocksMetaData Bool
499− -- ^ Set to True to disable metadata operations against the index.
500− | RefreshInterval NominalDiffTime
501− -- ^ The async refresh interval of a shard
502− | IndexConcurrency Int
503− | FailOnMergeFailure Bool
504− | TranslogFlushThresholdOps Int
505− -- ^ When to flush on operations.
506− | TranslogFlushThresholdSize Bytes
507− -- ^ When to flush based on translog (bytes) size.
508− | TranslogFlushThresholdPeriod NominalDiffTime
509− -- ^ When to flush based on a period of not flushing.
510− | TranslogDisableFlush Bool
511− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
512− | CacheFilterMaxSize (Maybe Bytes)
513− -- ^ The maximum size of filter cache (per segment in shard).
514− | CacheFilterExpire (Maybe NominalDiffTime)
515− -- ^ The expire after access time for filter cache.
516− | GatewaySnapshotInterval NominalDiffTime
517− -- ^ The gateway snapshot interval (only applies to shared gateways).
518− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
519− -- ^ A node matching any rule will be allowed to host shards from the index.
520− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
521− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
522− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
523− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
524− | RoutingAllocationEnable AllocationPolicy
525− -- ^ Enables shard allocation for a specific index.
526− | RoutingAllocationShardsPerNode ShardCount
527− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
528− | RecoveryInitialShards InitialShardCount
529− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
530− | GCDeletes NominalDiffTime
531− | TTLDisablePurge Bool
532− -- ^ Disables temporarily the purge of expired docs.
533− | TranslogFSType FSType
534− | IndexCompoundFormat CompoundFormat
535− | IndexCompoundOnFlush Bool
536− | WarmerEnabled Bool
537− deriving (Eq, Show, Generic, Typeable)
538−
539−data AllocationPolicy = AllocAll
540− -- ^ Allows shard allocation for all shards.
541− | AllocPrimaries
542− -- ^ Allows shard allocation only for primary shards.
543− | AllocNewPrimaries
544− -- ^ Allows shard allocation only for primary shards for new indices.
545− | AllocNone
546− -- ^ No shard allocation is allowed
547− deriving (Eq, Read, Show, Generic, Typeable)
548−
549−data ReplicaBounds = ReplicasBounded Int Int
550− | ReplicasLowerBounded Int
551− | ReplicasUnbounded
552− deriving (Eq, Read, Show, Generic, Typeable)
553−
554−-- | A measure of bytes used for various configurations. You may want
555−-- to use smart constructors like 'gigabytes' for larger values.
556−--
557−-- >>> gigabytes 9
558−-- Bytes 9000000000
559−--
560−-- >>> megabytes 9
561−-- Bytes 9000000
562−--
563−-- >>> kilobytes 9
564−-- Bytes 9000
565−newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
566−
567−gigabytes :: Int -> Bytes
568−gigabytes n = megabytes (1000 * n)
569−
570−
571−megabytes :: Int -> Bytes
572−megabytes n = kilobytes (1000 * n)
573−
574−
575−kilobytes :: Int -> Bytes
576−kilobytes n = Bytes (1000 * n)
577−
578−
579−data FSType = FSSimple
580− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
581−
582−data InitialShardCount = QuorumShards
583− | QuorumMinus1Shards
584− | FullShards
585− | FullMinus1Shards
586− | ExplicitShards Int
587− deriving (Eq, Read, Show, Generic, Typeable)
588−
589−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
590− , nodeAttrFilterValues :: NonEmpty Text}
591− deriving (Eq, Read, Show, Generic, Ord)
592−
593−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
594−
595−data CompoundFormat = CompoundFileFormat Bool
596− | MergeSegmentVsTotalIndex Double
597− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
598− deriving (Eq, Read, Show, Generic, Typeable)
599−
600−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
601−
602−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
603− , sSummaryFixedSettings :: IndexSettings
604− , sSummaryUpdateable :: [UpdatableIndexSetting]}
605− deriving (Eq, Show, Generic, Typeable)
606−
607−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
608−type Reply = Network.HTTP.Client.Response L.ByteString
609−type Method = NHTM.Method
610−
611−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
612−
613− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
614−-}
615−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
616−
617−data FieldType = GeoPointType
618− | GeoShapeType
619− | FloatType
620− | IntegerType
621− | LongType
622− | ShortType
623− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
624−
625−data FieldDefinition =
626− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
627−
628−{-| An 'IndexTemplate' defines a template that will automatically be
629− applied to new indices created. The templates include both
630− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
631− controls if the template will be applied to the index created.
632− Specify mappings as follows: @[toJSON TweetMapping, ...]@
633−
634− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
635−-}
636−data IndexTemplate =
637− IndexTemplate { templatePattern :: TemplatePattern
638− , templateSettings :: Maybe IndexSettings
639− , templateMappings :: [Value]
640− }
641−
642−data MappingField =
643− MappingField { mappingFieldName :: FieldName
644− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
645−
646−{-| Support for type reification of 'Mapping's is currently incomplete, for
647− now the mapping API verbiage expects a 'ToJSON'able blob.
648−
649− Indexes have mappings, mappings are schemas for the documents contained in the
650− index. I'd recommend having only one mapping per index, always having a mapping,
651− and keeping different kinds of documents separated if possible.
652−-}
653−data Mapping = Mapping { typeName :: TypeName
654− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
655−
656−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
657− operation index, create, delete, and update. 'BulkIndex' behaves like an
658− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
659−
660− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
661−-}
662−data BulkOperation =
663− BulkIndex IndexName MappingName DocId Value
664− | BulkCreate IndexName MappingName DocId Value
665− | BulkDelete IndexName MappingName DocId
666− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
667−
668−{-| 'EsResult' describes the standard wrapper JSON document that you see in
669− successful Elasticsearch lookups or lookups that couldn't find the document.
670−-}
671−data EsResult a = EsResult { _index :: Text
672− , _type :: Text
673− , _id :: Text
674− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
675−
676−{-| 'EsResultFound' contains the document and its metadata inside of an
677− 'EsResult' when the document was successfully found.
678−-}
679−data EsResultFound a = EsResultFound { _version :: DocVersion
680− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
681−
682−{-| 'EsError' is the generic type that will be returned when there was a
683− problem. If you can't parse the expected response, its a good idea to
684− try parsing this.
685−-}
686−data EsError = EsError { errorStatus :: Int
687− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
688−
689−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
690−returned by the ElasticSearch server. If you encounter this error, please
691−verify that your domain data types and FromJSON instances are working properly
692−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
693−sure that your mappings are correct, then this error may be an indication of an
694−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
695−and be sure to include the exception body.
696−-}
697−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
698− deriving (Eq, Read, Show, Generic, Typeable)
699−
700−instance Exception EsProtocolException
701−
702−data IndexAlias = IndexAlias { srcIndex :: IndexName
703− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
704−
705−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
706−
707−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
708− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
709−
710−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
711− , aliasCreateFilter :: Maybe Filter}
712− deriving (Read, Show, Eq, Generic, Typeable)
713−
714−data AliasRouting = AllAliasRouting RoutingValue
715− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
716− deriving (Read, Show, Eq, Generic, Typeable)
717−
718−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
719−
720−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
721−
722−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
723−
724−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
725−
726−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
727−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
728− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
729−
730−{-| 'DocVersion' is an integer version number for a document between 1
731−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
732−-}
733−newtype DocVersion = DocVersion {
734− docVersionNumber :: Int
735− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
736−
737−-- | Smart constructor for in-range doc version
738−mkDocVersion :: Int -> Maybe DocVersion
739−mkDocVersion i
740− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
741− Just $ DocVersion i
742− | otherwise = Nothing
743−
744−
745−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
746−own version numbers instead of ones from ES.
747−-}
748−newtype ExternalDocVersion = ExternalDocVersion DocVersion
749− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
750−
751−{-| 'VersionControl' is specified when indexing documents as a
752−optimistic concurrency control.
753−-}
754−data VersionControl = NoVersionControl
755− -- ^ Don't send a version. This is a pure overwrite.
756− | InternalVersion DocVersion
757− -- ^ Use the default ES versioning scheme. Only
758− -- index the document if the version is the same
759− -- as the one specified. Only applicable to
760− -- updates, as you should be getting Version from
761− -- a search result.
762− | ExternalGT ExternalDocVersion
763− -- ^ Use your own version numbering. Only index
764− -- the document if the version is strictly higher
765− -- OR the document doesn't exist. The given
766− -- version will be used as the new version number
767− -- for the stored document. N.B. All updates must
768− -- increment this number, meaning there is some
769− -- global, external ordering of updates.
770− | ExternalGTE ExternalDocVersion
771− -- ^ Use your own version numbering. Only index
772− -- the document if the version is equal or higher
773− -- than the stored version. Will succeed if there
774− -- is no existing document. The given version will
775− -- be used as the new version number for the
776− -- stored document. Use with care, as this could
777− -- result in data loss.
778− | ForceVersion ExternalDocVersion
779− -- ^ The document will always be indexed and the
780− -- given version will be the new version. This is
781− -- typically used for correcting errors. Use with
782− -- care, as this could result in data loss.
783− deriving (Read, Show, Eq, Generic, Ord)
784−
785−{-| 'DocumentParent' is used to specify a parent document.
786−-}
787−newtype DocumentParent = DocumentParent DocId
788− deriving (Eq, Read, Show, Generic, Typeable)
789−
790−{-| 'IndexDocumentSettings' are special settings supplied when indexing
791−a document. For the best backwards compatiblity when new fields are
792−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
793−-}
794−data IndexDocumentSettings =
795− IndexDocumentSettings { idsVersionControl :: VersionControl
796− , idsParent :: Maybe DocumentParent
797− } deriving (Eq, Read, Show, Generic, Typeable)
798−
799−{-| Reasonable default settings. Chooses no version control and no parent.
800−-}
801−defaultIndexDocumentSettings :: IndexDocumentSettings
802−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
803−
804−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
805− dependent with later sorts acting as tie-breakers for earlier sorts.
806−-}
807−type Sort = [SortSpec]
808−
809−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
810− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
811− 'DistanceUnit' to express "nearness" to a single geographical point as a
812− sort specification.
813−
814−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
815−-}
816−data SortSpec = DefaultSortSpec DefaultSort
817− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
818−
819−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
820− 'mkSort' convenience function for when you want to specify only the most
821− common parameters.
822−
823−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
824−-}
825−data DefaultSort =
826− DefaultSort { sortFieldName :: FieldName
827− , sortOrder :: SortOrder
828− -- default False
829− , ignoreUnmapped :: Bool
830− , sortMode :: Maybe SortMode
831− , missingSort :: Maybe Missing
832− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
833−
834−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
835− encoded into "asc" or "desc" when turned into JSON.
836−
837−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
838−-}
839−data SortOrder = Ascending
840− | Descending deriving (Eq, Read, Show, Generic, Typeable)
841−
842−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
843− sorted last, first, or using a custom value as a substitute.
844−
845−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
846−-}
847−data Missing = LastMissing
848− | FirstMissing
849− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
850−
851−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
852−
853−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
854−-}
855−data SortMode = SortMin
856− | SortMax
857− | SortSum
858− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
859−
860−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
861− that you can concisely describe the usual kind of 'SortSpec's you want.
862−-}
863−mkSort :: FieldName -> SortOrder -> DefaultSort
864−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
865−
866−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
867− 'Query's cannot be cached.
868−-}
869−type Cache = Bool -- caching on/off
870−defaultCache :: Cache
871−defaultCache = False
872−
873−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
874−-}
875−type PrefixValue = Text
876−
877−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
878− JSON encoding baked in. Used all over the place.
879−-}
880−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
881−
882−{-| 'ShardCount' is part of 'IndexSettings'
883−-}
884−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
885−
886−{-| 'ReplicaCount' is part of 'IndexSettings'
887−-}
888−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
889−
890−{-| 'IndexName' is used to describe which index to query/create/delete
891−-}
892−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
893−
894−{-| 'IndexSelection' is used for APIs which take a single index, a list of
895− indexes, or the special @_all@ index.
896−-}
897−--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.
898−data IndexSelection = IndexList (NonEmpty IndexName)
899− | AllIndexes deriving (Eq, Generic, Show, Typeable)
900−
901−{-| 'TemplateName' is used to describe which template to query/create/delete
902−-}
903−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
904−
905−{-| 'TemplatePattern' represents a pattern which is matched against index names
906−-}
907−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
908−
909−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
910− the data in the indices.
911−-}
912−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
913−
914−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
915− Can be set by the user or created by ES itself. Often used in client
916− functions for poking at specific documents.
917−-}
918−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
919−
920−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
921−-}
922−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
923−
924−{-| 'FieldName' is used all over the place wherever a specific field within
925− a document needs to be specified, usually in 'Query's or 'Filter's.
926−-}
927−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
928−
929−
930−{-| 'Script' is often used in place of 'FieldName' to specify more
931−complex ways of extracting a value from a document.
932−-}
933−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
934−
935−{-| 'CacheName' is used in 'RegexpFilter' for describing the
936− 'CacheKey' keyed caching behavior.
937−-}
938−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
939−
940−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
941−-}
942−newtype CacheKey =
943− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
944−newtype Existence =
945− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
946−newtype NullValue =
947− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
948−newtype CutoffFrequency =
949− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
950−newtype Analyzer =
951− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
952−newtype MaxExpansions =
953− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
954−
955−{-| 'Lenient', if set to true, will cause format based failures to be
956− ignored. I don't know what the bloody default is, Elasticsearch
957− documentation didn't say what it was. Let me know if you figure it out.
958−-}
959−newtype Lenient =
960− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
961−newtype Tiebreaker =
962− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
963−newtype Boost =
964− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
965−newtype BoostTerms =
966− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
967−
968−{-| 'MinimumMatch' controls how many should clauses in the bool query should
969− match. Can be an absolute value (2) or a percentage (30%) or a
970− combination of both.
971−-}
972−newtype MinimumMatch =
973− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
974−newtype DisableCoord =
975− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
976−newtype IgnoreTermFrequency =
977− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
978−newtype MinimumTermFrequency =
979− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
980−newtype MaxQueryTerms =
981− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
982−newtype Fuzziness =
983− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
984−
985−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
986−newtype PrefixLength =
987− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
988−newtype TypeName =
989− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
990−newtype PercentMatch =
991− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
992−newtype StopWord =
993− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
994−newtype QueryPath =
995− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
996−
997−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
998− heavy, because all terms in the index need to be examined, just in case
999− they match. Leading wildcards can be disabled by setting
1000− 'AllowLeadingWildcard' to false. -}
1001−newtype AllowLeadingWildcard =
1002− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1003−newtype LowercaseExpanded =
1004− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1005−newtype EnablePositionIncrements =
1006− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1007−
1008−{-| By default, wildcard terms in a query are not analyzed.
1009− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
1010−-}
1011−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1012−
1013−{-| 'GeneratePhraseQueries' defaults to false.
1014−-}
1015−newtype GeneratePhraseQueries =
1016− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1017−
1018−{-| 'Locale' is used for string conversions - defaults to ROOT.
1019−-}
1020−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1021−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1022−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1023−
1024−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
1025− phrase matches. Default is 0.
1026−-}
1027−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1028−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1029−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1030−
1031−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
1032−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
408+ , Analysis(..)
409+ , AnalyzerDefinition(..)
410+ , TokenizerDefinition(..)
411+ , TokenFilterDefinition(..)
412+ , CharFilterDefinition(..)
413+ , Ngram(..)
414+ , TokenChar(..)
415+ , Shingle(..)
416+ , Language(..)
417+ ) where
418+
419+import Bloodhound.Import
420+
421+import Database.Bloodhound.Internal.Aggregation
422+import Database.Bloodhound.Internal.Analysis
423+import Database.Bloodhound.Internal.Client
424+import Database.Bloodhound.Internal.Highlight
425+import Database.Bloodhound.Internal.Newtypes
426+import Database.Bloodhound.Internal.Query
427+import Database.Bloodhound.Internal.Sort
428+import Database.Bloodhound.Internal.Suggest
1033429
1034430{-| 'unpackId' is a silly convenience function that gets used once.
1035431-}
@@ -1037,8 +433,6 @@ unpackId :: DocId -> Text
1037433unpackId (DocId docId) = docId
1038434
1039435type TrackSortScores = Bool
1040−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1041−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON)
1042436
1043437data Search = Search { queryBody :: Maybe Query
1044438 , filterBody :: Maybe Filter
@@ -1050,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
1050444 , from :: From
1051445 , size :: Size
1052446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
1053448 , fields :: Maybe [FieldName]
1054− , source :: Maybe Source } deriving (Eq, Read, Show, Generic, Typeable)
449+ , scriptFields :: Maybe ScriptFields
450+ , source :: Maybe Source
451+ , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
452+ } deriving (Eq, Show)
453+
454+
455+instance ToJSON Search where
456+ toJSON (Search mquery sFilter sort searchAggs
457+ highlight sTrackSortScores sFrom sSize _ sAfter sFields
458+ sScriptFields sSource sSuggest) =
459+ omitNulls [ "query" .= query'
460+ , "sort" .= sort
461+ , "aggregations" .= searchAggs
462+ , "highlight" .= highlight
463+ , "from" .= sFrom
464+ , "size" .= sSize
465+ , "track_scores" .= sTrackSortScores
466+ , "search_after" .= sAfter
467+ , "fields" .= sFields
468+ , "script_fields" .= sScriptFields
469+ , "_source" .= sSource
470+ , "suggest" .= sSuggest]
471+
472+ where query' = case sFilter of
473+ Nothing -> mquery
474+ Just x ->
475+ Just
476+ . QueryBoolQuery
477+ $ mkBoolQuery (maybeToList mquery)
478+ [x] [] []
1055479
1056480data SearchType = SearchTypeQueryThenFetch
1057481 | SearchTypeDfsQueryThenFetch
1058− | SearchTypeCount
1059− | SearchTypeScan
1060− | SearchTypeQueryAndFetch
1061− | SearchTypeDfsQueryAndFetch
1062− deriving (Eq, Read, Show, Generic, Typeable)
482+ deriving (Eq, Show)
1063483
1064484data Source =
1065485 NoSource
1066486 | SourcePatterns PatternOrPatterns
1067487 | SourceIncludeExclude Include Exclude
1068− deriving (Read, Show, Eq, Generic, Typeable)
1069−
1070−data PatternOrPatterns = PopPattern Pattern
1071− | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1072−
1073−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1074−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1075−
1076−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
1077−
1078−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1079− , highlightFields :: [FieldHighlight]
1080− } deriving (Read, Show, Eq, Generic, Typeable)
1081−
1082−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1083− deriving (Read, Show, Eq, Generic, Typeable)
1084−
1085−
1086−data HighlightSettings = Plain PlainHighlight
1087− | Postings PostingsHighlight
1088− | FastVector FastVectorHighlight
1089− deriving (Read, Show, Eq, Generic, Typeable)
1090−data PlainHighlight =
1091− PlainHighlight { plainCommon :: Maybe CommonHighlight
1092− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
1093−
1094− -- This requires that index_options are set to 'offset' in the mapping.
1095−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
1096−
1097−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1098−data FastVectorHighlight =
1099− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
1100− , fvNonPostSettings :: Maybe NonPostings
1101− , boundaryChars :: Maybe Text
1102− , boundaryMaxScan :: Maybe Int
1103− , fragmentOffset :: Maybe Int
1104− , matchedFields :: [Text]
1105− , phraseLimit :: Maybe Int
1106− } deriving (Read, Show, Eq, Generic, Typeable)
1107−
1108−data CommonHighlight =
1109− CommonHighlight { order :: Maybe Text
1110− , forceSource :: Maybe Bool
1111− , tag :: Maybe HighlightTag
1112− , encoder :: Maybe HighlightEncoder
1113− , noMatchSize :: Maybe Int
1114− , highlightQuery :: Maybe Query
1115− , requireFieldMatch :: Maybe Bool
1116− } deriving (Read, Show, Eq, Generic, Typeable)
1117−
1118−-- Settings that are only applicable to FastVector and Plain highlighters.
1119−data NonPostings =
1120− NonPostings { fragmentSize :: Maybe Int
1121− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
1122−
1123−data HighlightEncoder = DefaultEncoder
1124− | HTMLEncoder
1125− deriving (Read, Show, Eq, Generic, Typeable)
1126−
1127−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1128−data HighlightTag = TagSchema Text
1129− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1130− deriving (Read, Show, Eq, Generic, Typeable)
1131−
1132−
1133−data Query =
1134− TermQuery Term (Maybe Boost)
1135− | TermsQuery Text (NonEmpty Text)
1136− | QueryMatchQuery MatchQuery
1137− | QueryMultiMatchQuery MultiMatchQuery
1138− | QueryBoolQuery BoolQuery
1139− | QueryBoostingQuery BoostingQuery
1140− | QueryCommonTermsQuery CommonTermsQuery
1141− | ConstantScoreFilter Filter Boost
1142− | ConstantScoreQuery Query Boost
1143− | QueryDisMaxQuery DisMaxQuery
1144− | QueryFilteredQuery FilteredQuery
1145− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1146− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1147− | QueryFuzzyQuery FuzzyQuery
1148− | QueryHasChildQuery HasChildQuery
1149− | QueryHasParentQuery HasParentQuery
1150− | IdsQuery MappingName [DocId]
1151− | QueryIndicesQuery IndicesQuery
1152− | MatchAllQuery (Maybe Boost)
1153− | QueryMoreLikeThisQuery MoreLikeThisQuery
1154− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1155− | QueryNestedQuery NestedQuery
1156− | QueryPrefixQuery PrefixQuery
1157− | QueryQueryStringQuery QueryStringQuery
1158− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1159− | QueryRangeQuery RangeQuery
1160− | QueryRegexpQuery RegexpQuery
1161− deriving (Eq, Read, Show, Generic, Typeable)
1162−
1163−data RegexpQuery =
1164− RegexpQuery { regexpQueryField :: FieldName
1165− , regexpQuery :: Regexp
1166− , regexpQueryFlags :: RegexpFlags
1167− , regexpQueryBoost :: Maybe Boost
1168− } deriving (Eq, Read, Show, Generic, Typeable)
1169−
1170−data RangeQuery =
1171− RangeQuery { rangeQueryField :: FieldName
1172− , rangeQueryRange :: RangeValue
1173− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1174−
1175−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1176−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1177−
1178−data SimpleQueryStringQuery =
1179− SimpleQueryStringQuery
1180− { simpleQueryStringQuery :: QueryString
1181− , simpleQueryStringField :: Maybe FieldOrFields
1182− , simpleQueryStringOperator :: Maybe BooleanOperator
1183− , simpleQueryStringAnalyzer :: Maybe Analyzer
1184− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1185− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1186− , simpleQueryStringLocale :: Maybe Locale
1187− } deriving (Eq, Read, Show, Generic, Typeable)
1188−
1189−data SimpleQueryFlag =
1190− SimpleQueryAll
1191− | SimpleQueryNone
1192− | SimpleQueryAnd
1193− | SimpleQueryOr
1194− | SimpleQueryPrefix
1195− | SimpleQueryPhrase
1196− | SimpleQueryPrecedence
1197− | SimpleQueryEscape
1198− | SimpleQueryWhitespace
1199− | SimpleQueryFuzzy
1200− | SimpleQueryNear
1201− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1202−
1203−-- use_dis_max and tie_breaker when fields are plural?
1204−data QueryStringQuery =
1205− QueryStringQuery
1206− { queryStringQuery :: QueryString
1207− , queryStringDefaultField :: Maybe FieldName
1208− , queryStringOperator :: Maybe BooleanOperator
1209− , queryStringAnalyzer :: Maybe Analyzer
1210− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1211− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1212− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1213− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1214− , queryStringFuzziness :: Maybe Fuzziness
1215− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1216− , queryStringPhraseSlop :: Maybe PhraseSlop
1217− , queryStringBoost :: Maybe Boost
1218− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1219− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1220− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1221− , queryStringLenient :: Maybe Lenient
1222− , queryStringLocale :: Maybe Locale
1223− } deriving (Eq, Read, Show, Generic, Typeable)
1224−
1225−mkQueryStringQuery :: QueryString -> QueryStringQuery
1226−mkQueryStringQuery qs =
1227− QueryStringQuery qs Nothing Nothing
1228− Nothing Nothing Nothing Nothing
1229− Nothing Nothing Nothing Nothing
1230− Nothing Nothing Nothing Nothing
1231− Nothing Nothing
1232−
1233−data FieldOrFields = FofField FieldName
1234− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
488+ deriving (Eq, Show)
1235489
1236−data PrefixQuery =
1237− PrefixQuery
1238− { prefixQueryField :: FieldName
1239− , prefixQueryPrefixValue :: Text
1240− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1241−
1242−data NestedQuery =
1243− NestedQuery
1244− { nestedQueryPath :: QueryPath
1245− , nestedQueryScoreType :: ScoreType
1246− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1247−
1248−data MoreLikeThisFieldQuery =
1249− MoreLikeThisFieldQuery
1250− { moreLikeThisFieldText :: Text
1251− , moreLikeThisFieldFields :: FieldName
1252− -- default 0.3 (30%)
1253− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1254− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1255− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1256− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1257− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1258− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1259− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1260− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1261− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1262− , moreLikeThisFieldBoost :: Maybe Boost
1263− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1264− } deriving (Eq, Read, Show, Generic, Typeable)
1265−
1266−data MoreLikeThisQuery =
1267− MoreLikeThisQuery
1268− { moreLikeThisText :: Text
1269− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1270− -- default 0.3 (30%)
1271− , moreLikeThisPercentMatch :: Maybe PercentMatch
1272− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1273− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1274− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1275− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1276− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1277− , moreLikeThisMinWordLength :: Maybe MinWordLength
1278− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1279− , moreLikeThisBoostTerms :: Maybe BoostTerms
1280− , moreLikeThisBoost :: Maybe Boost
1281− , moreLikeThisAnalyzer :: Maybe Analyzer
1282− } deriving (Eq, Read, Show, Generic, Typeable)
1283−
1284−data IndicesQuery =
1285− IndicesQuery
1286− { indicesQueryIndices :: [IndexName]
1287− , indicesQuery :: Query
1288− -- default "all"
1289− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1290−
1291−data HasParentQuery =
1292− HasParentQuery
1293− { hasParentQueryType :: TypeName
1294− , hasParentQuery :: Query
1295− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1296−
1297−data HasChildQuery =
1298− HasChildQuery
1299− { hasChildQueryType :: TypeName
1300− , hasChildQuery :: Query
1301− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1302−
1303−data ScoreType =
1304− ScoreTypeMax
1305− | ScoreTypeSum
1306− | ScoreTypeAvg
1307− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1308−
1309−data FuzzyQuery =
1310− FuzzyQuery { fuzzyQueryField :: FieldName
1311− , fuzzyQueryValue :: Text
1312− , fuzzyQueryPrefixLength :: PrefixLength
1313− , fuzzyQueryMaxExpansions :: MaxExpansions
1314− , fuzzyQueryFuzziness :: Fuzziness
1315− , fuzzyQueryBoost :: Maybe Boost
1316− } deriving (Eq, Read, Show, Generic, Typeable)
1317−
1318−data FuzzyLikeFieldQuery =
1319− FuzzyLikeFieldQuery
1320− { fuzzyLikeField :: FieldName
1321− -- anaphora is good for the soul.
1322− , fuzzyLikeFieldText :: Text
1323− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1324− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1325− , fuzzyLikeFieldFuzziness :: Fuzziness
1326− , fuzzyLikeFieldPrefixLength :: PrefixLength
1327− , fuzzyLikeFieldBoost :: Boost
1328− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1329− } deriving (Eq, Read, Show, Generic, Typeable)
1330−
1331−data FuzzyLikeThisQuery =
1332− FuzzyLikeThisQuery
1333− { fuzzyLikeFields :: [FieldName]
1334− , fuzzyLikeText :: Text
1335− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1336− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1337− , fuzzyLikeFuzziness :: Fuzziness
1338− , fuzzyLikePrefixLength :: PrefixLength
1339− , fuzzyLikeBoost :: Boost
1340− , fuzzyLikeAnalyzer :: Maybe Analyzer
1341− } deriving (Eq, Read, Show, Generic, Typeable)
1342−
1343−data FilteredQuery =
1344− FilteredQuery
1345− { filteredQuery :: Query
1346− , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1347−
1348−data DisMaxQuery =
1349− DisMaxQuery { disMaxQueries :: [Query]
1350− -- default 0.0
1351− , disMaxTiebreaker :: Tiebreaker
1352− , disMaxBoost :: Maybe Boost
1353− } deriving (Eq, Read, Show, Generic, Typeable)
1354−
1355−data MatchQuery =
1356− MatchQuery { matchQueryField :: FieldName
1357− , matchQueryQueryString :: QueryString
1358− , matchQueryOperator :: BooleanOperator
1359− , matchQueryZeroTerms :: ZeroTermsQuery
1360− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1361− , matchQueryMatchType :: Maybe MatchQueryType
1362− , matchQueryAnalyzer :: Maybe Analyzer
1363− , matchQueryMaxExpansions :: Maybe MaxExpansions
1364− , matchQueryLenient :: Maybe Lenient
1365− , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1366−
1367−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1368− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1369−-}
1370−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1371−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1372−
1373−data MatchQueryType =
1374− MatchPhrase
1375− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1376−
1377−data MultiMatchQuery =
1378− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1379− , multiMatchQueryString :: QueryString
1380− , multiMatchQueryOperator :: BooleanOperator
1381− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1382− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1383− , multiMatchQueryType :: Maybe MultiMatchQueryType
1384− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1385− , multiMatchQueryAnalyzer :: Maybe Analyzer
1386− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1387− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1388−
1389−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1390− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1391− make a 'MultiMatchQuery'.
1392−-}
1393−
1394−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1395−mkMultiMatchQuery matchFields query =
1396− MultiMatchQuery matchFields query
1397− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1398−
1399−data MultiMatchQueryType =
1400− MultiMatchBestFields
1401− | MultiMatchMostFields
1402− | MultiMatchCrossFields
1403− | MultiMatchPhrase
1404− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1405−
1406−data BoolQuery =
1407− BoolQuery { boolQueryMustMatch :: [Query]
1408− , boolQueryMustNotMatch :: [Query]
1409− , boolQueryShouldMatch :: [Query]
1410− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1411− , boolQueryBoost :: Maybe Boost
1412− , boolQueryDisableCoord :: Maybe DisableCoord
1413− } deriving (Eq, Read, Show, Generic, Typeable)
1414−
1415−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1416−mkBoolQuery must mustNot should =
1417− BoolQuery must mustNot should Nothing Nothing Nothing
1418−
1419−data BoostingQuery =
1420− BoostingQuery { positiveQuery :: Query
1421− , negativeQuery :: Query
1422− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1423−
1424−data CommonTermsQuery =
1425− CommonTermsQuery { commonField :: FieldName
1426− , commonQuery :: QueryString
1427− , commonCutoffFrequency :: CutoffFrequency
1428− , commonLowFreqOperator :: BooleanOperator
1429− , commonHighFreqOperator :: BooleanOperator
1430− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1431− , commonBoost :: Maybe Boost
1432− , commonAnalyzer :: Maybe Analyzer
1433− , commonDisableCoord :: Maybe DisableCoord
1434− } deriving (Eq, Read, Show, Generic, Typeable)
1435−
1436−data CommonMinimumMatch =
1437− CommonMinimumMatchHighLow MinimumMatchHighLow
1438− | CommonMinimumMatch MinimumMatch
1439− deriving (Eq, Read, Show, Generic, Typeable)
1440−
1441−data MinimumMatchHighLow =
1442− MinimumMatchHighLow { lowFreq :: MinimumMatch
1443− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1444−
1445−data Filter = AndFilter [Filter] Cache
1446− | OrFilter [Filter] Cache
1447− | NotFilter Filter Cache
1448− | IdentityFilter
1449− | BoolFilter BoolMatch
1450− | ExistsFilter FieldName -- always cached
1451− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1452− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1453− | GeoDistanceRangeFilter GeoPoint DistanceRange
1454− | GeoPolygonFilter FieldName [LatLon]
1455− | IdsFilter MappingName [DocId]
1456− | LimitFilter Int
1457− | MissingFilter FieldName Existence NullValue
1458− | PrefixFilter FieldName PrefixValue Cache
1459− | QueryFilter Query Cache
1460− | RangeFilter FieldName RangeValue RangeExecution Cache
1461− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1462− | TermFilter Term Cache
1463− deriving (Eq, Read, Show, Generic, Typeable)
1464−
1465−data ZeroTermsQuery = ZeroTermsNone
1466− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1467−
1468−data RangeExecution = RangeExecutionIndex
1469− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1470−
1471−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1472−
1473−data RegexpFlags = AllRegexpFlags
1474− | NoRegexpFlags
1475− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1476−
1477−data RegexpFlag = AnyString
1478− | Automaton
1479− | Complement
1480− | Empty
1481− | Intersection
1482− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1483−
1484−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1485−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1486−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1487−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1488−
1489−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1490−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1491−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1492−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1493−
1494−data RangeValue = RangeDateLte LessThanEqD
1495− | RangeDateLt LessThanD
1496− | RangeDateGte GreaterThanEqD
1497− | RangeDateGt GreaterThanD
1498− | RangeDateGtLt GreaterThanD LessThanD
1499− | RangeDateGteLte GreaterThanEqD LessThanEqD
1500− | RangeDateGteLt GreaterThanEqD LessThanD
1501− | RangeDateGtLte GreaterThanD LessThanEqD
1502− | RangeDoubleLte LessThanEq
1503− | RangeDoubleLt LessThan
1504− | RangeDoubleGte GreaterThanEq
1505− | RangeDoubleGt GreaterThan
1506− | RangeDoubleGtLt GreaterThan LessThan
1507− | RangeDoubleGteLte GreaterThanEq LessThanEq
1508− | RangeDoubleGteLt GreaterThanEq LessThan
1509− | RangeDoubleGtLte GreaterThan LessThanEq
1510− deriving (Eq, Read, Show, Generic, Typeable)
1511−
1512−rangeValueToPair :: RangeValue -> [Pair]
1513−rangeValueToPair rv = case rv of
1514− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1515− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1516− RangeDateLt (LessThanD t) -> ["lt" .= t]
1517− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1518− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1519− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1520− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1521− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1522− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1523− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1524− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1525− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1526− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1527− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1528− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1529− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1530−
1531−data Term = Term { termField :: Text
1532− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1533−
1534−data BoolMatch = MustMatch Term Cache
1535− | MustNotMatch Term Cache
1536− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1537−
1538−-- "memory" or "indexed"
1539−data GeoFilterType = GeoFilterMemory
1540− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1541−
1542−data LatLon = LatLon { lat :: Double
1543− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1544−
1545−data GeoBoundingBox =
1546− GeoBoundingBox { topLeft :: LatLon
1547− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
490+instance ToJSON Source where
491+ toJSON NoSource = toJSON False
492+ toJSON (SourcePatterns patterns) = toJSON patterns
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1548494
1549−data GeoBoundingBoxConstraint =
1550− GeoBoundingBoxConstraint { geoBBField :: FieldName
1551− , constraintBox :: GeoBoundingBox
1552− , bbConstraintcache :: Cache
1553− , geoType :: GeoFilterType
1554− } deriving (Eq, Read, Show, Generic, Typeable)
495+data PatternOrPatterns = PopPattern Pattern
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1555497
1556−data GeoPoint =
1557− GeoPoint { geoField :: FieldName
1558− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
498+instance ToJSON PatternOrPatterns where
499+ toJSON (PopPattern pattern) = toJSON pattern
500+ toJSON (PopPatterns patterns) = toJSON patterns
1559501
1560−data DistanceUnit = Miles
1561− | Yards
1562− | Feet
1563− | Inches
1564− | Kilometers
1565− | Meters
1566− | Centimeters
1567− | Millimeters
1568− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1569504
1570−data DistanceType = Arc
1571− | SloppyArc -- doesn't exist <1.0
1572− | Plane deriving (Eq, Read, Show, Generic, Typeable)
505+instance ToJSON Include where
506+ toJSON (Include patterns) = toJSON patterns
1573507
1574−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1575− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
508+instance ToJSON Exclude where
509+ toJSON (Exclude patterns) = toJSON patterns
1576510
1577−data Distance =
1578− Distance { coefficient :: Double
1579− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1580512
1581−data DistanceRange =
1582− DistanceRange { distanceFrom :: Distance
1583− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
513+instance ToJSON Pattern where
514+ toJSON (Pattern pattern) = toJSON pattern
1584515
1585516data SearchResult a =
1586517 SearchResult { took :: Int
@@ -1588,2069 +519,12 @@ data SearchResult a =
1588519 , shards :: ShardResult
1589520 , searchHits :: SearchHits a
1590521 , aggregations :: Maybe AggregationResults
1591− , scrollId :: Maybe ScrollId } deriving (Eq, Read, Show, Generic, Typeable)
1592−
1593−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
1594−
1595−type Score = Maybe Double
1596−
1597−data SearchHits a =
1598− SearchHits { hitsTotal :: Int
1599− , maxScore :: Score
1600− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1601−
1602−
1603−instance Monoid (SearchHits a) where
1604− mempty = SearchHits 0 Nothing mempty
1605− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1606− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1607−
1608−
1609−data Hit a =
1610− Hit { hitIndex :: IndexName
1611− , hitType :: MappingName
1612− , hitDocId :: DocId
1613− , hitScore :: Score
1614− , hitSource :: Maybe a
1615− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1616−
1617−data ShardResult =
1618− ShardResult { shardTotal :: Int
1619− , shardsSuccessful :: Int
1620− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1621−
1622−type HitHighlight = M.Map Text [Text]
1623−
1624−showText :: Show a => a -> Text
1625−showText = T.pack . show
1626−
1627−readMay :: Read a => String -> Maybe a
1628−readMay s = case reads s of
1629− (a, ""):_ -> Just a
1630− _ -> Nothing
1631−
1632−parseReadText :: Read a => Text -> Parser a
1633−parseReadText = maybe mzero return . readMay . T.unpack
1634−
1635−type Aggregations = M.Map Text Aggregation
1636−
1637−emptyAggregations :: Aggregations
1638−emptyAggregations = M.empty
1639−
1640−mkAggregations :: Text -> Aggregation -> Aggregations
1641−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1642−
1643−data TermOrder = TermOrder{ termSortField :: Text
1644− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1645−
1646−data TermInclusion = TermInclusion Text
1647− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1648−
1649−data CollectionMode = BreadthFirst
1650− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1651−
1652−data ExecutionHint = Ordinals
1653− | GlobalOrdinals
1654− | GlobalOrdinalsHash
1655− | GlobalOrdinalsLowCardinality
1656− | Map deriving (Eq, Read, Show, Generic, Typeable)
1657−
1658−data TimeInterval = Weeks
1659− | Days
1660− | Hours
1661− | Minutes
1662− | Seconds deriving Eq
1663−
1664−data Interval = Year
1665− | Quarter
1666− | Month
1667− | Week
1668− | Day
1669− | Hour
1670− | Minute
1671− | Second
1672− | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1673−
1674−data Aggregation = TermsAgg TermsAggregation
1675− | DateHistogramAgg DateHistogramAggregation
1676− | ValueCountAgg ValueCountAggregation
1677− | FilterAgg FilterAggregation
1678− | DateRangeAgg DateRangeAggregation
1679− | MissingAgg MissingAggregation deriving (Eq, Read, Show, Generic, Typeable)
1680−
1681−data MissingAggregation = MissingAggregation
1682− { maField :: Text
1683− } deriving (Eq, Read, Show, Generic, Typeable)
1684−
1685−data TermsAggregation = TermsAggregation { term :: Either Text Text
1686− , termInclude :: Maybe TermInclusion
1687− , termExclude :: Maybe TermInclusion
1688− , termOrder :: Maybe TermOrder
1689− , termMinDocCount :: Maybe Int
1690− , termSize :: Maybe Int
1691− , termShardSize :: Maybe Int
1692− , termCollectMode :: Maybe CollectionMode
1693− , termExecutionHint :: Maybe ExecutionHint
1694− , termAggs :: Maybe Aggregations
1695− } deriving (Eq, Read, Show, Generic, Typeable)
1696−
1697−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1698− , dateInterval :: Interval
1699− , dateFormat :: Maybe Text
1700− -- pre and post deprecated in 1.5
1701− , datePreZone :: Maybe Text
1702− , datePostZone :: Maybe Text
1703− , datePreOffset :: Maybe Text
1704− , datePostOffset :: Maybe Text
1705− , dateAggs :: Maybe Aggregations
1706− } deriving (Eq, Read, Show, Generic, Typeable)
1707−
1708−
1709−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1710− , draFormat :: Maybe Text
1711− , draRanges :: NonEmpty DateRangeAggRange
1712− } deriving (Eq, Read, Show, Generic, Typeable)
1713−
1714−data DateRangeAggRange = DateRangeFrom DateMathExpr
1715− | DateRangeTo DateMathExpr
1716− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
1717−
1718−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1719−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1720−
1721−
1722−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1723−data DateMathAnchor = DMNow
1724− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1725−
1726−data DateMathModifier = AddTime Int DateMathUnit
1727− | SubtractTime Int DateMathUnit
1728− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1729−
1730−data DateMathUnit = DMYear
1731− | DMMonth
1732− | DMWeek
1733− | DMDay
1734− | DMHour
1735− | DMMinute
1736− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1737−
1738−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1739−data ValueCountAggregation = FieldValueCount FieldName
1740− | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
1741−
1742−-- | 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.
1743−data FilterAggregation = FilterAggregation { faFilter :: Filter
1744− , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
1745−
1746−mkTermsAggregation :: Text -> TermsAggregation
1747−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1748−
1749−mkTermsScriptAggregation :: Text -> TermsAggregation
1750−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1751−
1752−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1753−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1754−
1755−instance ToJSON Version where
1756− toJSON Version {..} = object ["number" .= number
1757− ,"build_hash" .= build_hash
1758− ,"build_timestamp" .= build_timestamp
1759− ,"build_snapshot" .= build_snapshot
1760− ,"lucene_version" .= lucene_version]
1761−
1762−instance FromJSON Version where
1763− parseJSON = withObject "Version" parse
1764− where parse o = Version
1765− <$> o .: "number"
1766− <*> o .: "build_hash"
1767− <*> o .: "build_timestamp"
1768− <*> o .: "build_snapshot"
1769− <*> o .: "lucene_version"
1770−
1771−instance ToJSON VersionNumber where
1772− toJSON = toJSON . Vers.showVersion . versionNumber
1773−
1774−instance FromJSON VersionNumber where
1775− parseJSON = withText "VersionNumber" (parse . T.unpack)
1776− where
1777− parse s = case filter (null . snd)(RP.readP_to_S Vers.parseVersion s) of
1778− [(v, _)] -> pure (VersionNumber v)
1779− [] -> fail ("Invalid version string " ++ s)
1780− xs -> fail ("Ambiguous version string " ++ s ++ " (" ++ intercalate ", " (Vers.showVersion . fst <$> xs) ++ ")")
1781−
1782−instance ToJSON TermOrder where
1783− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1784−
1785−instance ToJSON TermInclusion where
1786− toJSON (TermInclusion x) = toJSON x
1787− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1788− "flags" .= flags]
1789−
1790−instance ToJSON CollectionMode where
1791− toJSON BreadthFirst = "breadth_first"
1792− toJSON DepthFirst = "depth_first"
1793−
1794−instance ToJSON ExecutionHint where
1795− toJSON Ordinals = "ordinals"
1796− toJSON GlobalOrdinals = "global_ordinals"
1797− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1798− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1799− toJSON Map = "map"
1800−
1801−instance ToJSON Interval where
1802− toJSON Year = "year"
1803− toJSON Quarter = "quarter"
1804− toJSON Month = "month"
1805− toJSON Week = "week"
1806− toJSON Day = "day"
1807− toJSON Hour = "hour"
1808− toJSON Minute = "minute"
1809− toJSON Second = "second"
1810− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1811−
1812−instance Show TimeInterval where
1813− show Weeks = "w"
1814− show Days = "d"
1815− show Hours = "h"
1816− show Minutes = "m"
1817− show Seconds = "s"
1818−
1819−instance Read TimeInterval where
1820− readPrec = f =<< TR.get
1821− where
1822− f 'w' = return Weeks
1823− f 'd' = return Days
1824− f 'h' = return Hours
1825− f 'm' = return Minutes
1826− f 's' = return Seconds
1827− f _ = fail "TimeInterval expected one of w, d, h, m, s"
1828−
1829−instance ToJSON Aggregation where
1830− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1831− omitNulls ["terms" .= omitNulls [ toJSON' term,
1832− "include" .= include,
1833− "exclude" .= exclude,
1834− "order" .= order,
1835− "min_doc_count" .= minDocCount,
1836− "size" .= size,
1837− "shard_size" .= shardSize,
1838− "collect_mode" .= collectMode,
1839− "execution_hint" .= executionHint
1840− ],
1841− "aggs" .= termAggs ]
1842− where
1843− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1844−
1845− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1846− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1847− "interval" .= interval,
1848− "format" .= format,
1849− "pre_zone" .= preZone,
1850− "post_zone" .= postZone,
1851− "pre_offset" .= preOffset,
1852− "post_offset" .= postOffset
1853− ],
1854− "aggs" .= dateHistoAggs ]
1855− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1856− where v = case a of
1857− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1858− (ScriptValueCount (Script s)) -> object ["script" .= s]
1859− toJSON (FilterAgg (FilterAggregation filt ags)) =
1860− omitNulls [ "filter" .= filt
1861− , "aggs" .= ags]
1862− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1863− ]
1864− toJSON (MissingAgg (MissingAggregation{..})) =
1865− object ["missing" .= object ["field" .= maField]]
1866−
1867−instance ToJSON DateRangeAggregation where
1868− toJSON DateRangeAggregation {..} =
1869− omitNulls [ "field" .= draField
1870− , "format" .= draFormat
1871− , "ranges" .= toList draRanges
1872− ]
1873−
1874−instance ToJSON DateRangeAggRange where
1875− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1876− toJSON (DateRangeTo e) = object [ "to" .= e ]
1877− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1878−
1879−instance ToJSON DateMathExpr where
1880− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1881− where fmtA DMNow = "now"
1882− fmtA (DMDate date) = case toGregorian date of
1883− (y,m,d) -> showText y <> "-" <>
1884− showText m <> "-" <>
1885− showText d <> "||"
1886− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1887− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1888− fmtMod (RoundDownTo u) = "/" <> fmtU u
1889− fmtU DMYear = "y"
1890− fmtU DMMonth = "M"
1891− fmtU DMWeek = "w"
1892− fmtU DMDay = "d"
1893− fmtU DMHour = "h"
1894− fmtU DMMinute = "m"
1895− fmtU DMSecond = "s"
1896−
1897−
1898−type AggregationResults = M.Map Text Value
1899−
1900−class BucketAggregation a where
1901− key :: a -> BucketValue
1902− docCount :: a -> Int
1903− aggs :: a -> Maybe AggregationResults
1904−
1905−
1906−data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1907−
1908−data BucketValue = TextValue Text
1909− | ScientificValue Scientific
1910− | BoolValue Bool deriving (Read, Show)
1911−
1912−data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1913−
1914−data TermsResult = TermsResult { termKey :: BucketValue
1915− , termsDocCount :: Int
1916− , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1917−
1918−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1919− , dateKeyStr :: Maybe Text
1920− , dateDocCount :: Int
1921− , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1922−
1923−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1924− , dateRangeFrom :: Maybe UTCTime
1925− , dateRangeFromAsString :: Maybe Text
1926− , dateRangeTo :: Maybe UTCTime
1927− , dateRangeToAsString :: Maybe Text
1928− , dateRangeDocCount :: Int
1929− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1930−
1931−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1932−toTerms = toAggResult
1933−
1934−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1935−toDateHistogram = toAggResult
1936−
1937−toMissing :: Text -> AggregationResults -> Maybe MissingResult
1938−toMissing = toAggResult
1939−
1940−toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1941−toAggResult t a = M.lookup t a >>= deserialize
1942− where deserialize = parseMaybe parseJSON
1943−
1944−instance BucketAggregation TermsResult where
1945− key = termKey
1946− docCount = termsDocCount
1947− aggs = termsAggs
1948−
1949−instance BucketAggregation DateHistogramResult where
1950− key = TextValue . showText . dateKey
1951− docCount = dateDocCount
1952− aggs = dateHistogramAggs
1953−
1954−instance BucketAggregation DateRangeResult where
1955− key = TextValue . dateRangeKey
1956− docCount = dateRangeDocCount
1957− aggs = dateRangeAggs
1958−
1959−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1960− parseJSON (Object v) = Bucket <$>
1961− v .: "buckets"
1962− parseJSON _ = mempty
1963−
1964−instance FromJSON BucketValue where
1965− parseJSON (String t) = return $ TextValue t
1966− parseJSON (Number s) = return $ ScientificValue s
1967− parseJSON (Bool b) = return $ BoolValue b
1968− parseJSON _ = mempty
1969−
1970−instance FromJSON MissingResult where
1971− parseJSON = withObject "MissingResult" parse
1972− where parse v = MissingResult <$> v .: "doc_count"
1973−
1974−instance FromJSON TermsResult where
1975− parseJSON (Object v) = TermsResult <$>
1976− v .: "key" <*>
1977− v .: "doc_count" <*>
1978− v .:? "aggregations"
1979− parseJSON _ = mempty
1980−
1981−instance FromJSON DateHistogramResult where
1982− parseJSON (Object v) = DateHistogramResult <$>
1983− v .: "key" <*>
1984− v .:? "key_as_string" <*>
1985− v .: "doc_count" <*>
1986− v .:? "aggregations"
1987− parseJSON _ = mempty
1988−
1989−instance FromJSON DateRangeResult where
1990− parseJSON = withObject "DateRangeResult" parse
1991− where parse v = DateRangeResult <$>
1992− v .: "key" <*>
1993− (fmap posixMS <$> v .:? "from") <*>
1994− v .:? "from_as_string" <*>
1995− (fmap posixMS <$> v .:? "to") <*>
1996− v .:? "to_as_string" <*>
1997− v .: "doc_count" <*>
1998− v .:? "aggregations"
1999−
2000−instance FromJSON POSIXMS where
2001− parseJSON = withScientific "POSIXMS" (return . parse)
2002− where parse n = let n' = truncate n :: Integer
2003− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
2004−
2005−instance Monoid Filter where
2006− mempty = IdentityFilter
2007− mappend a b = AndFilter [a, b] defaultCache
2008−
2009−instance Seminearring Filter where
2010− a <||> b = OrFilter [a, b] defaultCache
2011−
2012−instance ToJSON Filter where
2013− toJSON (AndFilter filters cache) =
2014− object ["and" .=
2015− object [ "filters" .= fmap toJSON filters
2016− , "_cache" .= cache]]
2017−
2018− toJSON (OrFilter filters cache) =
2019− object ["or" .=
2020− object [ "filters" .= fmap toJSON filters
2021− , "_cache" .= cache]]
2022−
2023− toJSON (NotFilter notFilter cache) =
2024− object ["not" .=
2025− object ["filter" .= notFilter
2026− , "_cache" .= cache]]
2027−
2028− toJSON (IdentityFilter) =
2029− object ["match_all" .= object []]
2030−
2031− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
2032− object ["term" .= object base]
2033− where base = [termFilterField .= termFilterValue,
2034− "_cache" .= cache]
2035−
2036− toJSON (ExistsFilter (FieldName fieldName)) =
2037− object ["exists" .= object
2038− ["field" .= fieldName]]
2039−
2040− toJSON (BoolFilter boolMatch) =
2041− object ["bool" .= boolMatch]
2042−
2043− toJSON (GeoBoundingBoxFilter bbConstraint) =
2044− object ["geo_bounding_box" .= bbConstraint]
2045−
2046− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
2047− distance distanceType optimizeBbox cache) =
2048− object ["geo_distance" .=
2049− object ["distance" .= distance
2050− , "distance_type" .= distanceType
2051− , "optimize_bbox" .= optimizeBbox
2052− , distanceGeoField .= geoDistLatLon
2053− , "_cache" .= cache]]
2054−
2055− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
2056− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
2057− object ["geo_distance_range" .=
2058− object ["from" .= geoDistRangeDistFrom
2059− , "to" .= drDistanceTo
2060− , gddrField .= drLatLon]]
2061−
2062− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
2063− object ["geo_polygon" .=
2064− object [geoPolygonFilterField .=
2065− object ["points" .= fmap toJSON latLons]]]
2066−
2067− toJSON (IdsFilter (MappingName mappingName) values) =
2068− object ["ids" .=
2069− object ["type" .= mappingName
2070− , "values" .= fmap unpackId values]]
2071−
2072− toJSON (LimitFilter limit) =
2073− object ["limit" .= object ["value" .= limit]]
2074−
2075− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
2076− object ["missing" .=
2077− object ["field" .= fieldName
2078− , "existence" .= existence
2079− , "null_value" .= nullValue]]
2080−
2081− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
2082− object ["prefix" .=
2083− object [fieldName .= fieldValue
2084− , "_cache" .= cache]]
2085−
2086− toJSON (QueryFilter query False) =
2087− object ["query" .= toJSON query ]
2088− toJSON (QueryFilter query True) =
2089− object ["fquery" .=
2090− object [ "query" .= toJSON query
2091− , "_cache" .= True ]]
2092−
2093− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
2094− object ["range" .=
2095− object [ fieldName .= object (rangeValueToPair rangeValue)
2096− , "execution" .= rangeExecution
2097− , "_cache" .= cache]]
2098−
2099− toJSON (RegexpFilter (FieldName fieldName)
2100− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
2101− object ["regexp" .=
2102− object [fieldName .=
2103− object ["value" .= regexText
2104− , "flags" .= flags]
2105− , "_name" .= cacheName
2106− , "_cache" .= cache
2107− , "_cache_key" .= cacheKey]]
2108−
2109−instance FromJSON Filter where
2110− parseJSON = withObject "Filter" parse
2111− where parse o = andFilter `taggedWith` "and"
2112− <|> orFilter `taggedWith` "or"
2113− <|> notFilter `taggedWith` "not"
2114− <|> identityFilter `taggedWith` "match_all"
2115− <|> boolFilter `taggedWith` "bool"
2116− <|> existsFilter `taggedWith` "exists"
2117− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
2118− <|> geoDistanceFilter `taggedWith` "geo_distance"
2119− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
2120− <|> geoPolygonFilter `taggedWith` "geo_polygon"
2121− <|> idsFilter `taggedWith` "ids"
2122− <|> limitFilter `taggedWith` "limit"
2123− <|> missingFilter `taggedWith` "missing"
2124− <|> prefixFilter `taggedWith` "prefix"
2125− <|> queryFilter `taggedWith` "query"
2126− <|> fqueryFilter `taggedWith` "fquery"
2127− <|> rangeFilter `taggedWith` "range"
2128− <|> regexpFilter `taggedWith` "regexp"
2129− <|> termFilter `taggedWith` "term"
2130− where taggedWith parser k = parser =<< o .: k
2131− andFilter o = AndFilter <$> o .: "filters"
2132− <*> o .:? "_cache" .!= defaultCache
2133− orFilter o = OrFilter <$> o .: "filters"
2134− <*> o .:? "_cache" .!= defaultCache
2135− notFilter o = NotFilter <$> o .: "filter"
2136− <*> o .: "_cache" .!= defaultCache
2137− identityFilter :: Object -> Parser Filter
2138− identityFilter m
2139− | HM.null m = pure IdentityFilter
2140− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
2141− boolFilter = pure . BoolFilter
2142− existsFilter o = ExistsFilter <$> o .: "field"
2143− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
2144− geoDistanceFilter o = do
2145− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
2146− [(fn, v)] -> do
2147− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2148− GeoDistanceFilter gp <$> o .: "distance"
2149− <*> o .: "distance_type"
2150− <*> o .: "optimize_bbox"
2151− <*> o .:? "_cache" .!= defaultCache
2152− _ -> fail "Could not find GeoDistanceFilter field name"
2153− geoDistanceRangeFilter o = do
2154− case HM.toList (deleteSeveral ["from", "to"] o) of
2155− [(fn, v)] -> do
2156− gp <- GeoPoint (FieldName fn) <$> parseJSON v
2157− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
2158− return (GeoDistanceRangeFilter gp rng)
2159− _ -> fail "Could not find GeoDistanceRangeFilter field name"
2160− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
2161− idsFilter o = IdsFilter <$> o .: "type"
2162− <*> o .: "values"
2163− limitFilter o = LimitFilter <$> o .: "value"
2164− missingFilter o = MissingFilter <$> o .: "field"
2165− <*> o .: "existence"
2166− <*> o .: "null_value"
2167− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
2168− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
2169− _ -> fail "Could not parse PrefixFilter"
2170−
2171− queryFilter q = pure (QueryFilter q False)
2172− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2173− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2174− [(fn, v)] -> RangeFilter (FieldName fn)
2175− <$> parseJSON v
2176− <*> o .: "execution"
2177− <*> o .:? "_cache" .!= defaultCache
2178− _ -> fail "Could not find field name for RangeFilter"
2179− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2180− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2181− <$> o' .: "value"
2182− <*> o' .: "flags"
2183− <*> o .: "_name"
2184− <*> o .:? "_cache" .!= defaultCache
2185− <*> o .: "_cache_key"
2186− _ -> fail "Could not find field name for RegexpFilter"
2187− termFilter o = case HM.toList (HM.delete "_cache" o) of
2188− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2189− <$> o .:? "_cache" .!= defaultCache
2190− _ -> fail "Could not find term field for TermFilter"
2191−
2192−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2193−fieldTagged f o = case HM.toList o of
2194− [(k, Object o')] -> f (FieldName k) o'
2195− _ -> fail "Expected object with 1 field-named key"
2196−
2197−instance ToJSON GeoPoint where
2198− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2199− object [ geoPointField .= geoPointLatLon ]
2200−
2201−
2202−instance ToJSON Query where
2203− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2204− object [ "term" .=
2205− object [termQueryField .= object merged]]
2206− where
2207− base = [ "value" .= termQueryValue ]
2208− boosted = maybe [] (return . ("boost" .=)) boost
2209− merged = mappend base boosted
2210−
2211− toJSON (TermsQuery fieldName terms) =
2212− object [ "terms" .= object conjoined ]
2213− where conjoined = [fieldName .= terms]
2214−
2215− toJSON (IdsQuery idsQueryMappingName docIds) =
2216− object [ "ids" .= object conjoined ]
2217− where conjoined = [ "type" .= idsQueryMappingName
2218− , "values" .= fmap toJSON docIds ]
2219−
2220− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2221− object [ "query_string" .= qQueryStringQuery ]
2222−
2223− toJSON (QueryMatchQuery matchQuery) =
2224− object [ "match" .= matchQuery ]
2225−
2226− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2227− toJSON multiMatchQuery
2228−
2229− toJSON (QueryBoolQuery boolQuery) =
2230− object [ "bool" .= boolQuery ]
2231−
2232− toJSON (QueryBoostingQuery boostingQuery) =
2233− object [ "boosting" .= boostingQuery ]
2234−
2235− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2236− object [ "common" .= commonTermsQuery ]
2237−
2238− toJSON (ConstantScoreFilter csFilter boost) =
2239− object ["constant_score" .= object ["filter" .= csFilter
2240− , "boost" .= boost]]
2241−
2242− toJSON (ConstantScoreQuery query boost) =
2243− object ["constant_score" .= object ["query" .= query
2244− , "boost" .= boost]]
2245−
2246− toJSON (QueryDisMaxQuery disMaxQuery) =
2247− object [ "dis_max" .= disMaxQuery ]
2248−
2249− toJSON (QueryFilteredQuery qFilteredQuery) =
2250− object [ "filtered" .= qFilteredQuery ]
2251−
2252− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2253− object [ "fuzzy_like_this" .= fuzzyQuery ]
2254−
2255− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2256− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2257−
2258− toJSON (QueryFuzzyQuery fuzzyQuery) =
2259− object [ "fuzzy" .= fuzzyQuery ]
2260−
2261− toJSON (QueryHasChildQuery childQuery) =
2262− object [ "has_child" .= childQuery ]
2263−
2264− toJSON (QueryHasParentQuery parentQuery) =
2265− object [ "has_parent" .= parentQuery ]
2266−
2267− toJSON (QueryIndicesQuery qIndicesQuery) =
2268− object [ "indices" .= qIndicesQuery ]
2269−
2270− toJSON (MatchAllQuery boost) =
2271− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2272−
2273− toJSON (QueryMoreLikeThisQuery query) =
2274− object [ "more_like_this" .= query ]
2275−
2276− toJSON (QueryMoreLikeThisFieldQuery query) =
2277− object [ "more_like_this_field" .= query ]
2278−
2279− toJSON (QueryNestedQuery query) =
2280− object [ "nested" .= query ]
2281−
2282− toJSON (QueryPrefixQuery query) =
2283− object [ "prefix" .= query ]
2284−
2285− toJSON (QueryRangeQuery query) =
2286− object [ "range" .= query ]
2287−
2288− toJSON (QueryRegexpQuery query) =
2289− object [ "regexp" .= query ]
2290−
2291− toJSON (QuerySimpleQueryStringQuery query) =
2292− object [ "simple_query_string" .= query ]
2293−
2294−instance FromJSON Query where
2295− parseJSON v = withObject "Query" parse v
2296− where parse o = termQuery `taggedWith` "term"
2297− <|> termsQuery `taggedWith` "terms"
2298− <|> idsQuery `taggedWith` "ids"
2299− <|> queryQueryStringQuery `taggedWith` "query_string"
2300− <|> queryMatchQuery `taggedWith` "match"
2301− <|> queryMultiMatchQuery
2302− <|> queryBoolQuery `taggedWith` "bool"
2303− <|> queryBoostingQuery `taggedWith` "boosting"
2304− <|> queryCommonTermsQuery `taggedWith` "common"
2305− <|> constantScoreFilter `taggedWith` "constant_score"
2306− <|> constantScoreQuery `taggedWith` "constant_score"
2307− <|> queryDisMaxQuery `taggedWith` "dis_max"
2308− <|> queryFilteredQuery `taggedWith` "filtered"
2309− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2310− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2311− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2312− <|> queryHasChildQuery `taggedWith` "has_child"
2313− <|> queryHasParentQuery `taggedWith` "has_parent"
2314− <|> queryIndicesQuery `taggedWith` "indices"
2315− <|> matchAllQuery `taggedWith` "match_all"
2316− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2317− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2318− <|> queryNestedQuery `taggedWith` "nested"
2319− <|> queryPrefixQuery `taggedWith` "prefix"
2320− <|> queryRangeQuery `taggedWith` "range"
2321− <|> queryRegexpQuery `taggedWith` "regexp"
2322− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2323− where taggedWith parser k = parser =<< o .: k
2324− termQuery = fieldTagged $ \(FieldName fn) o ->
2325− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2326− termsQuery o = case HM.toList o of
2327− [(fn, vs)] -> do vals <- parseJSON vs
2328− case vals of
2329− x:xs -> return (TermsQuery fn (x :| xs))
2330− _ -> fail "Expected non empty list of values"
2331− _ -> fail "Expected object with 1 field-named key"
2332− idsQuery o = IdsQuery <$> o .: "type"
2333− <*> o .: "values"
2334− queryQueryStringQuery = pure . QueryQueryStringQuery
2335− queryMatchQuery = pure . QueryMatchQuery
2336− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2337− queryBoolQuery = pure . QueryBoolQuery
2338− queryBoostingQuery = pure . QueryBoostingQuery
2339− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2340− constantScoreFilter o = case HM.lookup "filter" o of
2341− Just x -> ConstantScoreFilter <$> parseJSON x
2342− <*> o .: "boost"
2343− _ -> fail "Does not appear to be a ConstantScoreFilter"
2344− constantScoreQuery o = case HM.lookup "query" o of
2345− Just x -> ConstantScoreQuery <$> parseJSON x
2346− <*> o .: "boost"
2347− _ -> fail "Does not appear to be a ConstantScoreQuery"
2348− queryDisMaxQuery = pure . QueryDisMaxQuery
2349− queryFilteredQuery = pure . QueryFilteredQuery
2350− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2351− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2352− queryFuzzyQuery = pure . QueryFuzzyQuery
2353− queryHasChildQuery = pure . QueryHasChildQuery
2354− queryHasParentQuery = pure . QueryHasParentQuery
2355− queryIndicesQuery = pure . QueryIndicesQuery
2356− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2357− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2358− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2359− queryNestedQuery = pure . QueryNestedQuery
2360− queryPrefixQuery = pure . QueryPrefixQuery
2361− queryRangeQuery = pure . QueryRangeQuery
2362− queryRegexpQuery = pure . QueryRegexpQuery
2363− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2364−
2365−
2366−omitNulls :: [(Text, Value)] -> Value
2367−omitNulls = object . filter notNull where
2368− notNull (_, Null) = False
2369− notNull (_, Array a) = (not . V.null) a
2370− notNull _ = True
2371−
2372−
2373−instance ToJSON SimpleQueryStringQuery where
2374− toJSON SimpleQueryStringQuery {..} =
2375− omitNulls (base ++ maybeAdd)
2376− where base = [ "query" .= simpleQueryStringQuery ]
2377− maybeAdd = [ "fields" .= simpleQueryStringField
2378− , "default_operator" .= simpleQueryStringOperator
2379− , "analyzer" .= simpleQueryStringAnalyzer
2380− , "flags" .= simpleQueryStringFlags
2381− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2382− , "locale" .= simpleQueryStringLocale ]
2383−
2384−instance FromJSON SimpleQueryStringQuery where
2385− parseJSON = withObject "SimpleQueryStringQuery" parse
2386− where parse o = SimpleQueryStringQuery <$> o .: "query"
2387− <*> o .:? "fields"
2388− <*> o .:? "default_operator"
2389− <*> o .:? "analyzer"
2390− <*> (parseFlags <$> o .:? "flags")
2391− <*> o .:? "lowercase_expanded_terms"
2392− <*> o .:? "locale"
2393− parseFlags (Just (x:xs)) = Just (x :| xs)
2394− parseFlags _ = Nothing
2395−
2396−instance ToJSON FieldOrFields where
2397− toJSON (FofField fieldName) =
2398− toJSON fieldName
2399− toJSON (FofFields fieldNames) =
2400− toJSON fieldNames
2401−
2402−instance FromJSON FieldOrFields where
2403− parseJSON v = FofField <$> parseJSON v
2404− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2405−
2406−instance ToJSON SimpleQueryFlag where
2407− toJSON SimpleQueryAll = "ALL"
2408− toJSON SimpleQueryNone = "NONE"
2409− toJSON SimpleQueryAnd = "AND"
2410− toJSON SimpleQueryOr = "OR"
2411− toJSON SimpleQueryPrefix = "PREFIX"
2412− toJSON SimpleQueryPhrase = "PHRASE"
2413− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2414− toJSON SimpleQueryEscape = "ESCAPE"
2415− toJSON SimpleQueryWhitespace = "WHITESPACE"
2416− toJSON SimpleQueryFuzzy = "FUZZY"
2417− toJSON SimpleQueryNear = "NEAR"
2418− toJSON SimpleQuerySlop = "SLOP"
2419−
2420−instance FromJSON SimpleQueryFlag where
2421− parseJSON = withText "SimpleQueryFlag" parse
2422− where parse "ALL" = pure SimpleQueryAll
2423− parse "NONE" = pure SimpleQueryNone
2424− parse "AND" = pure SimpleQueryAnd
2425− parse "OR" = pure SimpleQueryOr
2426− parse "PREFIX" = pure SimpleQueryPrefix
2427− parse "PHRASE" = pure SimpleQueryPhrase
2428− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2429− parse "ESCAPE" = pure SimpleQueryEscape
2430− parse "WHITESPACE" = pure SimpleQueryWhitespace
2431− parse "FUZZY" = pure SimpleQueryFuzzy
2432− parse "NEAR" = pure SimpleQueryNear
2433− parse "SLOP" = pure SimpleQuerySlop
2434− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2435−
2436−instance ToJSON RegexpQuery where
2437− toJSON (RegexpQuery (FieldName rqQueryField)
2438− (Regexp regexpQueryQuery) rqQueryFlags
2439− rqQueryBoost) =
2440− object [ rqQueryField .= omitNulls base ]
2441− where base = [ "value" .= regexpQueryQuery
2442− , "flags" .= rqQueryFlags
2443− , "boost" .= rqQueryBoost ]
2444−
2445−instance FromJSON RegexpQuery where
2446− parseJSON = withObject "RegexpQuery" parse
2447− where parse = fieldTagged $ \fn o ->
2448− RegexpQuery fn
2449− <$> o .: "value"
2450− <*> o .: "flags"
2451− <*> o .:? "boost"
2452−
2453−instance ToJSON QueryStringQuery where
2454− toJSON (QueryStringQuery qsQueryString
2455− qsDefaultField qsOperator
2456− qsAnalyzer qsAllowWildcard
2457− qsLowercaseExpanded qsEnablePositionIncrements
2458− qsFuzzyMaxExpansions qsFuzziness
2459− qsFuzzyPrefixLength qsPhraseSlop
2460− qsBoost qsAnalyzeWildcard
2461− qsGeneratePhraseQueries qsMinimumShouldMatch
2462− qsLenient qsLocale) =
2463− omitNulls base
2464− where
2465− base = [ "query" .= qsQueryString
2466− , "default_field" .= qsDefaultField
2467− , "default_operator" .= qsOperator
2468− , "analyzer" .= qsAnalyzer
2469− , "allow_leading_wildcard" .= qsAllowWildcard
2470− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2471− , "enable_position_increments" .= qsEnablePositionIncrements
2472− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2473− , "fuzziness" .= qsFuzziness
2474− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2475− , "phrase_slop" .= qsPhraseSlop
2476− , "boost" .= qsBoost
2477− , "analyze_wildcard" .= qsAnalyzeWildcard
2478− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2479− , "minimum_should_match" .= qsMinimumShouldMatch
2480− , "lenient" .= qsLenient
2481− , "locale" .= qsLocale ]
2482−
2483−instance FromJSON QueryStringQuery where
2484− parseJSON = withObject "QueryStringQuery" parse
2485− where parse o = QueryStringQuery
2486− <$> o .: "query"
2487− <*> o .:? "default_field"
2488− <*> o .:? "default_operator"
2489− <*> o .:? "analyzer"
2490− <*> o .:? "allow_leading_wildcard"
2491− <*> o .:? "lowercase_expanded_terms"
2492− <*> o .:? "enable_position_increments"
2493− <*> o .:? "fuzzy_max_expansions"
2494− <*> o .:? "fuzziness"
2495− <*> o .:? "fuzzy_prefix_length"
2496− <*> o .:? "phrase_slop"
2497− <*> o .:? "boost"
2498− <*> o .:? "analyze_wildcard"
2499− <*> o .:? "auto_generate_phrase_queries"
2500− <*> o .:? "minimum_should_match"
2501− <*> o .:? "lenient"
2502− <*> o .:? "locale"
2503−
2504−instance ToJSON RangeQuery where
2505− toJSON (RangeQuery (FieldName fieldName) range boost) =
2506− object [ fieldName .= object conjoined ]
2507− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2508−
2509−instance FromJSON RangeQuery where
2510− parseJSON = withObject "RangeQuery" parse
2511− where parse = fieldTagged $ \fn o ->
2512− RangeQuery fn
2513− <$> parseJSON (Object o)
2514− <*> o .: "boost"
2515−
2516−instance FromJSON RangeValue where
2517− parseJSON = withObject "RangeValue" parse
2518− where parse o = parseDate o
2519− <|> parseDouble o
2520− parseDate o = do lt <- o .:? "lt"
2521− lte <- o .:? "lte"
2522− gt <- o .:? "gt"
2523− gte <- o .:? "gte"
2524− case (lt, lte, gt, gte) of
2525− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2526− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2527− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2528− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2529− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2530− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2531− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2532− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2533− (Nothing, Nothing, Nothing, Nothing) -> mzero
2534− parseDouble o = do lt <- o .:? "lt"
2535− lte <- o .:? "lte"
2536− gt <- o .:? "gt"
2537− gte <- o .:? "gte"
2538− case (lt, lte, gt, gte) of
2539− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2540− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2541− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2542− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2543− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2544− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2545− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2546− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2547− (Nothing, Nothing, Nothing, Nothing) -> mzero
2548−
2549−instance ToJSON PrefixQuery where
2550− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2551− object [ fieldName .= omitNulls base ]
2552− where base = [ "value" .= queryValue
2553− , "boost" .= boost ]
2554−
2555−instance FromJSON PrefixQuery where
2556− parseJSON = withObject "PrefixQuery" parse
2557− where parse = fieldTagged $ \fn o ->
2558− PrefixQuery fn
2559− <$> o .: "value"
2560− <*> o .:? "boost"
2561−
2562−instance ToJSON NestedQuery where
2563− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2564− object [ "path" .= nqPath
2565− , "score_mode" .= nqScoreType
2566− , "query" .= nqQuery ]
2567−
2568−instance FromJSON NestedQuery where
2569− parseJSON = withObject "NestedQuery" parse
2570− where parse o = NestedQuery
2571− <$> o .: "path"
2572− <*> o .: "score_mode"
2573− <*> o .: "query"
2574−
2575−instance ToJSON MoreLikeThisFieldQuery where
2576− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2577− percent mtf mqt stopwords mindf maxdf
2578− minwl maxwl boostTerms boost analyzer) =
2579− object [ fieldName .= omitNulls base ]
2580− where base = [ "like_text" .= text
2581− , "percent_terms_to_match" .= percent
2582− , "min_term_freq" .= mtf
2583− , "max_query_terms" .= mqt
2584− , "stop_words" .= stopwords
2585− , "min_doc_freq" .= mindf
2586− , "max_doc_freq" .= maxdf
2587− , "min_word_length" .= minwl
2588− , "max_word_length" .= maxwl
2589− , "boost_terms" .= boostTerms
2590− , "boost" .= boost
2591− , "analyzer" .= analyzer ]
2592−
2593−instance FromJSON MoreLikeThisFieldQuery where
2594− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2595− where parse = fieldTagged $ \fn o ->
2596− MoreLikeThisFieldQuery
2597− <$> o .: "like_text"
2598− <*> pure fn
2599− <*> o .:? "percent_terms_to_match"
2600− <*> o .:? "min_term_freq"
2601− <*> o .:? "max_query_terms"
2602− -- <*> (optionalNE =<< o .:? "stop_words")
2603− <*> o .:? "stop_words"
2604− <*> o .:? "min_doc_freq"
2605− <*> o .:? "max_doc_freq"
2606− <*> o .:? "min_word_length"
2607− <*> o .:? "max_word_length"
2608− <*> o .:? "boost_terms"
2609− <*> o .:? "boost"
2610− <*> o .:? "analyzer"
2611− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2612−
2613−instance ToJSON MoreLikeThisQuery where
2614− toJSON (MoreLikeThisQuery text fields percent
2615− mtf mqt stopwords mindf maxdf
2616− minwl maxwl boostTerms boost analyzer) =
2617− omitNulls base
2618− where base = [ "like_text" .= text
2619− , "fields" .= fields
2620− , "percent_terms_to_match" .= percent
2621− , "min_term_freq" .= mtf
2622− , "max_query_terms" .= mqt
2623− , "stop_words" .= stopwords
2624− , "min_doc_freq" .= mindf
2625− , "max_doc_freq" .= maxdf
2626− , "min_word_length" .= minwl
2627− , "max_word_length" .= maxwl
2628− , "boost_terms" .= boostTerms
2629− , "boost" .= boost
2630− , "analyzer" .= analyzer ]
2631−
2632−instance FromJSON MoreLikeThisQuery where
2633− parseJSON = withObject "MoreLikeThisQuery" parse
2634− where parse o = MoreLikeThisQuery
2635− <$> o .: "like_text"
2636− -- <*> (optionalNE =<< o .:? "fields")
2637− <*> o .:? "fields"
2638− <*> o .:? "percent_terms_to_match"
2639− <*> o .:? "min_term_freq"
2640− <*> o .:? "max_query_terms"
2641− -- <*> (optionalNE =<< o .:? "stop_words")
2642− <*> o .:? "stop_words"
2643− <*> o .:? "min_doc_freq"
2644− <*> o .:? "max_doc_freq"
2645− <*> o .:? "min_word_length"
2646− <*> o .:? "max_word_length"
2647− <*> o .:? "boost_terms"
2648− <*> o .:? "boost"
2649− <*> o .:? "analyzer"
2650− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2651−
2652−instance ToJSON IndicesQuery where
2653− toJSON (IndicesQuery indices query noMatch) =
2654− omitNulls [ "indices" .= indices
2655− , "no_match_query" .= noMatch
2656− , "query" .= query ]
2657−
2658−instance FromJSON IndicesQuery where
2659− parseJSON = withObject "IndicesQuery" parse
2660− where parse o = IndicesQuery
2661− <$> o .:? "indices" .!= []
2662− <*> o .: "query"
2663− <*> o .:? "no_match_query"
2664−
2665−instance ToJSON HasParentQuery where
2666− toJSON (HasParentQuery queryType query scoreType) =
2667− omitNulls [ "parent_type" .= queryType
2668− , "score_type" .= scoreType
2669− , "query" .= query ]
2670−
2671−instance FromJSON HasParentQuery where
2672− parseJSON = withObject "HasParentQuery" parse
2673− where parse o = HasParentQuery
2674− <$> o .: "parent_type"
2675− <*> o .: "query"
2676− <*> o .:? "score_type"
2677−
2678−instance ToJSON HasChildQuery where
2679− toJSON (HasChildQuery queryType query scoreType) =
2680− omitNulls [ "query" .= query
2681− , "score_type" .= scoreType
2682− , "type" .= queryType ]
2683−
2684−instance FromJSON HasChildQuery where
2685− parseJSON = withObject "HasChildQuery" parse
2686− where parse o = HasChildQuery
2687− <$> o .: "type"
2688− <*> o .: "query"
2689− <*> o .:? "score_type"
2690−
2691−instance ToJSON FuzzyQuery where
2692− toJSON (FuzzyQuery (FieldName fieldName) queryText
2693− prefixLength maxEx fuzziness boost) =
2694− object [ fieldName .= omitNulls base ]
2695− where base = [ "value" .= queryText
2696− , "fuzziness" .= fuzziness
2697− , "prefix_length" .= prefixLength
2698− , "boost" .= boost
2699− , "max_expansions" .= maxEx ]
2700−
2701−instance FromJSON FuzzyQuery where
2702− parseJSON = withObject "FuzzyQuery" parse
2703− where parse = fieldTagged $ \fn o ->
2704− FuzzyQuery fn
2705− <$> o .: "value"
2706− <*> o .: "prefix_length"
2707− <*> o .: "max_expansions"
2708− <*> o .: "fuzziness"
2709− <*> o .:? "boost"
2710−
2711−instance ToJSON FuzzyLikeFieldQuery where
2712− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2713− fieldText maxTerms ignoreFreq fuzziness prefixLength
2714− boost analyzer) =
2715− object [ fieldName .=
2716− omitNulls [ "like_text" .= fieldText
2717− , "max_query_terms" .= maxTerms
2718− , "ignore_tf" .= ignoreFreq
2719− , "fuzziness" .= fuzziness
2720− , "prefix_length" .= prefixLength
2721− , "analyzer" .= analyzer
2722− , "boost" .= boost ]]
2723−
2724−instance FromJSON FuzzyLikeFieldQuery where
2725− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2726− where parse = fieldTagged $ \fn o ->
2727− FuzzyLikeFieldQuery fn
2728− <$> o .: "like_text"
2729− <*> o .: "max_query_terms"
2730− <*> o .: "ignore_tf"
2731− <*> o .: "fuzziness"
2732− <*> o .: "prefix_length"
2733− <*> o .: "boost"
2734− <*> o .:? "analyzer"
2735−
2736−instance ToJSON FuzzyLikeThisQuery where
2737− toJSON (FuzzyLikeThisQuery fields text maxTerms
2738− ignoreFreq fuzziness prefixLength boost analyzer) =
2739− omitNulls base
2740− where base = [ "fields" .= fields
2741− , "like_text" .= text
2742− , "max_query_terms" .= maxTerms
2743− , "ignore_tf" .= ignoreFreq
2744− , "fuzziness" .= fuzziness
2745− , "prefix_length" .= prefixLength
2746− , "analyzer" .= analyzer
2747− , "boost" .= boost ]
2748−
2749−instance FromJSON FuzzyLikeThisQuery where
2750− parseJSON = withObject "FuzzyLikeThisQuery" parse
2751− where parse o = FuzzyLikeThisQuery
2752− <$> o .:? "fields" .!= []
2753− <*> o .: "like_text"
2754− <*> o .: "max_query_terms"
2755− <*> o .: "ignore_tf"
2756− <*> o .: "fuzziness"
2757− <*> o .: "prefix_length"
2758− <*> o .: "boost"
2759− <*> o .:? "analyzer"
2760−
2761−instance ToJSON FilteredQuery where
2762− toJSON (FilteredQuery query fFilter) =
2763− object [ "query" .= query
2764− , "filter" .= fFilter ]
2765−
2766−instance FromJSON FilteredQuery where
2767− parseJSON = withObject "FilteredQuery" parse
2768− where parse o = FilteredQuery
2769− <$> o .: "query"
2770− <*> o .: "filter"
2771−
2772−instance ToJSON DisMaxQuery where
2773− toJSON (DisMaxQuery queries tiebreaker boost) =
2774− omitNulls base
2775− where base = [ "queries" .= queries
2776− , "boost" .= boost
2777− , "tie_breaker" .= tiebreaker ]
2778−
2779−instance FromJSON DisMaxQuery where
2780− parseJSON = withObject "DisMaxQuery" parse
2781− where parse o = DisMaxQuery
2782− <$> o .:? "queries" .!= []
2783− <*> o .: "tie_breaker"
2784− <*> o .:? "boost"
2785−
2786−instance ToJSON CommonTermsQuery where
2787− toJSON (CommonTermsQuery (FieldName fieldName)
2788− (QueryString query) cf lfo hfo msm
2789− boost analyzer disableCoord) =
2790− object [fieldName .= omitNulls base ]
2791− where base = [ "query" .= query
2792− , "cutoff_frequency" .= cf
2793− , "low_freq_operator" .= lfo
2794− , "minimum_should_match" .= msm
2795− , "boost" .= boost
2796− , "analyzer" .= analyzer
2797− , "disable_coord" .= disableCoord
2798− , "high_freq_operator" .= hfo ]
2799−
2800−instance FromJSON CommonTermsQuery where
2801− parseJSON = withObject "CommonTermsQuery" parse
2802− where parse = fieldTagged $ \fn o ->
2803− CommonTermsQuery fn
2804− <$> o .: "query"
2805− <*> o .: "cutoff_frequency"
2806− <*> o .: "low_freq_operator"
2807− <*> o .: "high_freq_operator"
2808− <*> o .:? "minimum_should_match"
2809− <*> o .:? "boost"
2810− <*> o .:? "analyzer"
2811− <*> o .:? "disable_coord"
2812−
2813−instance ToJSON CommonMinimumMatch where
2814− toJSON (CommonMinimumMatch mm) = toJSON mm
2815− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2816− object [ "low_freq" .= lowF
2817− , "high_freq" .= highF ]
2818−
2819−instance FromJSON CommonMinimumMatch where
2820− parseJSON v = parseMinimum v
2821− <|> parseMinimumHighLow v
2822− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2823− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2824− MinimumMatchHighLow
2825− <$> o .: "low_freq"
2826− <*> o .: "high_freq")
2827−
2828−
2829−instance ToJSON BoostingQuery where
2830− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2831− object [ "positive" .= bqPositiveQuery
2832− , "negative" .= bqNegativeQuery
2833− , "negative_boost" .= bqNegativeBoost ]
2834−
2835−instance FromJSON BoostingQuery where
2836− parseJSON = withObject "BoostingQuery" parse
2837− where parse o = BoostingQuery
2838− <$> o .: "positive"
2839− <*> o .: "negative"
2840− <*> o .: "negative_boost"
2841−
2842−instance ToJSON BoolQuery where
2843− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2844− omitNulls base
2845− where base = [ "must" .= mustM
2846− , "must_not" .= notM
2847− , "should" .= shouldM
2848− , "minimum_should_match" .= bqMin
2849− , "boost" .= boost
2850− , "disable_coord" .= disableCoord ]
2851−
2852−instance FromJSON BoolQuery where
2853− parseJSON = withObject "BoolQuery" parse
2854− where parse o = BoolQuery
2855− <$> o .:? "must" .!= []
2856− <*> o .:? "must_not" .!= []
2857− <*> o .:? "should" .!= []
2858− <*> o .:? "minimum_should_match"
2859− <*> o .:? "boost"
2860− <*> o .:? "disable_coord"
2861−
2862−instance ToJSON MatchQuery where
2863− toJSON (MatchQuery (FieldName fieldName)
2864− (QueryString mqQueryString) booleanOperator
2865− zeroTermsQuery cutoffFrequency matchQueryType
2866− analyzer maxExpansions lenient boost) =
2867− object [ fieldName .= omitNulls base ]
2868− where base = [ "query" .= mqQueryString
2869− , "operator" .= booleanOperator
2870− , "zero_terms_query" .= zeroTermsQuery
2871− , "cutoff_frequency" .= cutoffFrequency
2872− , "type" .= matchQueryType
2873− , "analyzer" .= analyzer
2874− , "max_expansions" .= maxExpansions
2875− , "lenient" .= lenient
2876− , "boost" .= boost ]
2877−
2878−instance FromJSON MatchQuery where
2879− parseJSON = withObject "MatchQuery" parse
2880− where parse = fieldTagged $ \fn o ->
2881− MatchQuery fn
2882− <$> o .: "query"
2883− <*> o .: "operator"
2884− <*> o .: "zero_terms_query"
2885− <*> o .:? "cutoff_frequency"
2886− <*> o .:? "type"
2887− <*> o .:? "analyzer"
2888− <*> o .:? "max_expansions"
2889− <*> o .:? "lenient"
2890− <*> o .:? "boost"
2891−
2892−instance ToJSON MultiMatchQuery where
2893− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2894− ztQ tb mmqt cf analyzer maxEx lenient) =
2895− object ["multi_match" .= omitNulls base]
2896− where base = [ "fields" .= fmap toJSON fields
2897− , "query" .= query
2898− , "operator" .= boolOp
2899− , "zero_terms_query" .= ztQ
2900− , "tiebreaker" .= tb
2901− , "type" .= mmqt
2902− , "cutoff_frequency" .= cf
2903− , "analyzer" .= analyzer
2904− , "max_expansions" .= maxEx
2905− , "lenient" .= lenient ]
2906−
2907−instance FromJSON MultiMatchQuery where
2908− parseJSON = withObject "MultiMatchQuery" parse
2909− where parse raw = do o <- raw .: "multi_match"
2910− MultiMatchQuery
2911− <$> o .:? "fields" .!= []
2912− <*> o .: "query"
2913− <*> o .: "operator"
2914− <*> o .: "zero_terms_query"
2915− <*> o .:? "tiebreaker"
2916− <*> o .:? "type"
2917− <*> o .:? "cutoff_frequency"
2918− <*> o .:? "analyzer"
2919− <*> o .:? "max_expansions"
2920− <*> o .:? "lenient"
2921−
2922−instance ToJSON MultiMatchQueryType where
2923− toJSON MultiMatchBestFields = "best_fields"
2924− toJSON MultiMatchMostFields = "most_fields"
2925− toJSON MultiMatchCrossFields = "cross_fields"
2926− toJSON MultiMatchPhrase = "phrase"
2927− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2928−
2929−instance FromJSON MultiMatchQueryType where
2930− parseJSON = withText "MultiMatchPhrasePrefix" parse
2931− where parse "best_fields" = pure MultiMatchBestFields
2932− parse "most_fields" = pure MultiMatchMostFields
2933− parse "cross_fields" = pure MultiMatchCrossFields
2934− parse "phrase" = pure MultiMatchPhrase
2935− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2936− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2937−
2938−instance ToJSON BooleanOperator where
2939− toJSON And = String "and"
2940− toJSON Or = String "or"
2941−
2942−instance FromJSON BooleanOperator where
2943− parseJSON = withText "BooleanOperator" parse
2944− where parse "and" = pure And
2945− parse "or" = pure Or
2946− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2947−
2948−instance ToJSON ZeroTermsQuery where
2949− toJSON ZeroTermsNone = String "none"
2950− toJSON ZeroTermsAll = String "all"
2951−
2952−instance FromJSON ZeroTermsQuery where
2953− parseJSON = withText "ZeroTermsQuery" parse
2954− where parse "none" = pure ZeroTermsNone
2955− parse "all" = pure ZeroTermsAll
2956− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2957−
2958−instance ToJSON MatchQueryType where
2959− toJSON MatchPhrase = "phrase"
2960− toJSON MatchPhrasePrefix = "phrase_prefix"
2961−
2962−instance FromJSON MatchQueryType where
2963− parseJSON = withText "MatchQueryType" parse
2964− where parse "phrase" = pure MatchPhrase
2965− parse "phrase_prefix" = pure MatchPhrasePrefix
2966− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2967−
2968−instance FromJSON Status where
2969− parseJSON (Object v) = Status <$>
2970− v .:? "ok" <*>
2971− v .: "status" <*>
2972− v .: "name" <*>
2973− v .: "version" <*>
2974− v .: "tagline"
2975− parseJSON _ = empty
2976−
2977−
2978−instance ToJSON IndexSettings where
2979− toJSON (IndexSettings s r) = object ["settings" .=
2980− object ["index" .=
2981− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2982− ]
2983− ]
2984−
2985−instance FromJSON IndexSettings where
2986− parseJSON = withObject "IndexSettings" parse
2987− where parse o = do s <- o .: "settings"
2988− i <- s .: "index"
2989− IndexSettings <$> i .: "number_of_shards"
2990− <*> i .: "number_of_replicas"
2991−
2992−instance ToJSON UpdatableIndexSetting where
2993− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2994− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2995− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2996− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2997− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2998− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2999− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
3000− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
3001− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
3002− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
3003− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
3004− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
3005− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
3006− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
3007− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
3008− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
3009− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
3010− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
3011− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
3012− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
3013− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
3014− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
3015− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
3016− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
3017− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
3018− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
3019− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
3020− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
3021−
3022−instance FromJSON UpdatableIndexSetting where
3023− parseJSON = withObject "UpdatableIndexSetting" parse
3024− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
3025− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
3026− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
3027− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
3028− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
3029− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
3030− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
3031− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
3032− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
3033− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
3034− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
3035− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
3036− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
3037− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
3038− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
3039− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
3040− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
3041− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
3042− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
3043− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
3044− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
3045− <|> compoundFormat `taggedAt` ["index", "compound_format"]
3046− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
3047− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
3048− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
3049− <|> blocksRead `taggedAt` ["blocks", "read"]
3050− <|> blocksWrite `taggedAt` ["blocks", "write"]
3051− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
3052− where taggedAt f ks = taggedAt' f (Object o) ks
3053− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
3054− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
3055− taggedAt' f v' ks) v
3056− numberOfReplicas = pure . NumberOfReplicas
3057− autoExpandReplicas = pure . AutoExpandReplicas
3058− refreshInterval = pure . RefreshInterval . ndtJSON
3059− indexConcurrency = pure . IndexConcurrency
3060− failOnMergeFailure = pure . FailOnMergeFailure
3061− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
3062− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
3063− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
3064− translogDisableFlush = pure . TranslogDisableFlush
3065− cacheFilterMaxSize = pure . CacheFilterMaxSize
3066− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
3067− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
3068− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
3069− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
3070− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
3071− routingAllocationEnable = pure . RoutingAllocationEnable
3072− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
3073− recoveryInitialShards = pure . RecoveryInitialShards
3074− gcDeletes = pure . GCDeletes . ndtJSON
3075− ttlDisablePurge = pure . TTLDisablePurge
3076− translogFSType = pure . TranslogFSType
3077− compoundFormat = pure . IndexCompoundFormat
3078− compoundOnFlush = pure . IndexCompoundOnFlush
3079− warmerEnabled = pure . WarmerEnabled
3080− blocksReadOnly = pure . BlocksReadOnly
3081− blocksRead = pure . BlocksRead
3082− blocksWrite = pure . BlocksWrite
3083− blocksMetaData = pure . BlocksMetaData
3084−
3085−instance FromJSON IndexSettingsSummary where
3086− parseJSON = withObject "IndexSettingsSummary" parse
3087− where parse o = case HM.toList o of
3088− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
3089− <$> parseJSON v
3090− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
3091− _ -> fail "Expected single-key object with index name"
3092− redundant (NumberOfReplicas _) = True
3093− redundant _ = False
3094−
3095−-- | For some reason in several settings APIs, all leaf values get returned
3096−-- as strings. This function attepmts to recover from this for all
3097−-- non-recursive JSON types. If nothing can be done, the value is left alone.
3098−unStringlyTypeJSON :: Value -> Value
3099−unStringlyTypeJSON (String "true") = Bool True
3100−unStringlyTypeJSON (String "false") = Bool False
3101−unStringlyTypeJSON (String "null") = Null
3102−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3103− Just n -> Number n
3104− Nothing -> v
3105−unStringlyTypeJSON v = v
3106−
3107−
3108−parseSettings :: Object -> Parser [UpdatableIndexSetting]
3109−parseSettings o = do
3110− o' <- o .: "index"
3111− -- slice the index object into singleton hashmaps and try to parse each
3112− parses <- forM (HM.toList o') $ \(k, v) -> do
3113− -- blocks are now nested into the "index" key, which is not how they're serialized
3114− let atRoot = Object (HM.singleton k v)
3115− let atIndex = Object (HM.singleton "index" atRoot)
3116− optional (parseJSON atRoot <|> parseJSON atIndex)
3117− return (catMaybes parses)
3118−
3119−oPath :: ToJSON a => NonEmpty Text -> a -> Value
3120−oPath (k :| []) v = object [k .= v]
3121−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
3122−
3123−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
3124−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
3125− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
3126−
3127−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
3128−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
3129− where parse o = case HM.toList o of
3130− [] -> fail "Expected non-empty list of NodeAttrFilters"
3131− x:xs -> DT.mapM (uncurry parse') (x :| xs)
3132− parse' n = withText "Text" $ \t ->
3133− case T.splitOn "," t of
3134− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
3135− [] -> fail "Expected non-empty list of filter values"
3136−
3137−instance ToJSON ReplicaBounds where
3138− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
3139− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
3140− toJSON ReplicasUnbounded = Bool False
3141−
3142−instance FromJSON ReplicaBounds where
3143− parseJSON v = withText "ReplicaBounds" parseText v
3144− <|> withBool "ReplicaBounds" parseBool v
3145− where parseText t = case T.splitOn "-" t of
3146− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
3147− [a, b] -> ReplicasBounded <$> parseReadText a
3148− <*> parseReadText b
3149− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
3150− parseBool False = pure ReplicasUnbounded
3151− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
3152−
3153−instance ToJSON AllocationPolicy where
3154− toJSON AllocAll = String "all"
3155− toJSON AllocPrimaries = String "primaries"
3156− toJSON AllocNewPrimaries = String "new_primaries"
3157− toJSON AllocNone = String "none"
3158−
3159−instance FromJSON AllocationPolicy where
3160− parseJSON = withText "AllocationPolicy" parse
3161− where parse "all" = pure AllocAll
3162− parse "primaries" = pure AllocPrimaries
3163− parse "new_primaries" = pure AllocNewPrimaries
3164− parse "none" = pure AllocNone
3165− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3166−
3167−instance ToJSON InitialShardCount where
3168− toJSON QuorumShards = String "quorum"
3169− toJSON QuorumMinus1Shards = String "quorum-1"
3170− toJSON FullShards = String "full"
3171− toJSON FullMinus1Shards = String "full-1"
3172− toJSON (ExplicitShards x) = toJSON x
3173−
3174−instance FromJSON InitialShardCount where
3175− parseJSON v = withText "InitialShardCount" parseText v
3176− <|> ExplicitShards <$> parseJSON v
3177− where parseText "quorum" = pure QuorumShards
3178− parseText "quorum-1" = pure QuorumMinus1Shards
3179− parseText "full" = pure FullShards
3180− parseText "full-1" = pure FullMinus1Shards
3181− parseText _ = mzero
3182−
3183−instance ToJSON FSType where
3184− toJSON FSSimple = "simple"
3185− toJSON FSBuffered = "buffered"
3186−
3187−instance FromJSON FSType where
3188− parseJSON = withText "FSType" parse
3189− where parse "simple" = pure FSSimple
3190− parse "buffered" = pure FSBuffered
3191− parse t = fail ("Invalid FSType: " <> show t)
3192−
3193−instance ToJSON CompoundFormat where
3194− toJSON (CompoundFileFormat x) = Bool x
3195− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3196−
3197−instance FromJSON CompoundFormat where
3198− parseJSON v = CompoundFileFormat <$> parseJSON v
3199− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3200−
3201−instance ToJSON NominalDiffTimeJSON where
3202− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3203−
3204−instance FromJSON NominalDiffTimeJSON where
3205− parseJSON = withText "NominalDiffTime" parse
3206− where parse t = case T.takeEnd 1 t of
3207− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3208− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3209−
3210−instance ToJSON IndexTemplate where
3211− toJSON (IndexTemplate p s m) = merge
3212− (object [ "template" .= p
3213− , "mappings" .= foldl' merge (object []) m
3214− ])
3215− (toJSON s)
3216− where
3217− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3218− merge o Null = o
3219− merge _ _ = undefined
3220−
3221−instance (FromJSON a) => FromJSON (EsResult a) where
3222− parseJSON jsonVal@(Object v) = do
3223− found <- v .:? "found" .!= False
3224− fr <- if found
3225− then parseJSON jsonVal
3226− else return Nothing
3227− EsResult <$> v .: "_index" <*>
3228− v .: "_type" <*>
3229− v .: "_id" <*>
3230− pure fr
3231− parseJSON _ = empty
3232−
3233−instance (FromJSON a) => FromJSON (EsResultFound a) where
3234− parseJSON (Object v) = EsResultFound <$>
3235− v .: "_version" <*>
3236− v .: "_source"
3237− parseJSON _ = empty
3238−
3239−instance FromJSON EsError where
3240− parseJSON (Object v) = EsError <$>
3241− v .: "status" <*>
3242− v .: "error"
3243− parseJSON _ = empty
3244−
3245−instance FromJSON IndexAliasesSummary where
3246− parseJSON = withObject "IndexAliasesSummary" parse
3247− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3248− go ixn = withObject "index aliases" $ \ia -> do
3249− aliases <- ia .:? "aliases" .!= mempty
3250− forM (HM.toList aliases) $ \(aName, v) -> do
3251− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3252− IndexAliasSummary indexAlias <$> parseJSON v
3253−
3254−
3255−instance ToJSON IndexAliasAction where
3256− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3257− where Object iaObj = toJSON ia
3258− Object optsObj = toJSON opts
3259− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3260− where Object iaObj = toJSON ia
3261−
3262−instance ToJSON IndexAlias where
3263− toJSON IndexAlias {..} = object ["index" .= srcIndex
3264− , "alias" .= indexAlias
3265− ]
3266−
3267−instance ToJSON IndexAliasCreate where
3268− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3269− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3270− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3271−
3272−instance ToJSON AliasRouting where
3273− toJSON (AllAliasRouting v) = object ["routing" .= v]
3274− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3275− where prs = [("search_routing" .=) <$> srch
3276− ,("index_routing" .=) <$> idx]
3277−
3278−instance FromJSON AliasRouting where
3279− parseJSON = withObject "AliasRouting" parse
3280− where parse o = parseAll o <|> parseGranular o
3281− parseAll o = AllAliasRouting <$> o .: "routing"
3282− parseGranular o = do
3283− sr <- o .:? "search_routing"
3284− ir <- o .:? "index_routing"
3285− if isNothing sr && isNothing ir
3286− then fail "Both search_routing and index_routing can't be blank"
3287− else return (GranularAliasRouting sr ir)
3288−
3289−instance FromJSON IndexAliasCreate where
3290− parseJSON v = withObject "IndexAliasCreate" parse v
3291− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3292− <*> o .:? "filter"
3293−
3294−instance ToJSON SearchAliasRouting where
3295− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3296−
3297−instance FromJSON SearchAliasRouting where
3298− parseJSON = withText "SearchAliasRouting" parse
3299− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3300−
3301−instance ToJSON Search where
3302− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3303− omitNulls [ "query" .= query
3304− , "filter" .= sFilter
3305− , "sort" .= sort
3306− , "aggregations" .= searchAggs
3307− , "highlight" .= highlight
3308− , "from" .= sFrom
3309− , "size" .= sSize
3310− , "track_scores" .= sTrackSortScores
3311− , "fields" .= sFields
3312− , "_source" .= sSource]
3313−
3314−
3315−instance ToJSON Source where
3316− toJSON NoSource = toJSON False
3317− toJSON (SourcePatterns patterns) = toJSON patterns
3318− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3319−
3320−instance ToJSON PatternOrPatterns where
3321− toJSON (PopPattern pattern) = toJSON pattern
3322− toJSON (PopPatterns patterns) = toJSON patterns
3323−
3324−instance ToJSON Include where
3325− toJSON (Include patterns) = toJSON patterns
3326−
3327−instance ToJSON Exclude where
3328− toJSON (Exclude patterns) = toJSON patterns
3329−
3330−instance ToJSON Pattern where
3331− toJSON (Pattern pattern) = toJSON pattern
3332−
3333−
3334−instance ToJSON FieldHighlight where
3335− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3336− object [ fName .= fSettings ]
3337− toJSON (FieldHighlight (FieldName fName) Nothing) =
3338− object [ fName .= emptyObject ]
3339−
3340−instance ToJSON Highlights where
3341− toJSON (Highlights global fields) =
3342− omitNulls (("fields" .= fields)
3343− : highlightSettingsPairs global)
3344−
3345−instance ToJSON HighlightSettings where
3346− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3347−
3348−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3349−highlightSettingsPairs Nothing = []
3350−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3351−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3352−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3353−
3354−
3355−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3356−plainHighPairs Nothing = []
3357−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3358− [ "type" .= String "plain"]
3359− ++ commonHighlightPairs plCom
3360− ++ nonPostingsToPairs plNonPost
3361−
3362−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3363−postHighPairs Nothing = []
3364−postHighPairs (Just (PostingsHighlight pCom)) =
3365− ("type" .= String "postings")
3366− : commonHighlightPairs pCom
3367−
3368−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3369−fastVectorHighPairs Nothing = []
3370−fastVectorHighPairs (Just
3371− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3372− fvBoundMaxScan fvFragOff fvMatchedFields
3373− fvPhraseLim)) =
3374− [ "type" .= String "fvh"
3375− , "boundary_chars" .= fvBoundChars
3376− , "boundary_max_scan" .= fvBoundMaxScan
3377− , "fragment_offset" .= fvFragOff
3378− , "matched_fields" .= fvMatchedFields
3379− , "phraseLimit" .= fvPhraseLim]
3380− ++ commonHighlightPairs fvCom
3381− ++ nonPostingsToPairs fvNonPostSettings
3382−
3383−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3384−deleteSeveral ks hm = foldr HM.delete hm ks
3385−
3386−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3387−commonHighlightPairs Nothing = []
3388−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3389− chNoMatchSize chHighlightQuery
3390− chRequireFieldMatch)) =
3391− [ "order" .= chScore
3392− , "force_source" .= chForceSource
3393− , "encoder" .= chEncoder
3394− , "no_match_size" .= chNoMatchSize
3395− , "highlight_query" .= chHighlightQuery
3396− , "require_fieldMatch" .= chRequireFieldMatch]
3397− ++ highlightTagToPairs chTag
3398−
3399−
3400−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3401−nonPostingsToPairs Nothing = []
3402−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3403− [ "fragment_size" .= npFragSize
3404− , "number_of_fragments" .= npNumOfFrags]
3405−
3406−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3407−parseNEJSON [] = fail "Expected non-empty list"
3408−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3409−
3410−
3411−instance ToJSON HighlightEncoder where
3412− toJSON DefaultEncoder = String "default"
3413− toJSON HTMLEncoder = String "html"
3414−
3415−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3416−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3417−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3418− , "post_tags" .= post]
3419−highlightTagToPairs Nothing = []
3420−
3421−instance ToJSON SortSpec where
3422− toJSON (DefaultSortSpec
3423− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3424− dsSortMode dsMissingSort dsNestedFilter)) =
3425− object [dsSortFieldName .= omitNulls base] where
3426− base = [ "order" .= dsSortOrder
3427− , "ignore_unmapped" .= dsIgnoreUnmapped
3428− , "mode" .= dsSortMode
3429− , "missing" .= dsMissingSort
3430− , "nested_filter" .= dsNestedFilter ]
3431−
3432− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3433− object [ "unit" .= units
3434− , field .= gdsLatLon
3435− , "order" .= gdsSortOrder ]
3436−
3437−
3438−instance ToJSON SortOrder where
3439− toJSON Ascending = String "asc"
3440− toJSON Descending = String "desc"
3441−
3442−
3443−instance ToJSON SortMode where
3444− toJSON SortMin = String "min"
3445− toJSON SortMax = String "max"
3446− toJSON SortSum = String "sum"
3447− toJSON SortAvg = String "avg"
3448−
3449−
3450−instance ToJSON Missing where
3451− toJSON LastMissing = String "_last"
3452− toJSON FirstMissing = String "_first"
3453− toJSON (CustomMissing txt) = String txt
3454−
3455−
3456−instance ToJSON ScoreType where
3457− toJSON ScoreTypeMax = "max"
3458− toJSON ScoreTypeAvg = "avg"
3459− toJSON ScoreTypeSum = "sum"
3460− toJSON ScoreTypeNone = "none"
3461−
3462−instance FromJSON ScoreType where
3463− parseJSON = withText "ScoreType" parse
3464− where parse "max" = pure ScoreTypeMax
3465− parse "avg" = pure ScoreTypeAvg
3466− parse "sum" = pure ScoreTypeSum
3467− parse "none" = pure ScoreTypeNone
3468− parse t = fail ("Unexpected ScoreType: " <> show t)
3469−
3470−instance ToJSON Distance where
3471− toJSON (Distance dCoefficient dUnit) =
3472− String boltedTogether where
3473− coefText = showText dCoefficient
3474− (String unitText) = toJSON dUnit
3475− boltedTogether = mappend coefText unitText
3476−
3477−instance FromJSON Distance where
3478− parseJSON = withText "Distance" parse
3479− where parse t = Distance <$> parseCoeff nT
3480− <*> parseJSON (String unitT)
3481− where (nT, unitT) = T.span validForNumber t
3482− -- may be a better way to do this
3483− validForNumber '-' = True
3484− validForNumber '.' = True
3485− validForNumber 'e' = True
3486− validForNumber c = isNumber c
3487− parseCoeff "" = fail "Empty string cannot be parsed as number"
3488− parseCoeff s = return (read (T.unpack s))
3489−
3490−instance ToJSON DistanceUnit where
3491− toJSON Miles = String "mi"
3492− toJSON Yards = String "yd"
3493− toJSON Feet = String "ft"
3494− toJSON Inches = String "in"
3495− toJSON Kilometers = String "km"
3496− toJSON Meters = String "m"
3497− toJSON Centimeters = String "cm"
3498− toJSON Millimeters = String "mm"
3499− toJSON NauticalMiles = String "nmi"
3500−
3501−
3502−instance FromJSON DistanceUnit where
3503− parseJSON = withText "DistanceUnit" parse
3504− where parse "mi" = pure Miles
3505− parse "yd" = pure Yards
3506− parse "ft" = pure Feet
3507− parse "in" = pure Inches
3508− parse "km" = pure Kilometers
3509− parse "m" = pure Meters
3510− parse "cm" = pure Centimeters
3511− parse "mm" = pure Millimeters
3512− parse "nmi" = pure NauticalMiles
3513− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3514−
3515−instance ToJSON DistanceType where
3516− toJSON Arc = String "arc"
3517− toJSON SloppyArc = String "sloppy_arc"
3518− toJSON Plane = String "plane"
3519−
3520−instance FromJSON DistanceType where
3521− parseJSON = withText "DistanceType" parse
3522− where parse "arc" = pure Arc
3523− parse "sloppy_arc" = pure SloppyArc
3524− parse "plane" = pure Plane
3525− parse t = fail ("Unrecognized DistanceType: " <> show t)
3526−
3527−
3528−instance ToJSON OptimizeBbox where
3529− toJSON NoOptimizeBbox = String "none"
3530− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3531−
3532−instance FromJSON OptimizeBbox where
3533− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3534− <|> parseOptimize v
3535− where parseNoOptimize "none" = pure NoOptimizeBbox
3536− parseNoOptimize _ = mzero
3537− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3538−
3539−instance ToJSON GeoBoundingBoxConstraint where
3540− toJSON (GeoBoundingBoxConstraint
3541− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3542− object [gbbcGeoBBField .= gbbcConstraintBox
3543− , "_cache" .= cache
3544− , "type" .= type']
3545−
3546−instance FromJSON GeoBoundingBoxConstraint where
3547− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3548− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3549− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3550− <$> parseJSON v
3551− <*> o .:? "_cache" .!= defaultCache
3552− <*> o .: "type"
3553− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3554−
3555−instance ToJSON GeoFilterType where
3556− toJSON GeoFilterMemory = String "memory"
3557− toJSON GeoFilterIndexed = String "indexed"
3558−
3559−instance FromJSON GeoFilterType where
3560− parseJSON = withText "GeoFilterType" parse
3561− where parse "memory" = pure GeoFilterMemory
3562− parse "indexed" = pure GeoFilterIndexed
3563− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3564−
3565−instance ToJSON GeoBoundingBox where
3566− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3567− object ["top_left" .= gbbTopLeft
3568− , "bottom_right" .= gbbBottomRight]
3569−
3570−instance FromJSON GeoBoundingBox where
3571− parseJSON = withObject "GeoBoundingBox" parse
3572− where parse o = GeoBoundingBox
3573− <$> o .: "top_left"
3574− <*> o .: "bottom_right"
3575−
3576−instance ToJSON LatLon where
3577− toJSON (LatLon lLat lLon) =
3578− object ["lat" .= lLat
3579− , "lon" .= lLon]
3580−
3581−instance FromJSON LatLon where
3582− parseJSON = withObject "LatLon" parse
3583− where parse o = LatLon <$> o .: "lat"
3584− <*> o .: "lon"
3585−
3586−-- index for smaller ranges, fielddata for longer ranges
3587−instance ToJSON RangeExecution where
3588− toJSON RangeExecutionIndex = "index"
3589− toJSON RangeExecutionFielddata = "fielddata"
3590−
3591−
3592−instance FromJSON RangeExecution where
3593− parseJSON = withText "RangeExecution" parse
3594− where parse "index" = pure RangeExecutionIndex
3595− parse "fielddata" = pure RangeExecutionFielddata
3596− parse t = error ("Unrecognized RangeExecution " <> show t)
3597−
3598−instance ToJSON RegexpFlags where
3599− toJSON AllRegexpFlags = String "ALL"
3600− toJSON NoRegexpFlags = String "NONE"
3601− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3602− where flagStrs = map flagStr . nub $ h:fs
3603− flagStr AnyString = "ANYSTRING"
3604− flagStr Automaton = "AUTOMATON"
3605− flagStr Complement = "COMPLEMENT"
3606− flagStr Empty = "EMPTY"
3607− flagStr Intersection = "INTERSECTION"
3608− flagStr Interval = "INTERVAL"
3609−
3610−instance FromJSON RegexpFlags where
3611− parseJSON = withText "RegexpFlags" parse
3612− where parse "ALL" = pure AllRegexpFlags
3613− parse "NONE" = pure NoRegexpFlags
3614− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3615−
3616−instance FromJSON RegexpFlag where
3617− parseJSON = withText "RegexpFlag" parse
3618− where parse "ANYSTRING" = pure AnyString
3619− parse "AUTOMATON" = pure Automaton
3620− parse "COMPLEMENT" = pure Complement
3621− parse "EMPTY" = pure Empty
3622− parse "INTERSECTION" = pure Intersection
3623− parse "INTERVAL" = pure Interval
3624− parse f = fail ("Unknown RegexpFlag: " <> show f)
3625−
3626−instance ToJSON Term where
3627− toJSON (Term field value) = object ["term" .= object
3628− [field .= value]]
3629−
3630−instance FromJSON Term where
3631− parseJSON = withObject "Term" parse
3632− where parse o = do termObj <- o .: "term"
3633− case HM.toList termObj of
3634− [(fn, v)] -> Term fn <$> parseJSON v
3635− _ -> fail "Expected object with 1 field-named key"
3636−
3637−instance ToJSON BoolMatch where
3638− toJSON (MustMatch term cache) = object ["must" .= term,
3639− "_cache" .= cache]
3640− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3641− "_cache" .= cache]
3642− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3643− "_cache" .= cache]
3644−
3645−instance FromJSON BoolMatch where
3646− parseJSON = withObject "BoolMatch" parse
3647− where parse o = mustMatch `taggedWith` "must"
3648− <|> mustNotMatch `taggedWith` "must_not"
3649− <|> shouldMatch `taggedWith` "should"
3650− where taggedWith parser k = parser =<< o .: k
3651− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3652− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3653− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
522+ , scrollId :: Maybe ScrollId
523+ -- ^ Only one Suggestion request / response per
524+ -- Search is supported.
525+ , suggest :: Maybe NamedSuggestionResponse
526+ }
527+ deriving (Eq, Show)
3654528
3655529instance (FromJSON a) => FromJSON (SearchResult a) where
3656530 parseJSON (Object v) = SearchResult <$>
@@ -3659,663 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3659533 v .: "_shards" <*>
3660534 v .: "hits" <*>
3661535 v .:? "aggregations" <*>
3662− v .:? "_scroll_id"
3663− parseJSON _ = empty
3664−
3665−instance (FromJSON a) => FromJSON (SearchHits a) where
3666− parseJSON (Object v) = SearchHits <$>
3667− v .: "total" <*>
3668− v .: "max_score" <*>
3669− v .: "hits"
3670− parseJSON _ = empty
3671−
3672−instance (FromJSON a) => FromJSON (Hit a) where
3673− parseJSON (Object v) = Hit <$>
3674− v .: "_index" <*>
3675− v .: "_type" <*>
3676− v .: "_id" <*>
3677− v .: "_score" <*>
3678− v .:? "_source" <*>
3679− v .:? "highlight"
3680− parseJSON _ = empty
3681−
3682−instance FromJSON ShardResult where
3683− parseJSON (Object v) = ShardResult <$>
3684− v .: "total" <*>
3685− v .: "successful" <*>
3686− v .: "failed"
536+ v .:? "_scroll_id" <*>
537+ v .:? "suggest"
3687538 parseJSON _ = empty
3688539
3689−
3690−instance FromJSON DocVersion where
3691− parseJSON v = do
3692− i <- parseJSON v
3693− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3694−
3695−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3696−instance FromJSON ReplicaCount where
3697− parseJSON v = parseAsInt v
3698− <|> parseAsString v
3699− where parseAsInt = fmap ReplicaCount . parseJSON
3700− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3701−
3702−instance FromJSON ShardCount where
3703− parseJSON v = parseAsInt v
3704− <|> parseAsString v
3705− where parseAsInt = fmap ShardCount . parseJSON
3706− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3707−
3708−instance Bounded DocVersion where
3709− minBound = DocVersion 1
3710− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3711−
3712−instance Enum DocVersion where
3713− succ x
3714− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3715− | otherwise = succError "DocVersion"
3716− pred x
3717− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3718− | otherwise = predError "DocVersion"
3719− toEnum i =
3720− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3721− fromEnum = docVersionNumber
3722− enumFrom = boundedEnumFrom
3723− enumFromThen = boundedEnumFromThen
3724−
3725−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3726−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3727−
3728−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3729−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3730−
3731−
3732−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3733− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3734−
3735−
3736−-- | Either specifies an exact repo name or one with globs in it,
3737−-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3738−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3739− | RepoPattern Text
3740− deriving (Eq, Generic, Show, Typeable)
3741−
3742−-- | The unique name of a snapshot repository.
3743−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3744− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3745−
3746−
3747−-- | A generic representation of a snapshot repo. This is what gets
3748−-- sent to and parsed from the server. For repo types enabled by
3749−-- plugins that aren't exported by this library, consider making a
3750−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3751−-- type, consider submitting a pull request to have it included in the
3752−-- library proper
3753−data GenericSnapshotRepo = GenericSnapshotRepo {
3754− gSnapshotRepoName :: SnapshotRepoName
3755− , gSnapshotRepoType :: SnapshotRepoType
3756− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3757− } deriving (Eq, Generic, Show, Typeable)
3758−
3759−
3760−instance SnapshotRepo GenericSnapshotRepo where
3761− toGSnapshotRepo = id
3762− fromGSnapshotRepo = Right
3763−
3764−
3765−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3766− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3767−
3768−
3769−-- | Opaque representation of snapshot repo settings. Instances of
3770−-- 'SnapshotRepo' will produce this.
3771−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3772− deriving (Eq, Generic, Show, Typeable, ToJSON)
3773−
3774−
3775− -- Regardless of whether you send strongly typed json, my version of
3776− -- ES sends back stringly typed json in the settings, e.g. booleans
3777− -- as strings, so we'll try to convert them.
3778−instance FromJSON GenericSnapshotRepoSettings where
3779− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3780−
3781−-- | The result of running 'verifySnapshotRepo'.
3782−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3783− deriving (Eq, Generic, Show, Typeable)
3784−
3785−
3786−instance FromJSON SnapshotVerification where
3787− parseJSON = withObject "SnapshotVerification" parse
3788− where
3789− parse o = do
3790− o2 <- o .: "nodes"
3791− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3792− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3793− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3794−
3795−
3796−-- | A node that has verified a snapshot
3797−data SnapshotNodeVerification = SnapshotNodeVerification {
3798− snvFullId :: FullNodeId
3799− , snvNodeName :: NodeName
3800− } deriving (Eq, Generic, Show, Typeable)
3801−
3802−
3803−-- | Unique, automatically-generated name assigned to nodes that are
3804−-- usually returned in node-oriented APIs.
3805−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3806− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3807−
3808−
3809−-- | A human-readable node name that is supplied by the user in the
3810−-- node config or automatically generated by ElasticSearch.
3811−newtype NodeName = NodeName { nodeName :: Text }
3812− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3813−
3814−newtype ClusterName = ClusterName { clusterName :: Text }
3815− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3816−
3817−data NodesInfo = NodesInfo {
3818− nodesInfo :: [NodeInfo]
3819− , nodesClusterName :: ClusterName
3820− } deriving (Eq, Show, Generic, Typeable)
3821−
3822−-- | A quirky address format used throughout ElasticSearch. An example
3823−-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
3824−-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
3825−newtype EsAddress = EsAddress { esAddress :: Text }
3826− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3827−
3828−-- | Typically a 7 character hex string.
3829−newtype BuildHash = BuildHash { buildHash :: Text }
3830− deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
3831−
3832−newtype PluginName = PluginName { pluginName :: Text }
3833− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3834−
3835−data NodeInfo = NodeInfo {
3836− nodeInfoHTTPAddress :: EsAddress --TODO: better name
3837− , nodeInfoBuild :: BuildHash
3838− , nodeInfoESVersion :: VersionNumber --TODO: distribution provides this
3839− , nodeInfoIP :: Server
3840− , nodeInfoHost :: Server
3841− , nodeInfoTransportAddress :: EsAddress
3842− , nodeInfoName :: NodeName
3843− , nodeInfoFullId :: FullNodeId
3844− , nodeInfoPlugins :: [NodePluginInfo]
3845− , nodeInfoHTTP :: NodeHTTPInfo
3846− , nodeInfoTransport :: NodeTransportInfo
3847− , nodeInfoNetwork :: NodeNetworkInfo
3848− , nodeInfoThreadPool :: NodeThreadPoolsInfo
3849− , nodeInfoJVM :: NodeJVMInfo
3850− , nodeInfoProcess :: NodeProcessInfo
3851− , nodeInfoOS :: NodeOSInfo
3852− } deriving (Eq, Show, Generic, Typeable)
3853−
3854−data NodePluginInfo = NodePluginInfo {
3855− nodePluginSite :: Bool
3856− -- ^ Is this a site plugin?
3857− , nodePluginJVM :: Bool
3858− -- ^ Is this plugin running on the JVM
3859− , nodePluginDescription :: Text
3860− , nodePluginVersion :: VersionNumber
3861− , nodePluginName :: PluginName
3862− } deriving (Eq, Show, Generic, Typeable)
3863−
3864−data NodeHTTPInfo = NodeHTTPInfo {
3865− nodeHTTPMaxContentLength :: Bytes
3866− , nodeHTTPTransportAddress :: BoundTransportAddress
3867− } deriving (Eq, Show, Generic, Typeable)
3868−
3869−data NodeTransportInfo = NodeTransportInfo {
3870− nodeTransportProfiles :: [BoundTransportAddress] --TODO: bound transport/publish addresses, paper over NULL meaning []
3871− , nodeTransportAddress :: BoundTransportAddress
3872− } deriving (Eq, Show, Generic, Typeable)
3873−
3874−data BoundTransportAddress = BoundTransportAddress {
3875− publicAddress :: EsAddress
3876− , boundAddress :: EsAddress
3877− } deriving (Eq, Show, Generic, Typeable)
3878−
3879−data NodeNetworkInfo = NodeNetworkInfo {
3880− nodeNetworkPrimaryInterface :: NodeNetworkInterface
3881− , nodeNetworkRefreshInterval :: NominalDiffTime
3882− } deriving (Eq, Show, Generic, Typeable)
3883−
3884−newtype MacAddress = MacAddress { macAddress :: Text }
3885− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3886−
3887−newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
3888− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3889−
3890−data NodeNetworkInterface = NodeNetworkInterface {
3891− nodeNetIfaceMacAddress :: MacAddress
3892− , nodeNetIfaceName :: NetworkInterfaceName
3893− , nodeNetIfaceAddress :: Server
3894− } deriving (Eq, Show, Generic, Typeable)
3895−
3896−data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
3897− nodeThreadPoolsRefresh :: NodeThreadPoolInfo
3898− , nodeThreadPoolsManagement :: NodeThreadPoolInfo
3899− , nodeThreadPoolsPercolate :: NodeThreadPoolInfo
3900− , nodeThreadPoolsListener :: NodeThreadPoolInfo
3901− , nodeThreadPoolsFetchShardStarted :: NodeThreadPoolInfo
3902− , nodeThreadPoolsSearch :: NodeThreadPoolInfo
3903− , nodeThreadPoolsFlush :: NodeThreadPoolInfo
3904− , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
3905− , nodeThreadPoolsOptimize :: NodeThreadPoolInfo
3906− , nodeThreadPoolsBulk :: NodeThreadPoolInfo
3907− , nodeThreadPoolsSuggest :: NodeThreadPoolInfo
3908− , nodeThreadPoolsMerge :: NodeThreadPoolInfo
3909− , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
3910− , nodeThreadPoolsGet :: NodeThreadPoolInfo
3911− , nodeThreadPoolsFetchShardStore :: NodeThreadPoolInfo
3912− , nodeThreadPoolsIndex :: NodeThreadPoolInfo
3913− , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
3914− } deriving (Eq, Show, Generic, Typeable)
3915−
3916−data NodeThreadPoolInfo = NodeThreadPoolInfo {
3917− nodeThreadPoolQueueSize :: ThreadPoolSize
3918− , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
3919− , nodeThreadPoolMin :: Maybe Int
3920− , nodeThreadPoolMax :: Maybe Int
3921− , nodeThreadPoolType :: ThreadPoolType
3922− } deriving (Eq, Show, Generic, Typeable)
3923−
3924−data ThreadPoolSize = ThreadPoolLimited Int
3925− | ThreadPoolUnbounded
3926− deriving (Eq, Show, Generic, Typeable)
3927−
3928−data ThreadPoolType = ThreadPoolScaling
3929− | ThreadPoolFixed
3930− | ThreadPoolCached --TODO: are there others
3931− deriving (Eq, Show, Generic, Typeable)
3932−
3933−data NodeJVMInfo = NodeJVMInfo {
3934− nodeJVMInfoMemoryPools :: [JVMMemoryPool]
3935− , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
3936− , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
3937− , nodeJVMInfoStartTime :: UTCTime
3938− , nodeJVMInfoVMVendor :: Text
3939− , nodeJVMVMVersion :: VersionNumber
3940− -- ^ JVM doesn't seme to follow normal version conventions
3941− , nodeJVMVMName :: Text
3942− , nodeJVMVersion :: VersionNumber --TODO: normalize underscores
3943− , nodeJVMPID :: PID
3944− } deriving (Eq, Show, Generic, Typeable)
3945−
3946−data JVMMemoryInfo = JVMMemoryInfo {
3947− jvmMemoryInfoDirectMax :: Bytes
3948− , jvmMemoryInfoNonHeapMax :: Bytes
3949− , jvmMemoryInfoNonHeapInit :: Bytes
3950− , jvmMemoryInfoHeapMax :: Bytes
3951− , jvmMemoryInfoHeapInit :: Bytes
3952− } deriving (Eq, Show, Generic, Typeable)
3953−
3954−newtype JVMMemoryPool = JVMMemoryPool {
3955− jvmMemoryPool :: Text
3956− } deriving (Eq, Show, Generic, Typeable, FromJSON)
3957−
3958−newtype JVMGCCollector = JVMGCCollector {
3959− jvmGCCollector :: Text
3960− } deriving (Eq, Show, Generic, Typeable, FromJSON)
3961−
3962−newtype PID = PID {
3963− pid :: Int
3964− } deriving (Eq, Show, Generic, Typeable, FromJSON)
3965−
3966−data NodeOSInfo = NodeOSInfo {
3967− nodeOSSwap :: Bytes
3968− , nodeOSMem :: Bytes
3969− , nodeOSCPUInfo :: CPUInfo
3970− , nodeOSAvailableProcessors :: Int
3971− , nodeOSRefreshInterval :: NominalDiffTime
3972− } deriving (Eq, Show, Generic, Typeable)
3973−
3974−data CPUInfo = CPUInfo {
3975− cpuCacheSize :: Bytes
3976− , cpuCoresPerSocket :: Int
3977− , cpuTotalSockets :: Int
3978− , cpuTotalCores :: Int
3979− , cpuMHZ :: Int
3980− , cpuModel :: Text
3981− , cpuVendor :: Text
3982− } deriving (Eq, Show, Generic, Typeable)
3983−
3984−data NodeProcessInfo = NodeProcessInfo {
3985− nodeProcessMLockAll :: Bool
3986− -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
3987− , nodeProcessMaxFileDescriptors :: Int
3988− , nodeProcessId :: PID
3989− , nodeProcessRefreshInterval :: NominalDiffTime
3990− } deriving (Eq, Show, Generic, Typeable)
3991−
3992−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
3993− repoUpdateVerify :: Bool
3994− -- ^ After creation/update, synchronously check that nodes can
3995− -- write to this repo. Defaults to True. You may use False if you
3996− -- need a faster response and plan on verifying manually later
3997− -- with 'verifySnapshotRepo'.
3998− } deriving (Eq, Show, Generic, Typeable)
3999−
4000−
4001−-- | Reasonable defaults for repo creation/update
4002−--
4003−-- * repoUpdateVerify True
4004−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4005−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4006−
4007−
4008−-- | A filesystem-based snapshot repo that ships with
4009−-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4010−-- used with 'updateSnapshotRepo'
4011−data FsSnapshotRepo = FsSnapshotRepo {
4012− fsrName :: SnapshotRepoName
4013− , fsrLocation :: FilePath
4014− , fsrCompressMetadata :: Bool
4015− , fsrChunkSize :: Maybe Bytes
4016− -- ^ Size by which to split large files during snapshotting.
4017− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4018− -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4019− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4020− -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4021− } deriving (Eq, Generic, Show, Typeable)
4022−
4023−
4024−instance SnapshotRepo FsSnapshotRepo where
4025− toGSnapshotRepo FsSnapshotRepo {..} =
4026− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4027− where
4028− Object settings = object $ [ "location" .= fsrLocation
4029− , "compress" .= fsrCompressMetadata
4030− ] ++ optionalPairs
4031− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4032− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4033− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4034− ]
4035− fromGSnapshotRepo GenericSnapshotRepo {..}
4036− | gSnapshotRepoType == fsRepoType = do
4037− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4038− parseRepo $ do
4039− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4040− <*> o .:? "compress" .!= False
4041− <*> o .:? "chunk_size"
4042− <*> o .:? "max_restore_bytes_per_sec"
4043− <*> o .:? "max_snapshot_bytes_per_sec"
4044− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4045−
4046−
4047−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4048−parseRepo parser = case parseEither (const parser) () of
4049− Left e -> Left (OtherRepoConversionError (T.pack e))
4050− Right a -> Right a
4051−
4052−
4053−fsRepoType :: SnapshotRepoType
4054−fsRepoType = SnapshotRepoType "fs"
4055−
4056−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4057−class SnapshotRepo r where
4058− toGSnapshotRepo :: r -> GenericSnapshotRepo
4059− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4060−
4061−
4062−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4063− -- ^ Expected type and actual type
4064− | OtherRepoConversionError Text
4065− deriving (Show, Eq, Generic, Typeable)
4066−
4067−
4068−instance Exception SnapshotRepoConversionError
4069−
4070−
4071−data SnapshotCreateSettings = SnapshotCreateSettings {
4072− snapWaitForCompletion :: Bool
4073− -- ^ Should the API call return immediately after initializing
4074− -- the snapshot or wait until completed? Note that if this is
4075− -- enabled it could wait a long time, so you should adjust your
4076− -- 'ManagerSettings' accordingly to set long timeouts or
4077− -- explicitly handle timeouts.
4078− , snapIndices :: Maybe IndexSelection
4079− -- ^ Nothing will snapshot all indices. Just [] is permissable and
4080− -- will essentially be a no-op snapshot.
4081− , snapIgnoreUnavailable :: Bool
4082− -- ^ If set to True, any matched indices that don't exist will be
4083− -- ignored. Otherwise it will be an error and fail.
4084− , snapIncludeGlobalState :: Bool
4085− , snapPartial :: Bool
4086− -- ^ If some indices failed to snapshot (e.g. if not all primary
4087− -- shards are available), should the process proceed?
4088− } deriving (Eq, Generic, Show, Typeable)
4089−
4090−
4091−-- | Reasonable defaults for snapshot creation
4092−--
4093−-- * snapWaitForCompletion False
4094−-- * snapIndices Nothing
4095−-- * snapIgnoreUnavailable False
4096−-- * snapIncludeGlobalState True
4097−-- * snapPartial False
4098−defaultSnapshotCreateSettings :: SnapshotCreateSettings
4099−defaultSnapshotCreateSettings = SnapshotCreateSettings {
4100− snapWaitForCompletion = False
4101− , snapIndices = Nothing
4102− , snapIgnoreUnavailable = False
4103− , snapIncludeGlobalState = True
4104− , snapPartial = False
4105− }
4106−
4107−
4108−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4109− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4110−
4111−
4112−-- | Either specifies an exact snapshot name or one with globs in it,
4113−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4114−-- ES < 1.7
4115−data SnapshotPattern = ExactSnap SnapshotName
4116− | SnapPattern Text
4117− deriving (Eq, Generic, Show, Typeable)
4118−
4119−
4120−-- | General information about the state of a snapshot. Has some
4121−-- redundancies with 'SnapshotStatus'
4122−data SnapshotInfo = SnapshotInfo {
4123− snapInfoShards :: ShardResult
4124− , snapInfoFailures :: [SnapshotShardFailure]
4125− , snapInfoDuration :: NominalDiffTime
4126− , snapInfoEndTime :: UTCTime
4127− , snapInfoStartTime :: UTCTime
4128− , snapInfoState :: SnapshotState
4129− , snapInfoIndices :: [IndexName]
4130− , snapInfoName :: SnapshotName
4131− } deriving (Eq, Generic, Show, Typeable)
4132−
4133−
4134−instance FromJSON SnapshotInfo where
4135− parseJSON = withObject "SnapshotInfo" parse
4136− where
4137− parse o = SnapshotInfo <$> o .: "shards"
4138− <*> o .: "failures"
4139− <*> (unMS <$> o .: "duration_in_millis")
4140− <*> (posixMS <$> o .: "end_time_in_millis")
4141− <*> (posixMS <$> o .: "start_time_in_millis")
4142− <*> o .: "state"
4143− <*> o .: "indices"
4144− <*> o .: "snapshot"
4145−
4146−data SnapshotShardFailure = SnapshotShardFailure {
4147− snapShardFailureIndex :: IndexName
4148− , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4149− , snapShardFailureReason :: Text
4150− , snapShardFailureShardId :: ShardId
4151− } deriving (Eq, Show, Generic, Typeable)
4152−
4153−
4154−instance FromJSON SnapshotShardFailure where
4155− parseJSON = withObject "SnapshotShardFailure" parse
4156− where
4157− parse o = SnapshotShardFailure <$> o .: "index"
4158− <*> o .:? "node_id"
4159− <*> o .: "reason"
4160− <*> o .: "shard_id"
4161−
4162−
4163−newtype ShardId = ShardId { shardId :: Int }
4164− deriving (Eq, Show, Generic, Typeable, FromJSON)
4165−
4166−-- | Milliseconds
4167−newtype MS = MS NominalDiffTime
4168−
4169−
4170−-- keeps the unexported constructor warnings at bay
4171−unMS :: MS -> NominalDiffTime
4172−unMS (MS t) = t
4173−
4174−
4175−instance FromJSON MS where
4176− parseJSON = withScientific "MS" (return . MS . parse)
4177− where
4178− parse n = fromInteger ((truncate n) * 1000)
4179−
4180−
4181−data SnapshotState = SnapshotInit
4182− | SnapshotStarted
4183− | SnapshotSuccess
4184− | SnapshotFailed
4185− | SnapshotAborted
4186− | SnapshotMissing
4187− | SnapshotWaiting
4188− deriving (Show, Eq, Generic, Typeable)
4189−
4190−instance FromJSON SnapshotState where
4191− parseJSON = withText "SnapshotState" parse
4192− where
4193− parse "INIT" = return SnapshotInit
4194− parse "STARTED" = return SnapshotStarted
4195− parse "SUCCESS" = return SnapshotSuccess
4196− parse "FAILED" = return SnapshotFailed
4197− parse "ABORTED" = return SnapshotAborted
4198− parse "MISSING" = return SnapshotMissing
4199− parse "WAITING" = return SnapshotWaiting
4200− parse t = fail ("Invalid snapshot state " <> T.unpack t)
4201−
4202−
4203−newtype SnapshotName = SnapshotName { snapshotName :: Text }
4204− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4205−
4206−
4207−data SnapshotRestoreSettings = SnapshotRestoreSettings {
4208− snapRestoreWaitForCompletion :: Bool
4209− -- ^ Should the API call return immediately after initializing
4210− -- the restore or wait until completed? Note that if this is
4211− -- enabled, it could wait a long time, so you should adjust your
4212− -- 'ManagerSettings' accordingly to set long timeouts or
4213− -- explicitly handle timeouts.
4214− , snapRestoreIndices :: Maybe IndexSelection
4215− -- ^ Nothing will restore all indices in the snapshot. Just [] is
4216− -- permissable and will essentially be a no-op restore.
4217− , snapRestoreIgnoreUnavailable :: Bool
4218− -- ^ If set to True, any indices that do not exist will be ignored
4219− -- during snapshot rather than failing the restore.
4220− , snapRestoreIncludeGlobalState :: Bool
4221− -- ^ If set to false, will ignore any global state in the snapshot
4222− -- and will not restore it.
4223− , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4224− -- ^ A regex pattern for matching indices. Used with
4225− -- 'snapRestoreRenameReplacement', the restore can reference the
4226− -- matched index and create a new index name upon restore.
4227− , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4228− -- ^ Expression of how index renames should be constructed.
4229− , snapRestorePartial :: Bool
4230− -- ^ If some indices fail to restore, should the process proceed?
4231− , snapRestoreIncludeAliases :: Bool
4232− -- ^ Should the restore also restore the aliases captured in the
4233− -- snapshot.
4234− , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4235− -- ^ Settings to apply during the restore process. __NOTE:__ This
4236− -- option is not supported in ES < 1.5 and should be set to
4237− -- Nothing in that case.
4238− , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4239− -- ^ This type could be more rich but it isn't clear which
4240− -- settings are allowed to be ignored during restore, so we're
4241− -- going with including this feature in a basic form rather than
4242− -- omitting it. One example here would be
4243− -- "index.refresh_interval". Any setting specified here will
4244− -- revert back to the server default during the restore process.
4245− } deriving (Eq, Generic, Show, Typeable)
4246−
4247−-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4248−newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4249− deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4250−
4251−
4252−-- | A single token in a index renaming scheme for a restore. These
4253−-- are concatenated into a string before being sent to
4254−-- ElasticSearch. Check out these Java
4255−-- <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.
4256−data RestoreRenameToken = RRTLit Text
4257− -- ^ Just a literal string of characters
4258− | RRSubWholeMatch
4259− -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4260− | RRSubGroup RRGroupRefNum
4261− -- ^ A specific reference to a group number
4262− deriving (Show, Eq, Generic, Typeable)
4263−
4264−
4265−-- | A group number for regex matching. Only values from 1-9 are
4266−-- supported. Construct with 'mkRRGroupRefNum'
4267−newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4268− deriving (Show, Eq, Generic, Typeable, Ord)
4269−
4270−instance Bounded RRGroupRefNum where
4271− minBound = RRGroupRefNum 1
4272− maxBound = RRGroupRefNum 9
4273−
4274−
4275−-- | Only allows valid group number references (1-9).
4276−mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4277−mkRRGroupRefNum i
4278− | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4279− Just $ RRGroupRefNum i
4280− | otherwise = Nothing
4281−
4282−
4283−-- | Reasonable defaults for snapshot restores
4284−--
4285−-- * snapRestoreWaitForCompletion False
4286−-- * snapRestoreIndices Nothing
4287−-- * snapRestoreIgnoreUnavailable False
4288−-- * snapRestoreIncludeGlobalState True
4289−-- * snapRestoreRenamePattern Nothing
4290−-- * snapRestoreRenameReplacement Nothing
4291−-- * snapRestorePartial False
4292−-- * snapRestoreIncludeAliases True
4293−-- * snapRestoreIndexSettingsOverrides Nothing
4294−-- * snapRestoreIgnoreIndexSettings Nothing
4295−defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4296−defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4297− snapRestoreWaitForCompletion = False
4298− , snapRestoreIndices = Nothing
4299− , snapRestoreIgnoreUnavailable = False
4300− , snapRestoreIncludeGlobalState = True
4301− , snapRestoreRenamePattern = Nothing
4302− , snapRestoreRenameReplacement = Nothing
4303− , snapRestorePartial = False
4304− , snapRestoreIncludeAliases = True
4305− , snapRestoreIndexSettingsOverrides = Nothing
4306− , snapRestoreIgnoreIndexSettings = Nothing
4307− }
4308−
4309−
4310−-- | Index settings that can be overridden. The docs only mention you
4311−-- can update number of replicas, but there may be more. You
4312−-- definitely cannot override shard count.
4313−data RestoreIndexSettings = RestoreIndexSettings {
4314− restoreOverrideReplicas :: Maybe ReplicaCount
4315− } deriving (Show, Eq, Generic, Typeable)
4316−
4317−
4318−instance ToJSON RestoreIndexSettings where
4319− toJSON RestoreIndexSettings {..} = object prs
4320− where
4321− prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
540+newtype ScrollId =
541+ ScrollId Text
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)