@@ -4,7 +4,6 @@
44{-# LANGUAGE FlexibleInstances #-}
55{-# LANGUAGE GeneralizedNewtypeDeriving #-}
66{-# LANGUAGE MultiParamTypeClasses #-}
7−-- {-# LANGUAGE NoMonomorphismRestriction #-}
87{-# LANGUAGE NamedFieldPuns #-}
98{-# LANGUAGE OverloadedStrings #-}
109{-# LANGUAGE RecordWildCards #-}
@@ -386,580 +385,57 @@ module Database.V5.Bloodhound.Types
386385 , TokenChar(..)
387386 ) where
388387
389−import Control.Applicative as A
390−import Control.Arrow (first)
391−import Control.Monad.Catch
392−import Control.Monad.Except
393−import Control.Monad.Reader (MonadReader (..),
394− ReaderT (..))
395−import Control.Monad.State (MonadState)
396−import Control.Monad.Writer (MonadWriter)
397−import Data.Aeson
398−import Data.Aeson.Types (Pair, Parser,
399− emptyObject,
400− parseEither, parseMaybe,
401− typeMismatch)
402−import qualified Data.ByteString.Lazy.Char8 as L
403−import Data.Char
404−import Data.Hashable (Hashable)
388+-- import Control.Applicative as A
389+-- import Control.Arrow (first)
390+-- import Control.Monad.Catch
391+-- import Control.Monad.Except
392+-- import Control.Monad.State (MonadState)
393+-- import Control.Monad.Writer (MonadWriter)
394+-- import Data.Aeson
395+-- import Data.Aeson.Types (Pair, Parser,
396+-- emptyObject,
397+-- parseEither, parseMaybe,
398+-- typeMismatch)
399+-- import qualified Data.ByteString.Lazy.Char8 as L
400+-- import Data.Char
401+-- import Data.Hashable (Hashable)
402+-- import qualified Data.HashMap.Strict as HM
403+-- import Data.List (foldl', intercalate,
404+-- nub)
405+-- import Data.List.NonEmpty (NonEmpty (..), toList)
406+-- import Data.Maybe
407+-- import Data.Scientific (Scientific)
408+-- import Data.Semigroup
409+-- import Data.Text (Text)
410+-- import qualified Data.Text as T
411+-- import Data.Time.Calendar
412+-- import Data.Time.Clock (NominalDiffTime,
413+-- UTCTime)
414+-- import Data.Time.Clock.POSIX
415+-- import qualified Data.Traversable as DT
416+-- import Data.Typeable (Typeable)
417+-- import qualified Data.Vector as V
418+-- import qualified Data.Version as Vers
419+-- import GHC.Enum
420+-- import GHC.Generics (Generic)
421+-- import Network.HTTP.Client
422+-- import qualified Network.HTTP.Types.Method as NHTM
423+-- import qualified Text.ParserCombinators.ReadP as RP
424+-- import qualified Text.Read as TR
425+
426+import Bloodhound.Import
427+
428+import qualified Data.Traversable as DT
405429import qualified Data.HashMap.Strict as HM
406−import Data.List (foldl', intercalate,
407− nub)
408−import Data.List.NonEmpty (NonEmpty (..), toList)
409430import qualified Data.Map.Strict as M
410−import Data.Maybe
411−import Data.Scientific (Scientific)
412−import Data.Semigroup
413−import Data.Text (Text)
414431import qualified Data.Text as T
415−import Data.Time.Calendar
416−import Data.Time.Clock (NominalDiffTime,
417− UTCTime)
418−import Data.Time.Clock.POSIX
419−import qualified Data.Traversable as DT
420−import Data.Typeable (Typeable)
421−import qualified Data.Vector as V
422−import qualified Data.Version as Vers
423−import GHC.Enum
424−import GHC.Generics (Generic)
425−import Network.HTTP.Client
426−import qualified Network.HTTP.Types.Method as NHTM
427−import qualified Text.ParserCombinators.ReadP as RP
428−import qualified Text.Read as TR
429432
430433import Database.V5.Bloodhound.Types.Class
431−import Database.V5.Bloodhound.Types.Internal
432−
433−-- $setup
434−-- >>> :set -XOverloadedStrings
435−-- >>> import Data.Aeson
436−-- >>> import Database.V5.Bloodhound
437−-- >>> let testServer = (Server "http://localhost:9200")
438−-- >>> let testIndex = IndexName "twitter"
439−-- >>> let testMapping = MappingName "tweet"
440−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
441−
442−-- defaultIndexSettings is exported by Database.Bloodhound as well
443−-- no trailing slashes in servers, library handles building the path.
444−
445−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
446−-- will be a noop. You can use the exported fields to customize it further, e.g.:
447−--
448−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
449−mkBHEnv :: Server -> Manager -> BHEnv
450−mkBHEnv s m = BHEnv s m return
451−
452−newtype BH m a = BH {
453− unBH :: ReaderT BHEnv m a
454− } deriving ( Functor
455− , A.Applicative
456− , Monad
457− , MonadIO
458− , MonadState s
459− , MonadWriter w
460− , MonadError e
461− , Alternative
462− , MonadPlus
463− , MonadFix
464− , MonadThrow
465− , MonadCatch
466− , MonadMask)
467−
468−instance MonadTrans BH where
469− lift = BH . lift
470−
471−instance (MonadReader r m) => MonadReader r (BH m) where
472− ask = lift ask
473− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
474− local f (m r)
475−
476−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
477− getBHEnv = BH getBHEnv
478−
479−runBH :: BHEnv -> BH m a -> m a
480−runBH e f = runReaderT (unBH f) e
481−
482−{-| 'Version' is embedded in 'Status' -}
483−data Version = Version { number :: VersionNumber
484− , build_hash :: BuildHash
485− , build_date :: UTCTime
486− , build_snapshot :: Bool
487− , lucene_version :: VersionNumber } deriving (Eq, Read, Show, Generic, Typeable)
488−
489−-- | Traditional software versioning number
490−newtype VersionNumber = VersionNumber { versionNumber :: Vers.Version
491− } deriving (Eq, Read, Show, Generic, Typeable, Ord)
492−
493−{-| 'Status' is a data type for describing the JSON body returned by
494− Elasticsearch when you query its status. This was deprecated in 1.2.0.
495−
496− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
497−-}
498−
499−data Status = Status { name :: Text
500− , cluster_name :: Text
501− , cluster_uuid :: Text
502− , version :: Version
503− , tagline :: Text } deriving (Eq, Read, Show, Generic)
504−
505−{-| 'IndexSettings' is used to configure the shards and replicas when you create
506− an Elasticsearch Index.
507−
508− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
509−-}
510−
511−data IndexSettings =
512− IndexSettings { indexShards :: ShardCount
513− , indexReplicas :: ReplicaCount } deriving (Eq, Read, Show, Generic, Typeable)
514−
515−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
516−defaultIndexSettings :: IndexSettings
517−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
518−
519−
520−{-| 'ForceMergeIndexSettings' is used to configure index optimization. See
521− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-forcemerge.html>
522− for more info.
523−-}
524−data ForceMergeIndexSettings =
525− ForceMergeIndexSettings { maxNumSegments :: Maybe Int
526− -- ^ 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.
527− , onlyExpungeDeletes :: Bool
528− -- ^ 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.
529− , flushAfterOptimize :: Bool
530− -- ^ Should a flush be performed after the optimize.
531− } deriving (Eq, Show, Generic, Typeable)
532−
533−
534−{-| 'defaultForceMergeIndexSettings' implements the default settings that
535− ElasticSearch uses for index optimization. 'maxNumSegments' is Nothing,
536− 'onlyExpungeDeletes' is False, and flushAfterOptimize is True.
537−-}
538−defaultForceMergeIndexSettings :: ForceMergeIndexSettings
539−defaultForceMergeIndexSettings = ForceMergeIndexSettings Nothing False True
540−
541−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
542−
543− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
544−-}
545−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
546− -- ^ The number of replicas each shard has.
547− | AutoExpandReplicas ReplicaBounds
548− | BlocksReadOnly Bool
549− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
550− | BlocksRead Bool
551− -- ^ Set to True to disable read operations against the index.
552− | BlocksWrite Bool
553− -- ^ Set to True to disable write operations against the index.
554− | BlocksMetaData Bool
555− -- ^ Set to True to disable metadata operations against the index.
556− | RefreshInterval NominalDiffTime
557− -- ^ The async refresh interval of a shard
558− | IndexConcurrency Int
559− | FailOnMergeFailure Bool
560− | TranslogFlushThresholdOps Int
561− -- ^ When to flush on operations.
562− | TranslogFlushThresholdSize Bytes
563− -- ^ When to flush based on translog (bytes) size.
564− | TranslogFlushThresholdPeriod NominalDiffTime
565− -- ^ When to flush based on a period of not flushing.
566− | TranslogDisableFlush Bool
567− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
568− | CacheFilterMaxSize (Maybe Bytes)
569− -- ^ The maximum size of filter cache (per segment in shard).
570− | CacheFilterExpire (Maybe NominalDiffTime)
571− -- ^ The expire after access time for filter cache.
572− | GatewaySnapshotInterval NominalDiffTime
573− -- ^ The gateway snapshot interval (only applies to shared gateways).
574− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
575− -- ^ A node matching any rule will be allowed to host shards from the index.
576− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
577− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
578− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
579− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
580− | RoutingAllocationEnable AllocationPolicy
581− -- ^ Enables shard allocation for a specific index.
582− | RoutingAllocationShardsPerNode ShardCount
583− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
584− | RecoveryInitialShards InitialShardCount
585− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
586− | GCDeletes NominalDiffTime
587− | TTLDisablePurge Bool
588− -- ^ Disables temporarily the purge of expired docs.
589− | TranslogFSType FSType
590− | CompressionSetting Compression
591− | IndexCompoundFormat CompoundFormat
592− | IndexCompoundOnFlush Bool
593− | WarmerEnabled Bool
594− | MappingTotalFieldsLimit Int
595− | AnalysisSetting Analysis
596− -- ^ Analysis is not a dynamic setting and can only be performed on a closed index.
597− deriving (Eq, Show, Generic, Typeable)
598−
599−data Analysis = Analysis
600− { analysisAnalyzer :: M.Map Text AnalyzerDefinition
601− , analysisTokenizer :: M.Map Text TokenizerDefinition
602− } deriving (Eq,Show,Generic,Typeable)
603−
604−instance ToJSON Analysis where
605− toJSON (Analysis analyzer tokenizer) = object
606− [ "analyzer" .= analyzer
607− , "tokenizer" .= tokenizer
608− ]
609−
610−instance FromJSON Analysis where
611− parseJSON = withObject "Analysis" $ \m -> Analysis
612− <$> m .: "analyzer"
613− <*> m .: "tokenizer"
614−
615−data AnalyzerDefinition = AnalyzerDefinition
616− { analyzerDefinitionTokenizer :: Maybe Tokenizer
617− } deriving (Eq,Show,Generic,Typeable)
618−
619−instance ToJSON AnalyzerDefinition where
620− toJSON (AnalyzerDefinition tokenizer) = object $ catMaybes
621− [ fmap ("tokenizer" .=) tokenizer
622− ]
623−
624−instance FromJSON AnalyzerDefinition where
625− parseJSON = withObject "AnalyzerDefinition" $ \m -> AnalyzerDefinition
626− <$> m .:? "tokenizer"
627−
628−
629−data TokenizerDefinition
630− = TokenizerDefinitionNgram Ngram
631− deriving (Eq,Show,Generic,Typeable)
632−
633−instance ToJSON TokenizerDefinition where
634− toJSON x = case x of
635− TokenizerDefinitionNgram (Ngram minGram maxGram tokenChars) -> object
636− [ "type" .= ("ngram" :: Text)
637− , "min_gram" .= minGram
638− , "max_gram" .= maxGram
639− , "token_chars" .= tokenChars
640− ]
641−
642−instance FromJSON TokenizerDefinition where
643− parseJSON = withObject "TokenizerDefinition" $ \m -> do
644− typ <- m .: "type" :: Parser Text
645− case typ of
646− "ngram" -> fmap TokenizerDefinitionNgram $ Ngram
647− <$> (fmap unStringlyTypedInt (m .: "min_gram"))
648− <*> (fmap unStringlyTypedInt (m .: "max_gram"))
649− <*> m .: "token_chars"
650− _ -> fail "invalid TokenizerDefinition"
651−
652−data Ngram = Ngram
653− { ngramMinGram :: Int
654− , ngramMaxGram :: Int
655− , ngramTokenChars :: [TokenChar]
656− } deriving (Eq,Show,Generic,Typeable)
657−
658−data TokenChar = TokenLetter | TokenDigit | TokenWhitespace | TokenPunctuation | TokenSymbol
659− deriving (Eq,Read,Show,Generic,Typeable)
660−
661−instance ToJSON TokenChar where
662− toJSON t = String $ case t of
663− TokenLetter -> "letter"
664− TokenDigit -> "digit"
665− TokenWhitespace -> "whitespace"
666− TokenPunctuation -> "punctuation"
667− TokenSymbol -> "symbol"
668−
669−instance FromJSON TokenChar where
670− parseJSON = withText "TokenChar" $ \t -> case t of
671− "letter" -> return TokenLetter
672− "digit" -> return TokenDigit
673− "whitespace" -> return TokenWhitespace
674− "punctuation" -> return TokenPunctuation
675− "symbol" -> return TokenSymbol
676− _ -> fail "invalid TokenChar"
677−
678−data AllocationPolicy = AllocAll
679− -- ^ Allows shard allocation for all shards.
680− | AllocPrimaries
681− -- ^ Allows shard allocation only for primary shards.
682− | AllocNewPrimaries
683− -- ^ Allows shard allocation only for primary shards for new indices.
684− | AllocNone
685− -- ^ No shard allocation is allowed
686− deriving (Eq, Read, Show, Generic, Typeable)
687−
688−data ReplicaBounds = ReplicasBounded Int Int
689− | ReplicasLowerBounded Int
690− | ReplicasUnbounded
691− deriving (Eq, Read, Show, Generic, Typeable)
692−
693−data Compression
694− = CompressionDefault
695− -- ^ Compress with LZ4
696− | CompressionBest
697− -- ^ Compress with DEFLATE. Elastic
698− -- <https://www.elastic.co/blog/elasticsearch-storage-the-true-story-2.0 blogs>
699− -- that this can reduce disk use by 15%-25%.
700− deriving (Eq,Show,Generic,Typeable)
701−
702−instance ToJSON Compression where
703− toJSON x = case x of
704− CompressionDefault -> toJSON ("default" :: Text)
705− CompressionBest -> toJSON ("best_compression" :: Text)
706−
707−instance FromJSON Compression where
708− parseJSON = withText "Compression" $ \t -> case t of
709− "default" -> return CompressionDefault
710− "best_compression" -> return CompressionBest
711− _ -> fail "invalid compression codec"
712−
713−-- | A measure of bytes used for various configurations. You may want
714−-- to use smart constructors like 'gigabytes' for larger values.
715−--
716−-- >>> gigabytes 9
717−-- Bytes 9000000000
718−--
719−-- >>> megabytes 9
720−-- Bytes 9000000
721−--
722−-- >>> kilobytes 9
723−-- Bytes 9000
724−newtype Bytes = Bytes Int deriving (Eq, Read, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
725−
726−gigabytes :: Int -> Bytes
727−gigabytes n = megabytes (1000 * n)
728−
729−
730−megabytes :: Int -> Bytes
731−megabytes n = kilobytes (1000 * n)
732−
733−
734−kilobytes :: Int -> Bytes
735−kilobytes n = Bytes (1000 * n)
736−
737−
738−data FSType = FSSimple
739− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
740−
741−data InitialShardCount = QuorumShards
742− | QuorumMinus1Shards
743− | FullShards
744− | FullMinus1Shards
745− | ExplicitShards Int
746− deriving (Eq, Read, Show, Generic, Typeable)
747−
748−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
749− , nodeAttrFilterValues :: NonEmpty Text}
750− deriving (Eq, Read, Show, Generic, Ord, Typeable)
751−
752−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
753−
754−data CompoundFormat = CompoundFileFormat Bool
755− | MergeSegmentVsTotalIndex Double
756− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
757− deriving (Eq, Read, Show, Generic, Typeable)
758−
759−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
760−
761−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
762− , sSummaryFixedSettings :: IndexSettings
763− , sSummaryUpdateable :: [UpdatableIndexSetting]}
764− deriving (Eq, Show, Generic, Typeable)
765−
766−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
767−type Reply = Network.HTTP.Client.Response L.ByteString
768−type Method = NHTM.Method
769−
770−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
771−
772− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
773−-}
774−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
775−
776−data FieldType = GeoPointType
777− | GeoShapeType
778− | FloatType
779− | IntegerType
780− | LongType
781− | ShortType
782− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
783−
784−data FieldDefinition =
785− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
786−
787−{-| An 'IndexTemplate' defines a template that will automatically be
788− applied to new indices created. The templates include both
789− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
790− controls if the template will be applied to the index created.
791− Specify mappings as follows: @[toJSON TweetMapping, ...]@
792−
793− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
794−-}
795−data IndexTemplate =
796− IndexTemplate { templatePattern :: TemplatePattern
797− , templateSettings :: Maybe IndexSettings
798− , templateMappings :: [Value]
799− }
800−
801−data MappingField =
802− MappingField { mappingFieldName :: FieldName
803− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
804−
805−{-| Support for type reification of 'Mapping's is currently incomplete, for
806− now the mapping API verbiage expects a 'ToJSON'able blob.
807−
808− Indexes have mappings, mappings are schemas for the documents contained in the
809− index. I'd recommend having only one mapping per index, always having a mapping,
810− and keeping different kinds of documents separated if possible.
811−-}
812−data Mapping = Mapping { typeName :: TypeName
813− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
814−
815−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
816− operation index, create, delete, and update. 'BulkIndex' behaves like an
817− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
818−
819− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
820−-}
821−data BulkOperation =
822− BulkIndex IndexName MappingName DocId Value
823− | BulkCreate IndexName MappingName DocId Value
824− | BulkCreateEncoding IndexName MappingName DocId Encoding
825− | BulkDelete IndexName MappingName DocId
826− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show, Generic, Typeable)
827−
828−{-| 'EsResult' describes the standard wrapper JSON document that you see in
829− successful Elasticsearch lookups or lookups that couldn't find the document.
830−-}
831−data EsResult a = EsResult { _index :: Text
832− , _type :: Text
833− , _id :: Text
834− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
835−
836−{-| 'EsResultFound' contains the document and its metadata inside of an
837− 'EsResult' when the document was successfully found.
838−-}
839−data EsResultFound a = EsResultFound { _version :: DocVersion
840− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
841−
842−{-| 'EsError' is the generic type that will be returned when there was a
843− problem. If you can't parse the expected response, its a good idea to
844− try parsing this.
845−-}
846−data EsError = EsError { errorStatus :: Int
847− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
848−
849−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
850−returned by the ElasticSearch server. If you encounter this error, please
851−verify that your domain data types and FromJSON instances are working properly
852−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
853−sure that your mappings are correct, then this error may be an indication of an
854−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
855−and be sure to include the exception body.
856−-}
857−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
858− deriving (Eq, Read, Show, Generic, Typeable)
859−
860−instance Exception EsProtocolException
861−
862−data IndexAlias = IndexAlias { srcIndex :: IndexName
863− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
864−
865−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
866−
867−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
868− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
869−
870−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
871− , aliasCreateFilter :: Maybe Filter}
872− deriving (Read, Show, Eq, Generic, Typeable)
873−
874−data AliasRouting = AllAliasRouting RoutingValue
875− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
876− deriving (Read, Show, Eq, Generic, Typeable)
877−
878−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
879−
880−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
881−
882−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
883−
884−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
885−
886−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
887−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
888− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
889−
890−{-| 'DocVersion' is an integer version number for a document between 1
891−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
892−-}
893−newtype DocVersion = DocVersion {
894− docVersionNumber :: Int
895− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
896−
897−-- | Smart constructor for in-range doc version
898−mkDocVersion :: Int -> Maybe DocVersion
899−mkDocVersion i
900− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
901− Just $ DocVersion i
902− | otherwise = Nothing
903−
904−
905−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
906−own version numbers instead of ones from ES.
907−-}
908−newtype ExternalDocVersion = ExternalDocVersion DocVersion
909− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
910−
911−{-| 'VersionControl' is specified when indexing documents as a
912−optimistic concurrency control.
913−-}
914−data VersionControl = NoVersionControl
915− -- ^ Don't send a version. This is a pure overwrite.
916− | InternalVersion DocVersion
917− -- ^ Use the default ES versioning scheme. Only
918− -- index the document if the version is the same
919− -- as the one specified. Only applicable to
920− -- updates, as you should be getting Version from
921− -- a search result.
922− | ExternalGT ExternalDocVersion
923− -- ^ Use your own version numbering. Only index
924− -- the document if the version is strictly higher
925− -- OR the document doesn't exist. The given
926− -- version will be used as the new version number
927− -- for the stored document. N.B. All updates must
928− -- increment this number, meaning there is some
929− -- global, external ordering of updates.
930− | ExternalGTE ExternalDocVersion
931− -- ^ Use your own version numbering. Only index
932− -- the document if the version is equal or higher
933− -- than the stored version. Will succeed if there
934− -- is no existing document. The given version will
935− -- be used as the new version number for the
936− -- stored document. Use with care, as this could
937− -- result in data loss.
938− | ForceVersion ExternalDocVersion
939− -- ^ The document will always be indexed and the
940− -- given version will be the new version. This is
941− -- typically used for correcting errors. Use with
942− -- care, as this could result in data loss.
943− deriving (Read, Show, Eq, Generic, Ord)
944−
945−{-| 'DocumentParent' is used to specify a parent document.
946−-}
947−newtype DocumentParent = DocumentParent DocId
948− deriving (Eq, Read, Show, Generic, Typeable)
949−
950−{-| 'IndexDocumentSettings' are special settings supplied when indexing
951−a document. For the best backwards compatiblity when new fields are
952−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
953−-}
954−data IndexDocumentSettings =
955− IndexDocumentSettings { idsVersionControl :: VersionControl
956− , idsParent :: Maybe DocumentParent
957− } deriving (Eq, Read, Show, Generic, Typeable)
958−
959−{-| Reasonable default settings. Chooses no version control and no parent.
960−-}
961−defaultIndexDocumentSettings :: IndexDocumentSettings
962−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
434+import Database.V5.Bloodhound.Types.Internal.Analysis
435+import Database.V5.Bloodhound.Types.Internal.Client
436+import Database.V5.Bloodhound.Types.Internal.Newtypes
437+import Database.V5.Bloodhound.Types.Internal.Query
438+import Database.V5.Bloodhound.Types.Internal.StringlyTyped
963439
964440{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
965441 dependent with later sorts acting as tie-breakers for earlier sorts.
@@ -974,7 +450,7 @@ type Sort = [SortSpec]
974450<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
975451-}
976452data SortSpec = DefaultSortSpec DefaultSort
977− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
453+ | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show)
978454
979455{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
980456 'mkSort' convenience function for when you want to specify only the most
@@ -991,7 +467,7 @@ data DefaultSort =
991467 , ignoreUnmapped :: Maybe Text
992468 , sortMode :: Maybe SortMode
993469 , missingSort :: Maybe Missing
994− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
470+ , nestedFilter :: Maybe Filter } deriving (Eq, Show)
995471
996472{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
997473 encoded into "asc" or "desc" when turned into JSON.
@@ -999,7 +475,7 @@ data DefaultSort =
999475<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
1000476-}
1001477data SortOrder = Ascending
1002− | Descending deriving (Eq, Read, Show, Generic, Typeable)
478+ | Descending deriving (Eq, Show)
1003479
1004480{-| 'Missing' prescribes how to handle missing fields. A missing field can be
1005481 sorted last, first, or using a custom value as a substitute.
@@ -1008,7 +484,7 @@ data SortOrder = Ascending
1008484-}
1009485data Missing = LastMissing
1010486 | FirstMissing
1011− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
487+ | CustomMissing Text deriving (Eq, Show)
1012488
1013489{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
1014490
@@ -1017,7 +493,7 @@ http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-req
1017493data SortMode = SortMin
1018494 | SortMax
1019495 | SortSum
1020− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
496+ | SortAvg deriving (Eq, Show)
1021497
1022498{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
1023499 that you can concisely describe the usual kind of 'SortSpec's you want.
@@ -1025,203 +501,14 @@ data SortMode = SortMin
1025501mkSort :: FieldName -> SortOrder -> DefaultSort
1026502mkSort fieldName sOrder = DefaultSort fieldName sOrder Nothing Nothing Nothing Nothing
1027503
1028−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
1029− 'Query's cannot be cached.
1030−-}
1031−type Cache = Bool -- caching on/off
1032−defaultCache :: Cache
1033−defaultCache = False
1034−
1035−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
1036−-}
1037−-- type PrefixValue = Text
1038−
1039−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
1040− JSON encoding baked in. Used all over the place.
1041−-}
1042−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
1043−
1044−{-| 'ShardCount' is part of 'IndexSettings'
1045−-}
1046−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
1047−
1048−{-| 'ReplicaCount' is part of 'IndexSettings'
1049−-}
1050−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
1051−
1052−{-| 'IndexName' is used to describe which index to query/create/delete
1053−-}
1054−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
1055−
1056−{-| 'IndexSelection' is used for APIs which take a single index, a list of
1057− indexes, or the special @_all@ index.
1058−-}
1059−--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.
1060−data IndexSelection = IndexList (NonEmpty IndexName)
1061− | AllIndexes deriving (Eq, Generic, Show, Typeable)
1062−
1063−{-| 'NodeSelection' is used for most cluster APIs. See <https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster.html#cluster-nodes here> for more details.
1064−-}
1065−data NodeSelection = LocalNode
1066− -- ^ Whatever node receives this request
1067− | NodeList (NonEmpty NodeSelector)
1068− | AllNodes deriving (Eq, Generic, Show, Typeable)
1069−
1070−
1071−-- | An exact match or pattern to identify a node. Note that All of
1072−-- these options support wildcarding, so your node name, server, attr
1073−-- name can all contain * characters to be a fuzzy match.
1074−data NodeSelector = NodeByName NodeName
1075− | NodeByFullNodeId FullNodeId
1076− | NodeByHost Server
1077− -- ^ e.g. 10.0.0.1 or even 10.0.0.*
1078− | NodeByAttribute NodeAttrName Text
1079− -- ^ NodeAttrName can be a pattern, e.g. rack*. The value can too.
1080− deriving (Eq, Generic, Show, Typeable)
1081−
1082−{-| 'TemplateName' is used to describe which template to query/create/delete
1083−-}
1084−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1085−
1086−{-| 'TemplatePattern' represents a pattern which is matched against index names
1087−-}
1088−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1089−
1090−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
1091− the data in the indices.
1092−-}
1093−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
1094−
1095−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
1096− Can be set by the user or created by ES itself. Often used in client
1097− functions for poking at specific documents.
1098−-}
1099−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
1100−
1101−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
1102−-}
1103−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
1104−
1105−{-| 'FieldName' is used all over the place wherever a specific field within
1106− a document needs to be specified, usually in 'Query's or 'Filter's.
1107−-}
1108−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1109−
1110−
1111−{-| 'Script' is often used in place of 'FieldName' to specify more
1112−complex ways of extracting a value from a document.
1113−-}
1114−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1115−
1116−{-| 'CacheName' is used in 'RegexpFilter' for describing the
1117− 'CacheKey' keyed caching behavior.
1118−-}
1119−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1120−
1121−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
1122−-}
1123−newtype CacheKey =
1124− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1125−newtype Existence =
1126− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1127−newtype NullValue =
1128− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1129−newtype CutoffFrequency =
1130− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1131−newtype Analyzer =
1132− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1133−newtype Tokenizer =
1134− Tokenizer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1135−newtype MaxExpansions =
1136− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1137−
1138−{-| 'Lenient', if set to true, will cause format based failures to be
1139− ignored. I don't know what the bloody default is, Elasticsearch
1140− documentation didn't say what it was. Let me know if you figure it out.
1141−-}
1142−newtype Lenient =
1143− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1144−newtype Tiebreaker =
1145− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1146−newtype Boost =
1147− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1148−newtype BoostTerms =
1149− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1150−
1151−{-| 'MinimumMatch' controls how many should clauses in the bool query should
1152− match. Can be an absolute value (2) or a percentage (30%) or a
1153− combination of both.
1154−-}
1155−newtype MinimumMatch =
1156− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1157−newtype DisableCoord =
1158− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1159−newtype IgnoreTermFrequency =
1160− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1161−newtype MinimumTermFrequency =
1162− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1163−newtype MaxQueryTerms =
1164− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1165−newtype Fuzziness =
1166− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1167−
1168−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
1169−newtype PrefixLength =
1170− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1171−newtype TypeName =
1172− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1173−newtype PercentMatch =
1174− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1175−newtype StopWord =
1176− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1177−newtype QueryPath =
1178− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1179−
1180−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
1181− heavy, because all terms in the index need to be examined, just in case
1182− they match. Leading wildcards can be disabled by setting
1183− 'AllowLeadingWildcard' to false. -}
1184−newtype AllowLeadingWildcard =
1185− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1186−newtype LowercaseExpanded =
1187− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1188−newtype EnablePositionIncrements =
1189− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1190−
1191−{-| By default, wildcard terms in a query are not analyzed.
1192− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
1193−-}
1194−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1195−
1196−{-| 'GeneratePhraseQueries' defaults to false.
1197−-}
1198−newtype GeneratePhraseQueries =
1199− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1200−
1201−{-| 'Locale' is used for string conversions - defaults to ROOT.
1202−-}
1203−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1204−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1205−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1206−
1207−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
1208− phrase matches. Default is 0.
1209−-}
1210−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1211−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1212−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
1213−
1214−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
1215−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
1216−
1217504{-| 'unpackId' is a silly convenience function that gets used once.
1218505-}
1219506unpackId :: DocId -> Text
1220507unpackId (DocId docId) = docId
1221508
1222509type TrackSortScores = Bool
1223−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
1224−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON)
510+newtype From = From Int deriving (Eq, Show, ToJSON)
511+newtype Size = Size Int deriving (Eq, Show, ToJSON, FromJSON)
1225512
1226513data Search = Search { queryBody :: Maybe Query
1227514 , filterBody :: Maybe Filter
@@ -1236,44 +523,51 @@ data Search = Search { queryBody :: Maybe Query
1236523 , fields :: Maybe [FieldName]
1237524 , source :: Maybe Source
1238525 , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
1239− } deriving (Eq, Read, Show, Generic, Typeable)
526+ } deriving (Eq, Show)
1240527
1241528data SearchType = SearchTypeQueryThenFetch
1242529 | SearchTypeDfsQueryThenFetch
1243− deriving (Eq, Read, Show, Generic, Typeable)
530+ deriving (Eq, Show)
1244531
1245532data Source =
1246533 NoSource
1247534 | SourcePatterns PatternOrPatterns
1248535 | SourceIncludeExclude Include Exclude
1249− deriving (Read, Show, Eq, Generic, Typeable)
536+ deriving (Eq, Show)
1250537
1251538data PatternOrPatterns = PopPattern Pattern
1252− | PopPatterns [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
539+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1253540
1254−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
1255−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
541+data Include = Include [Pattern] deriving (Eq, Read, Show)
542+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1256543
1257−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
544+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1258545
1259−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
1260− , highlightFields :: [FieldHighlight]
1261− } deriving (Read, Show, Eq, Generic, Typeable)
546+data Highlights = Highlights
547+ { globalsettings :: Maybe HighlightSettings
548+ , highlightFields :: [FieldHighlight]
549+ } deriving (Eq, Show)
1262550
1263−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
1264− deriving (Read, Show, Eq, Generic, Typeable)
551+data FieldHighlight =
552+ FieldHighlight FieldName (Maybe HighlightSettings)
553+ deriving (Eq, Show)
1265554
1266555
1267−data HighlightSettings = Plain PlainHighlight
1268− | Postings PostingsHighlight
1269− | FastVector FastVectorHighlight
1270− deriving (Read, Show, Eq, Generic, Typeable)
556+data HighlightSettings =
557+ Plain PlainHighlight
558+ | Postings PostingsHighlight
559+ | FastVector FastVectorHighlight
560+ deriving (Eq, Show)
561+
1271562data PlainHighlight =
1272− PlainHighlight { plainCommon :: Maybe CommonHighlight
1273− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
563+ PlainHighlight { plainCommon :: Maybe CommonHighlight
564+ , plainNonPost :: Maybe NonPostings }
565+ deriving (Eq, Show)
1274566
1275567 -- This requires that index_options are set to 'offset' in the mapping.
1276−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
568+data PostingsHighlight =
569+ PostingsHighlight (Maybe CommonHighlight)
570+ deriving (Eq, Show)
1277571
1278572-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
1279573data FastVectorHighlight =
@@ -1284,7 +578,7 @@ data FastVectorHighlight =
1284578 , fragmentOffset :: Maybe Int
1285579 , matchedFields :: [Text]
1286580 , phraseLimit :: Maybe Int
1287− } deriving (Read, Show, Eq, Generic, Typeable)
581+ } deriving (Eq, Show)
1288582
1289583data CommonHighlight =
1290584 CommonHighlight { order :: Maybe Text
@@ -1294,496 +588,26 @@ data CommonHighlight =
1294588 , noMatchSize :: Maybe Int
1295589 , highlightQuery :: Maybe Query
1296590 , requireFieldMatch :: Maybe Bool
1297− } deriving (Read, Show, Eq, Generic, Typeable)
591+ } deriving (Eq, Show)
1298592
1299593-- Settings that are only applicable to FastVector and Plain highlighters.
1300594data NonPostings =
1301595 NonPostings { fragmentSize :: Maybe Int
1302− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
596+ , numberOfFragments :: Maybe Int
597+ } deriving (Eq, Show)
1303598
1304599data HighlightEncoder = DefaultEncoder
1305600 | HTMLEncoder
1306− deriving (Read, Show, Eq, Generic, Typeable)
601+ deriving (Eq, Show)
1307602
1308603-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1309−data HighlightTag = TagSchema Text
1310− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1311− deriving (Read, Show, Eq, Generic, Typeable)
1312−
1313−
1314−data Query =
1315− TermQuery Term (Maybe Boost)
1316− | TermsQuery Text (NonEmpty Text)
1317− | QueryMatchQuery MatchQuery
1318− | QueryMultiMatchQuery MultiMatchQuery
1319− | QueryBoolQuery BoolQuery
1320− | QueryBoostingQuery BoostingQuery
1321− | QueryCommonTermsQuery CommonTermsQuery
1322− | ConstantScoreQuery Query Boost
1323− | QueryDisMaxQuery DisMaxQuery
1324− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1325− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1326− | QueryFuzzyQuery FuzzyQuery
1327− | QueryHasChildQuery HasChildQuery
1328− | QueryHasParentQuery HasParentQuery
1329− | IdsQuery MappingName [DocId]
1330− | QueryIndicesQuery IndicesQuery
1331− | MatchAllQuery (Maybe Boost)
1332− | QueryMoreLikeThisQuery MoreLikeThisQuery
1333− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1334− | QueryNestedQuery NestedQuery
1335− | QueryPrefixQuery PrefixQuery
1336− | QueryQueryStringQuery QueryStringQuery
1337− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1338− | QueryRangeQuery RangeQuery
1339− | QueryRegexpQuery RegexpQuery
1340− | QueryExistsQuery FieldName
1341− | QueryMatchNoneQuery
1342− | QueryTemplateQueryInline TemplateQueryInline
1343− deriving (Eq, Read, Show, Generic, Typeable)
1344−
1345−-- | As of Elastic 2.0, 'Filters' are just 'Queries' housed in a Bool Query, and
1346−-- flagged in a different context.
1347−newtype Filter = Filter { unFilter :: Query }
1348− deriving (Eq, Read, Show, Generic, Typeable)
1349−
1350−instance ToJSON Filter where
1351− toJSON = toJSON . unFilter
1352−
1353−instance FromJSON Filter where
1354− parseJSON v = Filter <$> parseJSON v
1355−
1356−data RegexpQuery =
1357− RegexpQuery { regexpQueryField :: FieldName
1358− , regexpQuery :: Regexp
1359− , regexpQueryFlags :: RegexpFlags
1360− , regexpQueryBoost :: Maybe Boost
1361− } deriving (Eq, Read, Show, Generic, Typeable)
1362−
1363−data RangeQuery =
1364− RangeQuery { rangeQueryField :: FieldName
1365− , rangeQueryRange :: RangeValue
1366− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1367−
1368−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1369−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1370−
1371−data SimpleQueryStringQuery =
1372− SimpleQueryStringQuery
1373− { simpleQueryStringQuery :: QueryString
1374− , simpleQueryStringField :: Maybe FieldOrFields
1375− , simpleQueryStringOperator :: Maybe BooleanOperator
1376− , simpleQueryStringAnalyzer :: Maybe Analyzer
1377− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1378− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1379− , simpleQueryStringLocale :: Maybe Locale
1380− } deriving (Eq, Read, Show, Generic, Typeable)
1381−
1382−data SimpleQueryFlag =
1383− SimpleQueryAll
1384− | SimpleQueryNone
1385− | SimpleQueryAnd
1386− | SimpleQueryOr
1387− | SimpleQueryPrefix
1388− | SimpleQueryPhrase
1389− | SimpleQueryPrecedence
1390− | SimpleQueryEscape
1391− | SimpleQueryWhitespace
1392− | SimpleQueryFuzzy
1393− | SimpleQueryNear
1394− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1395−
1396−-- use_dis_max and tie_breaker when fields are plural?
1397−data QueryStringQuery =
1398− QueryStringQuery
1399− { queryStringQuery :: QueryString
1400− , queryStringDefaultField :: Maybe FieldName
1401− , queryStringOperator :: Maybe BooleanOperator
1402− , queryStringAnalyzer :: Maybe Analyzer
1403− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1404− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1405− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1406− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1407− , queryStringFuzziness :: Maybe Fuzziness
1408− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1409− , queryStringPhraseSlop :: Maybe PhraseSlop
1410− , queryStringBoost :: Maybe Boost
1411− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1412− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1413− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1414− , queryStringLenient :: Maybe Lenient
1415− , queryStringLocale :: Maybe Locale
1416− } deriving (Eq, Read, Show, Generic, Typeable)
1417−
1418−mkQueryStringQuery :: QueryString -> QueryStringQuery
1419−mkQueryStringQuery qs =
1420− QueryStringQuery qs Nothing Nothing
1421− Nothing Nothing Nothing Nothing
1422− Nothing Nothing Nothing Nothing
1423− Nothing Nothing Nothing Nothing
1424− Nothing Nothing
1425−
1426−data FieldOrFields = FofField FieldName
1427− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1428−
1429−data PrefixQuery =
1430− PrefixQuery
1431− { prefixQueryField :: FieldName
1432− , prefixQueryPrefixValue :: Text
1433− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1434−
1435−data NestedQuery =
1436− NestedQuery
1437− { nestedQueryPath :: QueryPath
1438− , nestedQueryScoreType :: ScoreType
1439− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1440−
1441−data MoreLikeThisFieldQuery =
1442− MoreLikeThisFieldQuery
1443− { moreLikeThisFieldText :: Text
1444− , moreLikeThisFieldFields :: FieldName
1445− -- default 0.3 (30%)
1446− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1447− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1448− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1449− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1450− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1451− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1452− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1453− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1454− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1455− , moreLikeThisFieldBoost :: Maybe Boost
1456− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1457− } deriving (Eq, Read, Show, Generic, Typeable)
1458−
1459−data MoreLikeThisQuery =
1460− MoreLikeThisQuery
1461− { moreLikeThisText :: Text
1462− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1463− -- default 0.3 (30%)
1464− , moreLikeThisPercentMatch :: Maybe PercentMatch
1465− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1466− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1467− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1468− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1469− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1470− , moreLikeThisMinWordLength :: Maybe MinWordLength
1471− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1472− , moreLikeThisBoostTerms :: Maybe BoostTerms
1473− , moreLikeThisBoost :: Maybe Boost
1474− , moreLikeThisAnalyzer :: Maybe Analyzer
1475− } deriving (Eq, Read, Show, Generic, Typeable)
1476−
1477−data IndicesQuery =
1478− IndicesQuery
1479− { indicesQueryIndices :: [IndexName]
1480− , indicesQuery :: Query
1481− -- default "all"
1482− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1483−
1484−data HasParentQuery =
1485− HasParentQuery
1486− { hasParentQueryType :: TypeName
1487− , hasParentQuery :: Query
1488− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1489−
1490−data HasChildQuery =
1491− HasChildQuery
1492− { hasChildQueryType :: TypeName
1493− , hasChildQuery :: Query
1494− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1495−
1496−data ScoreType =
1497− ScoreTypeMax
1498− | ScoreTypeSum
1499− | ScoreTypeAvg
1500− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1501−
1502−data FuzzyQuery =
1503− FuzzyQuery { fuzzyQueryField :: FieldName
1504− , fuzzyQueryValue :: Text
1505− , fuzzyQueryPrefixLength :: PrefixLength
1506− , fuzzyQueryMaxExpansions :: MaxExpansions
1507− , fuzzyQueryFuzziness :: Fuzziness
1508− , fuzzyQueryBoost :: Maybe Boost
1509− } deriving (Eq, Read, Show, Generic, Typeable)
1510−
1511−data FuzzyLikeFieldQuery =
1512− FuzzyLikeFieldQuery
1513− { fuzzyLikeField :: FieldName
1514− -- anaphora is good for the soul.
1515− , fuzzyLikeFieldText :: Text
1516− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1517− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1518− , fuzzyLikeFieldFuzziness :: Fuzziness
1519− , fuzzyLikeFieldPrefixLength :: PrefixLength
1520− , fuzzyLikeFieldBoost :: Boost
1521− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1522− } deriving (Eq, Read, Show, Generic, Typeable)
1523−
1524−data FuzzyLikeThisQuery =
1525− FuzzyLikeThisQuery
1526− { fuzzyLikeFields :: [FieldName]
1527− , fuzzyLikeText :: Text
1528− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1529− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1530− , fuzzyLikeFuzziness :: Fuzziness
1531− , fuzzyLikePrefixLength :: PrefixLength
1532− , fuzzyLikeBoost :: Boost
1533− , fuzzyLikeAnalyzer :: Maybe Analyzer
1534− } deriving (Eq, Read, Show, Generic, Typeable)
1535−
1536−data DisMaxQuery =
1537− DisMaxQuery { disMaxQueries :: [Query]
1538− -- default 0.0
1539− , disMaxTiebreaker :: Tiebreaker
1540− , disMaxBoost :: Maybe Boost
1541− } deriving (Eq, Read, Show, Generic, Typeable)
1542−
1543−data MatchQuery =
1544− MatchQuery { matchQueryField :: FieldName
1545− , matchQueryQueryString :: QueryString
1546− , matchQueryOperator :: BooleanOperator
1547− , matchQueryZeroTerms :: ZeroTermsQuery
1548− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1549− , matchQueryMatchType :: Maybe MatchQueryType
1550− , matchQueryAnalyzer :: Maybe Analyzer
1551− , matchQueryMaxExpansions :: Maybe MaxExpansions
1552− , matchQueryLenient :: Maybe Lenient
1553− , matchQueryBoost :: Maybe Boost
1554− , matchQueryMinimumShouldMatch :: Maybe Text
1555− } deriving (Eq, Read, Show, Generic, Typeable)
1556−
1557−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1558− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1559−-}
1560−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1561−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1562−
1563−data MatchQueryType =
1564− MatchPhrase
1565− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1566−
1567−data MultiMatchQuery =
1568− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1569− , multiMatchQueryString :: QueryString
1570− , multiMatchQueryOperator :: BooleanOperator
1571− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1572− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1573− , multiMatchQueryType :: Maybe MultiMatchQueryType
1574− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1575− , multiMatchQueryAnalyzer :: Maybe Analyzer
1576− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1577− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1578−
1579−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1580− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1581− make a 'MultiMatchQuery'.
1582−-}
604+data HighlightTag =
605+ TagSchema Text
606+ -- Only uses more than the first value in the lists if fvh
607+ | CustomTags ([Text], [Text])
608+ deriving (Eq, Show)
609+
1583610
1584−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1585−mkMultiMatchQuery matchFields query =
1586− MultiMatchQuery matchFields query
1587− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1588−
1589−data MultiMatchQueryType =
1590− MultiMatchBestFields
1591− | MultiMatchMostFields
1592− | MultiMatchCrossFields
1593− | MultiMatchPhrase
1594− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1595−
1596−data BoolQuery =
1597− BoolQuery { boolQueryMustMatch :: [Query]
1598− , boolQueryFilter :: [Filter]
1599− , boolQueryMustNotMatch :: [Query]
1600− , boolQueryShouldMatch :: [Query]
1601− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1602− , boolQueryBoost :: Maybe Boost
1603− , boolQueryDisableCoord :: Maybe DisableCoord
1604− } deriving (Eq, Read, Show, Generic, Typeable)
1605−
1606−mkBoolQuery :: [Query] -> [Filter] -> [Query] -> [Query] -> BoolQuery
1607−mkBoolQuery must filt mustNot should =
1608− BoolQuery must filt mustNot should Nothing Nothing Nothing
1609−
1610−data BoostingQuery =
1611− BoostingQuery { positiveQuery :: Query
1612− , negativeQuery :: Query
1613− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1614−
1615−data CommonTermsQuery =
1616− CommonTermsQuery { commonField :: FieldName
1617− , commonQuery :: QueryString
1618− , commonCutoffFrequency :: CutoffFrequency
1619− , commonLowFreqOperator :: BooleanOperator
1620− , commonHighFreqOperator :: BooleanOperator
1621− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1622− , commonBoost :: Maybe Boost
1623− , commonAnalyzer :: Maybe Analyzer
1624− , commonDisableCoord :: Maybe DisableCoord
1625− } deriving (Eq, Read, Show, Generic, Typeable)
1626−
1627−data CommonMinimumMatch =
1628− CommonMinimumMatchHighLow MinimumMatchHighLow
1629− | CommonMinimumMatch MinimumMatch
1630− deriving (Eq, Read, Show, Generic, Typeable)
1631−
1632−data MinimumMatchHighLow =
1633− MinimumMatchHighLow { lowFreq :: MinimumMatch
1634− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1635−
1636−data ZeroTermsQuery = ZeroTermsNone
1637− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1638−
1639−data RangeExecution = RangeExecutionIndex
1640− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1641−
1642−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1643−
1644−data RegexpFlags = AllRegexpFlags
1645− | NoRegexpFlags
1646− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1647−
1648−data RegexpFlag = AnyString
1649− | Automaton
1650− | Complement
1651− | Empty
1652− | Intersection
1653− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1654−
1655−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1656−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1657−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1658−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1659−
1660−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1661−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1662−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1663−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1664−
1665−data RangeValue = RangeDateLte LessThanEqD
1666− | RangeDateLt LessThanD
1667− | RangeDateGte GreaterThanEqD
1668− | RangeDateGt GreaterThanD
1669− | RangeDateGtLt GreaterThanD LessThanD
1670− | RangeDateGteLte GreaterThanEqD LessThanEqD
1671− | RangeDateGteLt GreaterThanEqD LessThanD
1672− | RangeDateGtLte GreaterThanD LessThanEqD
1673− | RangeDoubleLte LessThanEq
1674− | RangeDoubleLt LessThan
1675− | RangeDoubleGte GreaterThanEq
1676− | RangeDoubleGt GreaterThan
1677− | RangeDoubleGtLt GreaterThan LessThan
1678− | RangeDoubleGteLte GreaterThanEq LessThanEq
1679− | RangeDoubleGteLt GreaterThanEq LessThan
1680− | RangeDoubleGtLte GreaterThan LessThanEq
1681− deriving (Eq, Read, Show, Generic, Typeable)
1682−
1683−rangeValueToPair :: RangeValue -> [Pair]
1684−rangeValueToPair rv = case rv of
1685− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1686− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1687− RangeDateLt (LessThanD t) -> ["lt" .= t]
1688− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1689− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1690− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1691− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1692− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1693− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1694− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1695− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1696− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1697− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1698− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1699− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1700− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1701−
1702−data Term = Term { termField :: Text
1703− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1704−
1705−data BoolMatch = MustMatch Term Cache
1706− | MustNotMatch Term Cache
1707− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1708−
1709−-- "memory" or "indexed"
1710−data GeoFilterType = GeoFilterMemory
1711− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1712−
1713−data LatLon = LatLon { lat :: Double
1714− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1715−
1716−data GeoBoundingBox =
1717− GeoBoundingBox { topLeft :: LatLon
1718− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1719−
1720−data GeoBoundingBoxConstraint =
1721− GeoBoundingBoxConstraint { geoBBField :: FieldName
1722− , constraintBox :: GeoBoundingBox
1723− , bbConstraintcache :: Cache
1724− , geoType :: GeoFilterType
1725− } deriving (Eq, Read, Show, Generic, Typeable)
1726−
1727−data GeoPoint =
1728− GeoPoint { geoField :: FieldName
1729− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
1730−
1731−data DistanceUnit = Miles
1732− | Yards
1733− | Feet
1734− | Inches
1735− | Kilometers
1736− | Meters
1737− | Centimeters
1738− | Millimeters
1739− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
1740−
1741−data DistanceType = Arc
1742− | SloppyArc -- doesn't exist <1.0
1743− | Plane deriving (Eq, Read, Show, Generic, Typeable)
1744−
1745−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1746− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
1747−
1748−data Distance =
1749− Distance { coefficient :: Double
1750− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1751−
1752−data DistanceRange =
1753− DistanceRange { distanceFrom :: Distance
1754− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
1755−
1756−type TemplateQueryKey = Text
1757−type TemplateQueryValue = Text
1758−
1759−newtype TemplateQueryKeyValuePairs = TemplateQueryKeyValuePairs (HM.HashMap TemplateQueryKey TemplateQueryValue)
1760− deriving (Eq, Read, Show, Generic)
1761−
1762−instance ToJSON TemplateQueryKeyValuePairs where
1763− toJSON (TemplateQueryKeyValuePairs x) = Object $ HM.map toJSON x
1764−
1765−instance FromJSON TemplateQueryKeyValuePairs where
1766− parseJSON (Object o) = pure . TemplateQueryKeyValuePairs $ HM.mapMaybe getValue o
1767− where getValue (String x) = Just x
1768− getValue _ = Nothing
1769− parseJSON _ = fail "error parsing TemplateQueryKeyValuePairs"
1770−
1771−data TemplateQueryInline =
1772− TemplateQueryInline { inline :: Query
1773− , params :: TemplateQueryKeyValuePairs
1774− }
1775− deriving (Eq, Read, Show, Generic, Typeable)
1776−
1777−instance ToJSON TemplateQueryInline where
1778− toJSON TemplateQueryInline{..} = object [ "inline" .= inline
1779− , "params" .= params
1780− ]
1781−
1782−instance FromJSON TemplateQueryInline where
1783− parseJSON = withObject "TemplateQueryInline" parse
1784− where parse o = TemplateQueryInline
1785− <$> o .: "inline"
1786− <*> o .: "params"
1787611
1788612
1789613data SearchResult a =
@@ -1795,16 +619,18 @@ data SearchResult a =
1795619 , scrollId :: Maybe ScrollId
1796620 , suggest :: Maybe NamedSuggestionResponse -- ^ Only one Suggestion request / response per Search is supported.
1797621 }
1798− deriving (Eq, Read, Show, Generic, Typeable)
622+ deriving (Eq, Show)
1799623
1800−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
624+newtype ScrollId =
625+ ScrollId Text
626+ deriving (Eq, Show, Ord, ToJSON, FromJSON)
1801627
1802628type Score = Maybe Double
1803629
1804630data SearchHits a =
1805631 SearchHits { hitsTotal :: Int
1806632 , maxScore :: Score
1807− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
633+ , hits :: [Hit a] } deriving (Eq, Show)
1808634
1809635instance Semigroup (SearchHits a) where
1810636 (SearchHits ta ma ha) <> (SearchHits tb mb hb) = SearchHits (ta + tb) (max ma mb) (ha <> hb)
@@ -1819,25 +645,10 @@ data Hit a =
1819645 , hitDocId :: DocId
1820646 , hitScore :: Score
1821647 , hitSource :: Maybe a
1822− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1823−
1824−data ShardResult =
1825− ShardResult { shardTotal :: Int
1826− , shardsSuccessful :: Int
1827− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
648+ , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show)
1828649
1829650type HitHighlight = M.Map Text [Text]
1830651
1831−showText :: Show a => a -> Text
1832−showText = T.pack . show
1833−
1834−readMay :: Read a => String -> Maybe a
1835−readMay s = case reads s of
1836− (a, ""):_ -> Just a
1837− _ -> Nothing
1838−
1839−parseReadText :: Read a => Text -> Parser a
1840−parseReadText = maybe mzero return . readMay . T.unpack
1841652
1842653type Aggregations = M.Map Text Aggregation
1843654
@@ -1848,34 +659,19 @@ mkAggregations :: Text -> Aggregation -> Aggregations
1848659mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1849660
1850661data TermOrder = TermOrder{ termSortField :: Text
1851− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
662+ , termSortOrder :: SortOrder } deriving (Eq, Show)
1852663
1853664data TermInclusion = TermInclusion Text
1854− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
665+ | TermPattern Text Text deriving (Eq, Show)
1855666
1856667data CollectionMode = BreadthFirst
1857− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
668+ | DepthFirst deriving (Eq, Show)
1858669
1859670data ExecutionHint = Ordinals
1860671 | GlobalOrdinals
1861672 | GlobalOrdinalsHash
1862673 | GlobalOrdinalsLowCardinality
1863− | Map deriving (Eq, Read, Show, Generic, Typeable)
1864−
1865−data TimeInterval = Weeks
1866− | Days
1867− | Hours
1868− | Minutes
1869− | Seconds deriving Eq
1870−
1871−data Interval = Year
1872− | Quarter
1873− | Month
1874− | Week
1875− | Day
1876− | Hour
1877− | Minute
1878− | Second deriving (Eq, Read, Show, Generic, Typeable)
674+ | Map deriving (Eq, Show)
1879675
1880676data Aggregation = TermsAgg TermsAggregation
1881677 | CardinalityAgg CardinalityAggregation
@@ -1886,17 +682,17 @@ data Aggregation = TermsAgg TermsAggregation
1886682 | MissingAgg MissingAggregation
1887683 | TopHitsAgg TopHitsAggregation
1888684 | StatsAgg StatisticsAggregation
1889− deriving (Eq, Read, Show, Generic, Typeable)
685+ deriving (Eq, Show)
1890686
1891687data TopHitsAggregation = TopHitsAggregation
1892688 { taFrom :: Maybe From
1893689 , taSize :: Maybe Size
1894690 , taSort :: Maybe Sort
1895− } deriving (Eq, Read, Show)
691+ } deriving (Eq, Show)
1896692
1897693data MissingAggregation = MissingAggregation
1898694 { maField :: Text
1899− } deriving (Eq, Read, Show, Generic, Typeable)
695+ } deriving (Eq, Show)
1900696
1901697data TermsAggregation = TermsAggregation { term :: Either Text Text
1902698 , termInclude :: Maybe TermInclusion
@@ -1908,71 +704,91 @@ data TermsAggregation = TermsAggregation { term :: Either Text Text
1908704 , termCollectMode :: Maybe CollectionMode
1909705 , termExecutionHint :: Maybe ExecutionHint
1910706 , termAggs :: Maybe Aggregations
1911− } deriving (Eq, Read, Show, Generic, Typeable)
1912−
1913−data CardinalityAggregation = CardinalityAggregation { cardinalityField :: FieldName,
1914− precisionThreshold :: Maybe Int
1915− } deriving (Eq, Read, Show, Generic, Typeable)
1916−
1917−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1918− , dateInterval :: Interval
1919− , dateFormat :: Maybe Text
1920− -- pre and post deprecated in 1.5
1921− , datePreZone :: Maybe Text
1922− , datePostZone :: Maybe Text
1923− , datePreOffset :: Maybe Text
1924− , datePostOffset :: Maybe Text
1925− , dateAggs :: Maybe Aggregations
1926− } deriving (Eq, Read, Show, Generic, Typeable)
1927−
1928−
1929−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1930− , draFormat :: Maybe Text
1931− , draRanges :: NonEmpty DateRangeAggRange
1932− } deriving (Eq, Read, Show, Generic, Typeable)
1933−
1934−data DateRangeAggRange = DateRangeFrom DateMathExpr
1935− | DateRangeTo DateMathExpr
1936− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Read, Show, Generic, Typeable)
707+ } deriving (Eq, Show)
708+
709+data CardinalityAggregation = CardinalityAggregation
710+ { cardinalityField :: FieldName,
711+ precisionThreshold :: Maybe Int
712+ } deriving (Eq, Show)
713+
714+data DateHistogramAggregation = DateHistogramAggregation
715+ { dateField :: FieldName
716+ , dateInterval :: Interval
717+ , dateFormat :: Maybe Text
718+ -- pre and post deprecated in 1.5
719+ , datePreZone :: Maybe Text
720+ , datePostZone :: Maybe Text
721+ , datePreOffset :: Maybe Text
722+ , datePostOffset :: Maybe Text
723+ , dateAggs :: Maybe Aggregations
724+ } deriving (Eq, Show)
725+
726+data DateRangeAggregation = DateRangeAggregation
727+ { draField :: FieldName
728+ , draFormat :: Maybe Text
729+ , draRanges :: NonEmpty DateRangeAggRange
730+ } deriving (Eq, Show)
731+
732+data DateRangeAggRange =
733+ DateRangeFrom DateMathExpr
734+ | DateRangeTo DateMathExpr
735+ | DateRangeFromAndTo DateMathExpr DateMathExpr
736+ deriving (Eq, Show)
1937737
1938738-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1939−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
739+data DateMathExpr =
740+ DateMathExpr DateMathAnchor [DateMathModifier]
741+ deriving (Eq, Show)
1940742
1941743
1942744-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1943−data DateMathAnchor = DMNow
1944− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1945−
1946−data DateMathModifier = AddTime Int DateMathUnit
1947− | SubtractTime Int DateMathUnit
1948− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1949−
1950−data DateMathUnit = DMYear
1951− | DMMonth
1952− | DMWeek
1953− | DMDay
1954− | DMHour
1955− | DMMinute
1956− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
745+data DateMathAnchor =
746+ DMNow
747+ | DMDate Day
748+ deriving (Eq, Show)
749+
750+data DateMathModifier =
751+ AddTime Int DateMathUnit
752+ | SubtractTime Int DateMathUnit
753+ | RoundDownTo DateMathUnit
754+ deriving (Eq, Show)
755+
756+data DateMathUnit =
757+ DMYear
758+ | DMMonth
759+ | DMWeek
760+ | DMDay
761+ | DMHour
762+ | DMMinute
763+ | DMSecond
764+ deriving (Eq, Show)
1957765
1958766-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1959−data ValueCountAggregation = FieldValueCount FieldName
1960− | ScriptValueCount Script deriving (Eq, Read, Show, Generic, Typeable)
767+data ValueCountAggregation =
768+ FieldValueCount FieldName
769+ | ScriptValueCount Script
770+ deriving (Eq, Show)
1961771
1962772-- | 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.
1963−data FilterAggregation = FilterAggregation { faFilter :: Filter
1964− , faAggs :: Maybe Aggregations} deriving (Eq, Read, Show, Generic, Typeable)
773+data FilterAggregation = FilterAggregation
774+ { faFilter :: Filter
775+ , faAggs :: Maybe Aggregations }
776+ deriving (Eq, Show)
1965777
1966−data StatisticsAggregation = StatisticsAggregation { statsType :: StatsType
1967− , statsField :: FieldName } deriving (Eq, Read, Show, Generic, Typeable)
778+data StatisticsAggregation = StatisticsAggregation
779+ { statsType :: StatsType
780+ , statsField :: FieldName }
781+ deriving (Eq, Show)
1968782
1969783data StatsType
1970784 = Basic
1971785 | Extended
1972− deriving (Eq, Read, Show, Generic, Typeable)
786+ deriving (Eq, Show)
1973787
1974788mkTermsAggregation :: Text -> TermsAggregation
1975−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
789+mkTermsAggregation t =
790+ TermsAggregation (Left t)
791+ Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1976792
1977793mkTermsScriptAggregation :: Text -> TermsAggregation
1978794mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
@@ -1989,33 +805,6 @@ mkStatsAggregation = StatisticsAggregation Basic
1989805mkExtendedStatsAggregation :: FieldName -> StatisticsAggregation
1990806mkExtendedStatsAggregation = StatisticsAggregation Extended
1991807
1992−instance ToJSON Version where
1993− toJSON Version {..} = object ["number" .= number
1994− ,"build_hash" .= build_hash
1995− ,"build_date" .= build_date
1996− ,"build_snapshot" .= build_snapshot
1997− ,"lucene_version" .= lucene_version]
1998−
1999−instance FromJSON Version where
2000− parseJSON = withObject "Version" parse
2001− where parse o = Version
2002− <$> o .: "number"
2003− <*> o .: "build_hash"
2004− <*> o .: "build_date"
2005− <*> o .: "build_snapshot"
2006− <*> o .: "lucene_version"
2007−
2008−instance ToJSON VersionNumber where
2009− toJSON = toJSON . Vers.showVersion . versionNumber
2010−
2011−instance FromJSON VersionNumber where
2012− parseJSON = withText "VersionNumber" (parse . T.unpack)
2013− where
2014− parse s = case filter (null . snd)(RP.readP_to_S Vers.parseVersion s) of
2015− [(v, _)] -> pure (VersionNumber v)
2016− [] -> fail ("Invalid version string " ++ s)
2017− xs -> fail ("Ambiguous version string " ++ s ++ " (" ++ intercalate ", " (Vers.showVersion . fst <$> xs) ++ ")")
2018−
2019808instance ToJSON TermOrder where
2020809 toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
2021810
@@ -2045,23 +834,6 @@ instance ToJSON Interval where
2045834 toJSON Minute = "minute"
2046835 toJSON Second = "second"
2047836
2048−instance Show TimeInterval where
2049− show Weeks = "w"
2050− show Days = "d"
2051− show Hours = "h"
2052− show Minutes = "m"
2053− show Seconds = "s"
2054−
2055−instance Read TimeInterval where
2056− readPrec = f =<< TR.get
2057− where
2058− f 'w' = return Weeks
2059− f 'd' = return Days
2060− f 'h' = return Hours
2061− f 'm' = return Minutes
2062− f 's' = return Seconds
2063− f _ = fail "TimeInterval expected one of w, d, h, m, s"
2064−
2065837instance ToJSON Aggregation where
2066838 toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
2067839 omitNulls ["terms" .= omitNulls [ toJSON' term,
@@ -2175,13 +947,15 @@ data DateHistogramResult = DateHistogramResult { dateKey :: Int
2175947 , dateDocCount :: Int
2176948 , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
2177949
2178−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
2179− , dateRangeFrom :: Maybe UTCTime
2180− , dateRangeFromAsString :: Maybe Text
2181− , dateRangeTo :: Maybe UTCTime
2182− , dateRangeToAsString :: Maybe Text
2183− , dateRangeDocCount :: Int
2184− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
950+data DateRangeResult =
951+ DateRangeResult { dateRangeKey :: Text
952+ , dateRangeFrom :: Maybe UTCTime
953+ , dateRangeFromAsString :: Maybe Text
954+ , dateRangeTo :: Maybe UTCTime
955+ , dateRangeToAsString :: Maybe Text
956+ , dateRangeDocCount :: Int
957+ , dateRangeAggs :: Maybe AggregationResults }
958+ deriving (Eq, Show)
2185959
2186960toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
2187961toTerms = toAggResult
@@ -2266,21 +1040,11 @@ instance FromJSON DateRangeResult where
22661040 ]
22671041 )
22681042
2269−instance FromJSON POSIXMS where
2270− parseJSON = withScientific "POSIXMS" (return . parse)
2271− where parse n = let n' = truncate n :: Integer
2272− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
2273−
22741043instance (FromJSON a) => FromJSON (TopHitResult a) where
22751044 parseJSON (Object v) = TopHitResult <$>
22761045 v .: "hits"
22771046 parseJSON _ = fail "Failure in FromJSON (TopHitResult a)"
22781047
2279−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2280−fieldTagged f o = case HM.toList o of
2281− [(k, Object o')] -> f (FieldName k) o'
2282− _ -> fail "Expected object with 1 field-named key"
2283−
22841048-- Try to get an AggregationResults when we don't know the
22851049-- field name. We filter out the known keys to try to minimize the noise.
22861050getNamedSubAgg :: Object -> [Text] -> Maybe AggregationResults
@@ -2295,765 +1059,9 @@ instance ToJSON GeoPoint where
22951059 object [ geoPointField .= geoPointLatLon ]
22961060
22971061
2298−instance ToJSON Query where
2299− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2300− object [ "term" .=
2301− object [termQueryField .= object merged]]
2302− where
2303− base = [ "value" .= termQueryValue ]
2304− boosted = maybe [] (return . ("boost" .=)) boost
2305− merged = mappend base boosted
2306−
2307− toJSON (TermsQuery fieldName terms) =
2308− object [ "terms" .= object conjoined ]
2309− where conjoined = [fieldName .= terms]
2310−
2311− toJSON (IdsQuery idsQueryMappingName docIds) =
2312− object [ "ids" .= object conjoined ]
2313− where conjoined = [ "type" .= idsQueryMappingName
2314− , "values" .= fmap toJSON docIds ]
2315−
2316− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2317− object [ "query_string" .= qQueryStringQuery ]
2318−
2319− toJSON (QueryMatchQuery matchQuery) =
2320− object [ "match" .= matchQuery ]
2321−
2322− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2323− toJSON multiMatchQuery
2324−
2325− toJSON (QueryBoolQuery boolQuery) =
2326− object [ "bool" .= boolQuery ]
2327−
2328− toJSON (QueryBoostingQuery boostingQuery) =
2329− object [ "boosting" .= boostingQuery ]
2330−
2331− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2332− object [ "common" .= commonTermsQuery ]
2333−
2334− toJSON (ConstantScoreQuery query boost) =
2335− object ["constant_score" .= object ["query" .= query
2336− , "boost" .= boost]]
23371062
2338− toJSON (QueryDisMaxQuery disMaxQuery) =
2339− object [ "dis_max" .= disMaxQuery ]
23401063
2341− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2342− object [ "fuzzy_like_this" .= fuzzyQuery ]
23431064
2344− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2345− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2346−
2347− toJSON (QueryFuzzyQuery fuzzyQuery) =
2348− object [ "fuzzy" .= fuzzyQuery ]
2349−
2350− toJSON (QueryHasChildQuery childQuery) =
2351− object [ "has_child" .= childQuery ]
2352−
2353− toJSON (QueryHasParentQuery parentQuery) =
2354− object [ "has_parent" .= parentQuery ]
2355−
2356− toJSON (QueryIndicesQuery qIndicesQuery) =
2357− object [ "indices" .= qIndicesQuery ]
2358−
2359− toJSON (MatchAllQuery boost) =
2360− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2361−
2362− toJSON (QueryMoreLikeThisQuery query) =
2363− object [ "more_like_this" .= query ]
2364−
2365− toJSON (QueryMoreLikeThisFieldQuery query) =
2366− object [ "more_like_this_field" .= query ]
2367−
2368− toJSON (QueryNestedQuery query) =
2369− object [ "nested" .= query ]
2370−
2371− toJSON (QueryPrefixQuery query) =
2372− object [ "prefix" .= query ]
2373−
2374− toJSON (QueryRangeQuery query) =
2375− object [ "range" .= query ]
2376−
2377− toJSON (QueryRegexpQuery query) =
2378− object [ "regexp" .= query ]
2379−
2380− toJSON (QuerySimpleQueryStringQuery query) =
2381− object [ "simple_query_string" .= query ]
2382−
2383− toJSON (QueryExistsQuery (FieldName fieldName)) =
2384− object ["exists" .= object
2385− ["field" .= fieldName]
2386− ]
2387− toJSON QueryMatchNoneQuery =
2388− object ["match_none" .= object []]
2389−
2390− toJSON (QueryTemplateQueryInline templateQuery) =
2391− object [ "template" .= templateQuery ]
2392−
2393−instance FromJSON Query where
2394− parseJSON v = withObject "Query" parse v
2395− where parse o = termQuery `taggedWith` "term"
2396− <|> termsQuery `taggedWith` "terms"
2397− <|> idsQuery `taggedWith` "ids"
2398− <|> queryQueryStringQuery `taggedWith` "query_string"
2399− <|> queryMatchQuery `taggedWith` "match"
2400− <|> queryMultiMatchQuery
2401− <|> queryBoolQuery `taggedWith` "bool"
2402− <|> queryBoostingQuery `taggedWith` "boosting"
2403− <|> queryCommonTermsQuery `taggedWith` "common"
2404− <|> constantScoreQuery `taggedWith` "constant_score"
2405− <|> queryDisMaxQuery `taggedWith` "dis_max"
2406− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2407− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2408− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2409− <|> queryHasChildQuery `taggedWith` "has_child"
2410− <|> queryHasParentQuery `taggedWith` "has_parent"
2411− <|> queryIndicesQuery `taggedWith` "indices"
2412− <|> matchAllQuery `taggedWith` "match_all"
2413− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2414− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2415− <|> queryNestedQuery `taggedWith` "nested"
2416− <|> queryPrefixQuery `taggedWith` "prefix"
2417− <|> queryRangeQuery `taggedWith` "range"
2418− <|> queryRegexpQuery `taggedWith` "regexp"
2419− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2420− <|> queryTemplateQueryInline `taggedWith` "template"
2421− where taggedWith parser k = parser =<< o .: k
2422− termQuery = fieldTagged $ \(FieldName fn) o ->
2423− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2424− termsQuery o = case HM.toList o of
2425− [(fn, vs)] -> do vals <- parseJSON vs
2426− case vals of
2427− x:xs -> return (TermsQuery fn (x :| xs))
2428− _ -> fail "Expected non empty list of values"
2429− _ -> fail "Expected object with 1 field-named key"
2430− idsQuery o = IdsQuery <$> o .: "type"
2431− <*> o .: "values"
2432− queryQueryStringQuery = pure . QueryQueryStringQuery
2433− queryMatchQuery = pure . QueryMatchQuery
2434− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2435− queryBoolQuery = pure . QueryBoolQuery
2436− queryBoostingQuery = pure . QueryBoostingQuery
2437− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2438− constantScoreQuery o = case HM.lookup "query" o of
2439− Just x -> ConstantScoreQuery <$> parseJSON x
2440− <*> o .: "boost"
2441− _ -> fail "Does not appear to be a ConstantScoreQuery"
2442− queryDisMaxQuery = pure . QueryDisMaxQuery
2443− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2444− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2445− queryFuzzyQuery = pure . QueryFuzzyQuery
2446− queryHasChildQuery = pure . QueryHasChildQuery
2447− queryHasParentQuery = pure . QueryHasParentQuery
2448− queryIndicesQuery = pure . QueryIndicesQuery
2449− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2450− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2451− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2452− queryNestedQuery = pure . QueryNestedQuery
2453− queryPrefixQuery = pure . QueryPrefixQuery
2454− queryRangeQuery = pure . QueryRangeQuery
2455− queryRegexpQuery = pure . QueryRegexpQuery
2456− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2457− -- queryExistsQuery o = QueryExistsQuery <$> o .: "field"
2458− queryTemplateQueryInline = pure . QueryTemplateQueryInline
2459−
2460−
2461−omitNulls :: [(Text, Value)] -> Value
2462−omitNulls = object . filter notNull where
2463− notNull (_, Null) = False
2464− notNull (_, Array a) = (not . V.null) a
2465− notNull _ = True
2466−
2467−instance ToJSON SimpleQueryStringQuery where
2468− toJSON SimpleQueryStringQuery {..} =
2469− omitNulls (base ++ maybeAdd)
2470− where base = [ "query" .= simpleQueryStringQuery ]
2471− maybeAdd = [ "fields" .= simpleQueryStringField
2472− , "default_operator" .= simpleQueryStringOperator
2473− , "analyzer" .= simpleQueryStringAnalyzer
2474− , "flags" .= simpleQueryStringFlags
2475− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2476− , "locale" .= simpleQueryStringLocale ]
2477−
2478−instance FromJSON SimpleQueryStringQuery where
2479− parseJSON = withObject "SimpleQueryStringQuery" parse
2480− where parse o = SimpleQueryStringQuery <$> o .: "query"
2481− <*> o .:? "fields"
2482− <*> o .:? "default_operator"
2483− <*> o .:? "analyzer"
2484− <*> (parseFlags <$> o .:? "flags")
2485− <*> o .:? "lowercase_expanded_terms"
2486− <*> o .:? "locale"
2487− parseFlags (Just (x:xs)) = Just (x :| xs)
2488− parseFlags _ = Nothing
2489−
2490−instance ToJSON FieldOrFields where
2491− toJSON (FofField fieldName) =
2492− toJSON fieldName
2493− toJSON (FofFields fieldNames) =
2494− toJSON fieldNames
2495−
2496−instance FromJSON FieldOrFields where
2497− parseJSON v = FofField <$> parseJSON v
2498− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2499−
2500−instance ToJSON SimpleQueryFlag where
2501− toJSON SimpleQueryAll = "ALL"
2502− toJSON SimpleQueryNone = "NONE"
2503− toJSON SimpleQueryAnd = "AND"
2504− toJSON SimpleQueryOr = "OR"
2505− toJSON SimpleQueryPrefix = "PREFIX"
2506− toJSON SimpleQueryPhrase = "PHRASE"
2507− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2508− toJSON SimpleQueryEscape = "ESCAPE"
2509− toJSON SimpleQueryWhitespace = "WHITESPACE"
2510− toJSON SimpleQueryFuzzy = "FUZZY"
2511− toJSON SimpleQueryNear = "NEAR"
2512− toJSON SimpleQuerySlop = "SLOP"
2513−
2514−instance FromJSON SimpleQueryFlag where
2515− parseJSON = withText "SimpleQueryFlag" parse
2516− where parse "ALL" = pure SimpleQueryAll
2517− parse "NONE" = pure SimpleQueryNone
2518− parse "AND" = pure SimpleQueryAnd
2519− parse "OR" = pure SimpleQueryOr
2520− parse "PREFIX" = pure SimpleQueryPrefix
2521− parse "PHRASE" = pure SimpleQueryPhrase
2522− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2523− parse "ESCAPE" = pure SimpleQueryEscape
2524− parse "WHITESPACE" = pure SimpleQueryWhitespace
2525− parse "FUZZY" = pure SimpleQueryFuzzy
2526− parse "NEAR" = pure SimpleQueryNear
2527− parse "SLOP" = pure SimpleQuerySlop
2528− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2529−
2530−instance ToJSON RegexpQuery where
2531− toJSON (RegexpQuery (FieldName rqQueryField)
2532− (Regexp regexpQueryQuery) rqQueryFlags
2533− rqQueryBoost) =
2534− object [ rqQueryField .= omitNulls base ]
2535− where base = [ "value" .= regexpQueryQuery
2536− , "flags" .= rqQueryFlags
2537− , "boost" .= rqQueryBoost ]
2538−
2539−instance FromJSON RegexpQuery where
2540− parseJSON = withObject "RegexpQuery" parse
2541− where parse = fieldTagged $ \fn o ->
2542− RegexpQuery fn
2543− <$> o .: "value"
2544− <*> o .: "flags"
2545− <*> o .:? "boost"
2546−
2547−instance ToJSON QueryStringQuery where
2548− toJSON (QueryStringQuery qsQueryString
2549− qsDefaultField qsOperator
2550− qsAnalyzer qsAllowWildcard
2551− qsLowercaseExpanded qsEnablePositionIncrements
2552− qsFuzzyMaxExpansions qsFuzziness
2553− qsFuzzyPrefixLength qsPhraseSlop
2554− qsBoost qsAnalyzeWildcard
2555− qsGeneratePhraseQueries qsMinimumShouldMatch
2556− qsLenient qsLocale) =
2557− omitNulls base
2558− where
2559− base = [ "query" .= qsQueryString
2560− , "default_field" .= qsDefaultField
2561− , "default_operator" .= qsOperator
2562− , "analyzer" .= qsAnalyzer
2563− , "allow_leading_wildcard" .= qsAllowWildcard
2564− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2565− , "enable_position_increments" .= qsEnablePositionIncrements
2566− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2567− , "fuzziness" .= qsFuzziness
2568− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2569− , "phrase_slop" .= qsPhraseSlop
2570− , "boost" .= qsBoost
2571− , "analyze_wildcard" .= qsAnalyzeWildcard
2572− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2573− , "minimum_should_match" .= qsMinimumShouldMatch
2574− , "lenient" .= qsLenient
2575− , "locale" .= qsLocale ]
2576−
2577−instance FromJSON QueryStringQuery where
2578− parseJSON = withObject "QueryStringQuery" parse
2579− where parse o = QueryStringQuery
2580− <$> o .: "query"
2581− <*> o .:? "default_field"
2582− <*> o .:? "default_operator"
2583− <*> o .:? "analyzer"
2584− <*> o .:? "allow_leading_wildcard"
2585− <*> o .:? "lowercase_expanded_terms"
2586− <*> o .:? "enable_position_increments"
2587− <*> o .:? "fuzzy_max_expansions"
2588− <*> o .:? "fuzziness"
2589− <*> o .:? "fuzzy_prefix_length"
2590− <*> o .:? "phrase_slop"
2591− <*> o .:? "boost"
2592− <*> o .:? "analyze_wildcard"
2593− <*> o .:? "auto_generate_phrase_queries"
2594− <*> o .:? "minimum_should_match"
2595− <*> o .:? "lenient"
2596− <*> o .:? "locale"
2597−
2598−instance ToJSON RangeQuery where
2599− toJSON (RangeQuery (FieldName fieldName) range boost) =
2600− object [ fieldName .= object conjoined ]
2601− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2602−
2603−instance FromJSON RangeQuery where
2604− parseJSON = withObject "RangeQuery" parse
2605− where parse = fieldTagged $ \fn o ->
2606− RangeQuery fn
2607− <$> parseJSON (Object o)
2608− <*> o .: "boost"
2609−
2610−instance FromJSON RangeValue where
2611− parseJSON = withObject "RangeValue" parse
2612− where parse o = parseDate o
2613− <|> parseDouble o
2614− parseDate o = do lt <- o .:? "lt"
2615− lte <- o .:? "lte"
2616− gt <- o .:? "gt"
2617− gte <- o .:? "gte"
2618− case (lt, lte, gt, gte) of
2619− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2620− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2621− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2622− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2623− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2624− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2625− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2626− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2627− (Nothing, Nothing, Nothing, Nothing) -> mzero
2628− parseDouble o = do lt <- o .:? "lt"
2629− lte <- o .:? "lte"
2630− gt <- o .:? "gt"
2631− gte <- o .:? "gte"
2632− case (lt, lte, gt, gte) of
2633− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2634− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2635− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2636− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2637− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2638− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2639− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2640− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2641− (Nothing, Nothing, Nothing, Nothing) -> mzero
2642−
2643−instance ToJSON PrefixQuery where
2644− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2645− object [ fieldName .= omitNulls base ]
2646− where base = [ "value" .= queryValue
2647− , "boost" .= boost ]
2648−
2649−instance FromJSON PrefixQuery where
2650− parseJSON = withObject "PrefixQuery" parse
2651− where parse = fieldTagged $ \fn o ->
2652− PrefixQuery fn
2653− <$> o .: "value"
2654− <*> o .:? "boost"
2655−
2656−instance ToJSON NestedQuery where
2657− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2658− object [ "path" .= nqPath
2659− , "score_mode" .= nqScoreType
2660− , "query" .= nqQuery ]
2661−
2662−instance FromJSON NestedQuery where
2663− parseJSON = withObject "NestedQuery" parse
2664− where parse o = NestedQuery
2665− <$> o .: "path"
2666− <*> o .: "score_mode"
2667− <*> o .: "query"
2668−
2669−instance ToJSON MoreLikeThisFieldQuery where
2670− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2671− percent mtf mqt stopwords mindf maxdf
2672− minwl maxwl boostTerms boost analyzer) =
2673− object [ fieldName .= omitNulls base ]
2674− where base = [ "like_text" .= text
2675− , "percent_terms_to_match" .= percent
2676− , "min_term_freq" .= mtf
2677− , "max_query_terms" .= mqt
2678− , "stop_words" .= stopwords
2679− , "min_doc_freq" .= mindf
2680− , "max_doc_freq" .= maxdf
2681− , "min_word_length" .= minwl
2682− , "max_word_length" .= maxwl
2683− , "boost_terms" .= boostTerms
2684− , "boost" .= boost
2685− , "analyzer" .= analyzer ]
2686−
2687−instance FromJSON MoreLikeThisFieldQuery where
2688− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2689− where parse = fieldTagged $ \fn o ->
2690− MoreLikeThisFieldQuery
2691− <$> o .: "like_text"
2692− <*> pure fn
2693− <*> o .:? "percent_terms_to_match"
2694− <*> o .:? "min_term_freq"
2695− <*> o .:? "max_query_terms"
2696− -- <*> (optionalNE =<< o .:? "stop_words")
2697− <*> o .:? "stop_words"
2698− <*> o .:? "min_doc_freq"
2699− <*> o .:? "max_doc_freq"
2700− <*> o .:? "min_word_length"
2701− <*> o .:? "max_word_length"
2702− <*> o .:? "boost_terms"
2703− <*> o .:? "boost"
2704− <*> o .:? "analyzer"
2705− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2706−
2707−instance ToJSON MoreLikeThisQuery where
2708− toJSON (MoreLikeThisQuery text fields percent
2709− mtf mqt stopwords mindf maxdf
2710− minwl maxwl boostTerms boost analyzer) =
2711− omitNulls base
2712− where base = [ "like_text" .= text
2713− , "fields" .= fields
2714− , "percent_terms_to_match" .= percent
2715− , "min_term_freq" .= mtf
2716− , "max_query_terms" .= mqt
2717− , "stop_words" .= stopwords
2718− , "min_doc_freq" .= mindf
2719− , "max_doc_freq" .= maxdf
2720− , "min_word_length" .= minwl
2721− , "max_word_length" .= maxwl
2722− , "boost_terms" .= boostTerms
2723− , "boost" .= boost
2724− , "analyzer" .= analyzer ]
2725−
2726−instance FromJSON MoreLikeThisQuery where
2727− parseJSON = withObject "MoreLikeThisQuery" parse
2728− where parse o = MoreLikeThisQuery
2729− <$> o .: "like_text"
2730− -- <*> (optionalNE =<< o .:? "fields")
2731− <*> o .:? "fields"
2732− <*> o .:? "percent_terms_to_match"
2733− <*> o .:? "min_term_freq"
2734− <*> o .:? "max_query_terms"
2735− -- <*> (optionalNE =<< o .:? "stop_words")
2736− <*> o .:? "stop_words"
2737− <*> o .:? "min_doc_freq"
2738− <*> o .:? "max_doc_freq"
2739− <*> o .:? "min_word_length"
2740− <*> o .:? "max_word_length"
2741− <*> o .:? "boost_terms"
2742− <*> o .:? "boost"
2743− <*> o .:? "analyzer"
2744− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2745−
2746−instance ToJSON IndicesQuery where
2747− toJSON (IndicesQuery indices query noMatch) =
2748− omitNulls [ "indices" .= indices
2749− , "no_match_query" .= noMatch
2750− , "query" .= query ]
2751−
2752−instance FromJSON IndicesQuery where
2753− parseJSON = withObject "IndicesQuery" parse
2754− where parse o = IndicesQuery
2755− <$> o .:? "indices" .!= []
2756− <*> o .: "query"
2757− <*> o .:? "no_match_query"
2758−
2759−instance ToJSON HasParentQuery where
2760− toJSON (HasParentQuery queryType query scoreType) =
2761− omitNulls [ "parent_type" .= queryType
2762− , "score_type" .= scoreType
2763− , "query" .= query ]
2764−
2765−instance FromJSON HasParentQuery where
2766− parseJSON = withObject "HasParentQuery" parse
2767− where parse o = HasParentQuery
2768− <$> o .: "parent_type"
2769− <*> o .: "query"
2770− <*> o .:? "score_type"
2771−
2772−instance ToJSON HasChildQuery where
2773− toJSON (HasChildQuery queryType query scoreType) =
2774− omitNulls [ "query" .= query
2775− , "score_type" .= scoreType
2776− , "type" .= queryType ]
2777−
2778−instance FromJSON HasChildQuery where
2779− parseJSON = withObject "HasChildQuery" parse
2780− where parse o = HasChildQuery
2781− <$> o .: "type"
2782− <*> o .: "query"
2783− <*> o .:? "score_type"
2784−
2785−instance ToJSON FuzzyQuery where
2786− toJSON (FuzzyQuery (FieldName fieldName) queryText
2787− prefixLength maxEx fuzziness boost) =
2788− object [ fieldName .= omitNulls base ]
2789− where base = [ "value" .= queryText
2790− , "fuzziness" .= fuzziness
2791− , "prefix_length" .= prefixLength
2792− , "boost" .= boost
2793− , "max_expansions" .= maxEx ]
2794−
2795−instance FromJSON FuzzyQuery where
2796− parseJSON = withObject "FuzzyQuery" parse
2797− where parse = fieldTagged $ \fn o ->
2798− FuzzyQuery fn
2799− <$> o .: "value"
2800− <*> o .: "prefix_length"
2801− <*> o .: "max_expansions"
2802− <*> o .: "fuzziness"
2803− <*> o .:? "boost"
2804−
2805−instance ToJSON FuzzyLikeFieldQuery where
2806− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2807− fieldText maxTerms ignoreFreq fuzziness prefixLength
2808− boost analyzer) =
2809− object [ fieldName .=
2810− omitNulls [ "like_text" .= fieldText
2811− , "max_query_terms" .= maxTerms
2812− , "ignore_tf" .= ignoreFreq
2813− , "fuzziness" .= fuzziness
2814− , "prefix_length" .= prefixLength
2815− , "analyzer" .= analyzer
2816− , "boost" .= boost ]]
2817−
2818−instance FromJSON FuzzyLikeFieldQuery where
2819− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2820− where parse = fieldTagged $ \fn o ->
2821− FuzzyLikeFieldQuery fn
2822− <$> o .: "like_text"
2823− <*> o .: "max_query_terms"
2824− <*> o .: "ignore_tf"
2825− <*> o .: "fuzziness"
2826− <*> o .: "prefix_length"
2827− <*> o .: "boost"
2828− <*> o .:? "analyzer"
2829−
2830−instance ToJSON FuzzyLikeThisQuery where
2831− toJSON (FuzzyLikeThisQuery fields text maxTerms
2832− ignoreFreq fuzziness prefixLength boost analyzer) =
2833− omitNulls base
2834− where base = [ "fields" .= fields
2835− , "like_text" .= text
2836− , "max_query_terms" .= maxTerms
2837− , "ignore_tf" .= ignoreFreq
2838− , "fuzziness" .= fuzziness
2839− , "prefix_length" .= prefixLength
2840− , "analyzer" .= analyzer
2841− , "boost" .= boost ]
2842−
2843−instance FromJSON FuzzyLikeThisQuery where
2844− parseJSON = withObject "FuzzyLikeThisQuery" parse
2845− where parse o = FuzzyLikeThisQuery
2846− <$> o .:? "fields" .!= []
2847− <*> o .: "like_text"
2848− <*> o .: "max_query_terms"
2849− <*> o .: "ignore_tf"
2850− <*> o .: "fuzziness"
2851− <*> o .: "prefix_length"
2852− <*> o .: "boost"
2853− <*> o .:? "analyzer"
2854−
2855−instance ToJSON DisMaxQuery where
2856− toJSON (DisMaxQuery queries tiebreaker boost) =
2857− omitNulls base
2858− where base = [ "queries" .= queries
2859− , "boost" .= boost
2860− , "tie_breaker" .= tiebreaker ]
2861−
2862−instance FromJSON DisMaxQuery where
2863− parseJSON = withObject "DisMaxQuery" parse
2864− where parse o = DisMaxQuery
2865− <$> o .:? "queries" .!= []
2866− <*> o .: "tie_breaker"
2867− <*> o .:? "boost"
2868−
2869−instance ToJSON CommonTermsQuery where
2870− toJSON (CommonTermsQuery (FieldName fieldName)
2871− (QueryString query) cf lfo hfo msm
2872− boost analyzer disableCoord) =
2873− object [fieldName .= omitNulls base ]
2874− where base = [ "query" .= query
2875− , "cutoff_frequency" .= cf
2876− , "low_freq_operator" .= lfo
2877− , "minimum_should_match" .= msm
2878− , "boost" .= boost
2879− , "analyzer" .= analyzer
2880− , "disable_coord" .= disableCoord
2881− , "high_freq_operator" .= hfo ]
2882−
2883−instance FromJSON CommonTermsQuery where
2884− parseJSON = withObject "CommonTermsQuery" parse
2885− where parse = fieldTagged $ \fn o ->
2886− CommonTermsQuery fn
2887− <$> o .: "query"
2888− <*> o .: "cutoff_frequency"
2889− <*> o .: "low_freq_operator"
2890− <*> o .: "high_freq_operator"
2891− <*> o .:? "minimum_should_match"
2892− <*> o .:? "boost"
2893− <*> o .:? "analyzer"
2894− <*> o .:? "disable_coord"
2895−
2896−instance ToJSON CommonMinimumMatch where
2897− toJSON (CommonMinimumMatch mm) = toJSON mm
2898− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2899− object [ "low_freq" .= lowF
2900− , "high_freq" .= highF ]
2901−
2902−instance FromJSON CommonMinimumMatch where
2903− parseJSON v = parseMinimum v
2904− <|> parseMinimumHighLow v
2905− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2906− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2907− MinimumMatchHighLow
2908− <$> o .: "low_freq"
2909− <*> o .: "high_freq")
2910−
2911−
2912−instance ToJSON BoostingQuery where
2913− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2914− object [ "positive" .= bqPositiveQuery
2915− , "negative" .= bqNegativeQuery
2916− , "negative_boost" .= bqNegativeBoost ]
2917−
2918−instance FromJSON BoostingQuery where
2919− parseJSON = withObject "BoostingQuery" parse
2920− where parse o = BoostingQuery
2921− <$> o .: "positive"
2922− <*> o .: "negative"
2923− <*> o .: "negative_boost"
2924−
2925−instance ToJSON BoolQuery where
2926− toJSON (BoolQuery mustM filterM' notM shouldM bqMin boost disableCoord) =
2927− omitNulls base
2928− where base = [ "must" .= mustM
2929− , "filter" .= filterM'
2930− , "must_not" .= notM
2931− , "should" .= shouldM
2932− , "minimum_should_match" .= bqMin
2933− , "boost" .= boost
2934− , "disable_coord" .= disableCoord ]
2935−
2936−instance FromJSON BoolQuery where
2937− parseJSON = withObject "BoolQuery" parse
2938− where parse o = BoolQuery
2939− <$> o .:? "must" .!= []
2940− <*> o .:? "filter" .!= []
2941− <*> o .:? "must_not" .!= []
2942− <*> o .:? "should" .!= []
2943− <*> o .:? "minimum_should_match"
2944− <*> o .:? "boost"
2945− <*> o .:? "disable_coord"
2946−
2947−instance ToJSON MatchQuery where
2948− toJSON (MatchQuery (FieldName fieldName)
2949− (QueryString mqQueryString) booleanOperator
2950− zeroTermsQuery cutoffFrequency matchQueryType
2951− analyzer maxExpansions lenient boost
2952− minShouldMatch
2953− ) =
2954− object [ fieldName .= omitNulls base ]
2955− where base = [ "query" .= mqQueryString
2956− , "operator" .= booleanOperator
2957− , "zero_terms_query" .= zeroTermsQuery
2958− , "cutoff_frequency" .= cutoffFrequency
2959− , "type" .= matchQueryType
2960− , "analyzer" .= analyzer
2961− , "max_expansions" .= maxExpansions
2962− , "lenient" .= lenient
2963− , "boost" .= boost
2964− , "minimum_should_match" .= minShouldMatch
2965− ]
2966−
2967−instance FromJSON MatchQuery where
2968− parseJSON = withObject "MatchQuery" parse
2969− where parse = fieldTagged $ \fn o ->
2970− MatchQuery fn
2971− <$> o .: "query"
2972− <*> o .: "operator"
2973− <*> o .: "zero_terms_query"
2974− <*> o .:? "cutoff_frequency"
2975− <*> o .:? "type"
2976− <*> o .:? "analyzer"
2977− <*> o .:? "max_expansions"
2978− <*> o .:? "lenient"
2979− <*> o .:? "boost"
2980− <*> o .:? "minimum_should_match"
2981−
2982−instance ToJSON MultiMatchQuery where
2983− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2984− ztQ tb mmqt cf analyzer maxEx lenient) =
2985− object ["multi_match" .= omitNulls base]
2986− where base = [ "fields" .= fmap toJSON fields
2987− , "query" .= query
2988− , "operator" .= boolOp
2989− , "zero_terms_query" .= ztQ
2990− , "tie_breaker" .= tb
2991− , "type" .= mmqt
2992− , "cutoff_frequency" .= cf
2993− , "analyzer" .= analyzer
2994− , "max_expansions" .= maxEx
2995− , "lenient" .= lenient ]
2996−
2997−instance FromJSON MultiMatchQuery where
2998− parseJSON = withObject "MultiMatchQuery" parse
2999− where parse raw = do o <- raw .: "multi_match"
3000− MultiMatchQuery
3001− <$> o .:? "fields" .!= []
3002− <*> o .: "query"
3003− <*> o .: "operator"
3004− <*> o .: "zero_terms_query"
3005− <*> o .:? "tie_breaker"
3006− <*> o .:? "type"
3007− <*> o .:? "cutoff_frequency"
3008− <*> o .:? "analyzer"
3009− <*> o .:? "max_expansions"
3010− <*> o .:? "lenient"
3011−
3012−instance ToJSON MultiMatchQueryType where
3013− toJSON MultiMatchBestFields = "best_fields"
3014− toJSON MultiMatchMostFields = "most_fields"
3015− toJSON MultiMatchCrossFields = "cross_fields"
3016− toJSON MultiMatchPhrase = "phrase"
3017− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
3018−
3019−instance FromJSON MultiMatchQueryType where
3020− parseJSON = withText "MultiMatchPhrasePrefix" parse
3021− where parse "best_fields" = pure MultiMatchBestFields
3022− parse "most_fields" = pure MultiMatchMostFields
3023− parse "cross_fields" = pure MultiMatchCrossFields
3024− parse "phrase" = pure MultiMatchPhrase
3025− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
3026− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
3027−
3028−instance ToJSON BooleanOperator where
3029− toJSON And = String "and"
3030− toJSON Or = String "or"
3031−
3032−instance FromJSON BooleanOperator where
3033− parseJSON = withText "BooleanOperator" parse
3034− where parse "and" = pure And
3035− parse "or" = pure Or
3036− parse o = fail ("Unexpected BooleanOperator: " <> show o)
3037−
3038−instance ToJSON ZeroTermsQuery where
3039− toJSON ZeroTermsNone = String "none"
3040− toJSON ZeroTermsAll = String "all"
3041−
3042−instance FromJSON ZeroTermsQuery where
3043− parseJSON = withText "ZeroTermsQuery" parse
3044− where parse "none" = pure ZeroTermsNone
3045− parse "all" = pure ZeroTermsAll
3046− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
3047−
3048−instance ToJSON MatchQueryType where
3049− toJSON MatchPhrase = "phrase"
3050− toJSON MatchPhrasePrefix = "phrase_prefix"
3051−
3052−instance FromJSON MatchQueryType where
3053− parseJSON = withText "MatchQueryType" parse
3054− where parse "phrase" = pure MatchPhrase
3055− parse "phrase_prefix" = pure MatchPhrasePrefix
3056− parse t = fail ("Unexpected MatchQueryType: " <> show t)
30571065
30581066instance FromJSON Status where
30591067 parseJSON (Object v) = Status <$>
@@ -3064,7 +1072,6 @@ instance FromJSON Status where
30641072 v .: "tagline"
30651073 parseJSON _ = empty
30661074
3067−
30681075instance ToJSON IndexSettings where
30691076 toJSON (IndexSettings s r) = object ["settings" .=
30701077 object ["index" .=
@@ -3191,18 +1198,6 @@ instance FromJSON IndexSettingsSummary where
31911198 redundant (NumberOfReplicas _) = True
31921199 redundant _ = False
31931200
3194−-- | For some reason in several settings APIs, all leaf values get returned
3195−-- as strings. This function attepmts to recover from this for all
3196−-- non-recursive JSON types. If nothing can be done, the value is left alone.
3197−unStringlyTypeJSON :: Value -> Value
3198−unStringlyTypeJSON (String "true") = Bool True
3199−unStringlyTypeJSON (String "false") = Bool False
3200−unStringlyTypeJSON (String "null") = Null
3201−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
3202− Just n -> Number n
3203− Nothing -> v
3204−unStringlyTypeJSON v = v
3205−
32061201
32071202parseSettings :: Object -> Parser [UpdatableIndexSetting]
32081203parseSettings o = do
@@ -3482,9 +1477,6 @@ fastVectorHighPairs (Just
34821477 ++ commonHighlightPairs fvCom
34831478 ++ nonPostingsToPairs fvNonPostSettings
34841479
3485−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3486−deleteSeveral ks hm = foldr HM.delete hm ks
3487−
34881480commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
34891481commonHighlightPairs Nothing = []
34901482commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
@@ -3505,10 +1497,6 @@ nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
35051497 [ "fragment_size" .= npFragSize
35061498 , "number_of_fragments" .= npNumOfFrags]
35071499
3508−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3509−parseNEJSON [] = fail "Expected non-empty list"
3510−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3511−
35121500
35131501instance ToJSON HighlightEncoder where
35141502 toJSON DefaultEncoder = String "default"
@@ -3555,204 +1543,6 @@ instance ToJSON Missing where
35551543 toJSON (CustomMissing txt) = String txt
35561544
35571545
3558−instance ToJSON ScoreType where
3559− toJSON ScoreTypeMax = "max"
3560− toJSON ScoreTypeAvg = "avg"
3561− toJSON ScoreTypeSum = "sum"
3562− toJSON ScoreTypeNone = "none"
3563−
3564−instance FromJSON ScoreType where
3565− parseJSON = withText "ScoreType" parse
3566− where parse "max" = pure ScoreTypeMax
3567− parse "avg" = pure ScoreTypeAvg
3568− parse "sum" = pure ScoreTypeSum
3569− parse "none" = pure ScoreTypeNone
3570− parse t = fail ("Unexpected ScoreType: " <> show t)
3571−
3572−instance ToJSON Distance where
3573− toJSON (Distance dCoefficient dUnit) =
3574− String boltedTogether where
3575− coefText = showText dCoefficient
3576− (String unitText) = toJSON dUnit
3577− boltedTogether = mappend coefText unitText
3578−
3579−instance FromJSON Distance where
3580− parseJSON = withText "Distance" parse
3581− where parse t = Distance <$> parseCoeff nT
3582− <*> parseJSON (String unitT)
3583− where (nT, unitT) = T.span validForNumber t
3584− -- may be a better way to do this
3585− validForNumber '-' = True
3586− validForNumber '.' = True
3587− validForNumber 'e' = True
3588− validForNumber c = isNumber c
3589− parseCoeff "" = fail "Empty string cannot be parsed as number"
3590− parseCoeff s = return (read (T.unpack s))
3591−
3592−instance ToJSON DistanceUnit where
3593− toJSON Miles = String "mi"
3594− toJSON Yards = String "yd"
3595− toJSON Feet = String "ft"
3596− toJSON Inches = String "in"
3597− toJSON Kilometers = String "km"
3598− toJSON Meters = String "m"
3599− toJSON Centimeters = String "cm"
3600− toJSON Millimeters = String "mm"
3601− toJSON NauticalMiles = String "nmi"
3602−
3603−
3604−instance FromJSON DistanceUnit where
3605− parseJSON = withText "DistanceUnit" parse
3606− where parse "mi" = pure Miles
3607− parse "yd" = pure Yards
3608− parse "ft" = pure Feet
3609− parse "in" = pure Inches
3610− parse "km" = pure Kilometers
3611− parse "m" = pure Meters
3612− parse "cm" = pure Centimeters
3613− parse "mm" = pure Millimeters
3614− parse "nmi" = pure NauticalMiles
3615− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3616−
3617−instance ToJSON DistanceType where
3618− toJSON Arc = String "arc"
3619− toJSON SloppyArc = String "sloppy_arc"
3620− toJSON Plane = String "plane"
3621−
3622−instance FromJSON DistanceType where
3623− parseJSON = withText "DistanceType" parse
3624− where parse "arc" = pure Arc
3625− parse "sloppy_arc" = pure SloppyArc
3626− parse "plane" = pure Plane
3627− parse t = fail ("Unrecognized DistanceType: " <> show t)
3628−
3629−
3630−instance ToJSON OptimizeBbox where
3631− toJSON NoOptimizeBbox = String "none"
3632− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3633−
3634−instance FromJSON OptimizeBbox where
3635− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3636− <|> parseOptimize v
3637− where parseNoOptimize "none" = pure NoOptimizeBbox
3638− parseNoOptimize _ = mzero
3639− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3640−
3641−instance ToJSON GeoBoundingBoxConstraint where
3642− toJSON (GeoBoundingBoxConstraint
3643− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3644− object [gbbcGeoBBField .= gbbcConstraintBox
3645− , "_cache" .= cache
3646− , "type" .= type']
3647−
3648−instance FromJSON GeoBoundingBoxConstraint where
3649− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3650− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3651− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3652− <$> parseJSON v
3653− <*> o .:? "_cache" .!= defaultCache
3654− <*> o .: "type"
3655− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3656−
3657−instance ToJSON GeoFilterType where
3658− toJSON GeoFilterMemory = String "memory"
3659− toJSON GeoFilterIndexed = String "indexed"
3660−
3661−instance FromJSON GeoFilterType where
3662− parseJSON = withText "GeoFilterType" parse
3663− where parse "memory" = pure GeoFilterMemory
3664− parse "indexed" = pure GeoFilterIndexed
3665− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3666−
3667−instance ToJSON GeoBoundingBox where
3668− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3669− object ["top_left" .= gbbTopLeft
3670− , "bottom_right" .= gbbBottomRight]
3671−
3672−instance FromJSON GeoBoundingBox where
3673− parseJSON = withObject "GeoBoundingBox" parse
3674− where parse o = GeoBoundingBox
3675− <$> o .: "top_left"
3676− <*> o .: "bottom_right"
3677−
3678−instance ToJSON LatLon where
3679− toJSON (LatLon lLat lLon) =
3680− object ["lat" .= lLat
3681− , "lon" .= lLon]
3682−
3683−instance FromJSON LatLon where
3684− parseJSON = withObject "LatLon" parse
3685− where parse o = LatLon <$> o .: "lat"
3686− <*> o .: "lon"
3687−
3688−-- index for smaller ranges, fielddata for longer ranges
3689−instance ToJSON RangeExecution where
3690− toJSON RangeExecutionIndex = "index"
3691− toJSON RangeExecutionFielddata = "fielddata"
3692−
3693−
3694−instance FromJSON RangeExecution where
3695− parseJSON = withText "RangeExecution" parse
3696− where parse "index" = pure RangeExecutionIndex
3697− parse "fielddata" = pure RangeExecutionFielddata
3698− parse t = error ("Unrecognized RangeExecution " <> show t)
3699−
3700−instance ToJSON RegexpFlags where
3701− toJSON AllRegexpFlags = String "ALL"
3702− toJSON NoRegexpFlags = String "NONE"
3703− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3704− where flagStrs = map flagStr . nub $ h:fs
3705− flagStr AnyString = "ANYSTRING"
3706− flagStr Automaton = "AUTOMATON"
3707− flagStr Complement = "COMPLEMENT"
3708− flagStr Empty = "EMPTY"
3709− flagStr Intersection = "INTERSECTION"
3710− flagStr Interval = "INTERVAL"
3711−
3712−instance FromJSON RegexpFlags where
3713− parseJSON = withText "RegexpFlags" parse
3714− where parse "ALL" = pure AllRegexpFlags
3715− parse "NONE" = pure NoRegexpFlags
3716− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3717−
3718−instance FromJSON RegexpFlag where
3719− parseJSON = withText "RegexpFlag" parse
3720− where parse "ANYSTRING" = pure AnyString
3721− parse "AUTOMATON" = pure Automaton
3722− parse "COMPLEMENT" = pure Complement
3723− parse "EMPTY" = pure Empty
3724− parse "INTERSECTION" = pure Intersection
3725− parse "INTERVAL" = pure Interval
3726− parse f = fail ("Unknown RegexpFlag: " <> show f)
3727−
3728−instance ToJSON Term where
3729− toJSON (Term field value) = object ["term" .= object
3730− [field .= value]]
3731−
3732−instance FromJSON Term where
3733− parseJSON = withObject "Term" parse
3734− where parse o = do termObj <- o .: "term"
3735− case HM.toList termObj of
3736− [(fn, v)] -> Term fn <$> parseJSON v
3737− _ -> fail "Expected object with 1 field-named key"
3738−
3739−instance ToJSON BoolMatch where
3740− toJSON (MustMatch term cache) = object ["must" .= term,
3741− "_cache" .= cache]
3742− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3743− "_cache" .= cache]
3744− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3745− "_cache" .= cache]
3746−
3747−instance FromJSON BoolMatch where
3748− parseJSON = withObject "BoolMatch" parse
3749− where parse o = mustMatch `taggedWith` "must"
3750− <|> mustNotMatch `taggedWith` "must_not"
3751− <|> shouldMatch `taggedWith` "should"
3752− where taggedWith parser k = parser =<< o .: k
3753− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3754− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3755− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
37561546
37571547instance (FromJSON a) => FromJSON (SearchResult a) where
37581548 parseJSON (Object v) = SearchResult <$>
@@ -3782,1476 +1572,20 @@ instance (FromJSON a) => FromJSON (Hit a) where
37821572 v .:? "highlight"
37831573 parseJSON _ = empty
37841574
3785−instance FromJSON ShardResult where
3786− parseJSON (Object v) = ShardResult <$>
3787− v .: "total" <*>
3788− v .: "successful" <*>
3789− v .: "failed"
3790− parseJSON _ = empty
3791−
37921575
37931576instance FromJSON DocVersion where
37941577 parseJSON v = do
37951578 i <- parseJSON v
37961579 maybe (fail "DocVersion out of range") return $ mkDocVersion i
37971580
3798−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3799−instance FromJSON ReplicaCount where
3800− parseJSON v = parseAsInt v
3801− <|> parseAsString v
3802− where parseAsInt = fmap ReplicaCount . parseJSON
3803− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3804−
3805−instance FromJSON ShardCount where
3806− parseJSON v = parseAsInt v
3807− <|> parseAsString v
3808− where parseAsInt = fmap ShardCount . parseJSON
3809− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3810−
3811−instance Bounded DocVersion where
3812− minBound = DocVersion 1
3813− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3814−
3815−instance Enum DocVersion where
3816− succ x
3817− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3818− | otherwise = succError "DocVersion"
3819− pred x
3820− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3821− | otherwise = predError "DocVersion"
3822− toEnum i =
3823− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3824− fromEnum = docVersionNumber
3825− enumFrom = boundedEnumFrom
3826− enumFromThen = boundedEnumFromThen
3827−
3828−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3829−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3830−
3831−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3832−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3833−
3834−
3835−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3836− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3837−
3838−
3839−-- | Either specifies an exact repo name or one with globs in it,
3840−-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3841−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3842− | RepoPattern Text
3843− deriving (Eq, Generic, Show, Typeable)
3844−
3845−-- | The unique name of a snapshot repository.
3846−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3847− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3848−
3849−
3850−-- | A generic representation of a snapshot repo. This is what gets
3851−-- sent to and parsed from the server. For repo types enabled by
3852−-- plugins that aren't exported by this library, consider making a
3853−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3854−-- type, consider submitting a pull request to have it included in the
3855−-- library proper
3856−data GenericSnapshotRepo = GenericSnapshotRepo {
3857− gSnapshotRepoName :: SnapshotRepoName
3858− , gSnapshotRepoType :: SnapshotRepoType
3859− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3860− } deriving (Eq, Generic, Show, Typeable)
3861−
3862−
3863−instance SnapshotRepo GenericSnapshotRepo where
3864− toGSnapshotRepo = id
3865− fromGSnapshotRepo = Right
3866−
3867−
3868−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3869− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3870−
3871−
3872−-- | Opaque representation of snapshot repo settings. Instances of
3873−-- 'SnapshotRepo' will produce this.
3874−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3875− deriving (Eq, Generic, Show, Typeable, ToJSON)
3876−
3877−
3878− -- Regardless of whether you send strongly typed json, my version of
3879− -- ES sends back stringly typed json in the settings, e.g. booleans
3880− -- as strings, so we'll try to convert them.
3881−instance FromJSON GenericSnapshotRepoSettings where
3882− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3883−
3884−-- | The result of running 'verifySnapshotRepo'.
3885−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3886− deriving (Eq, Generic, Show, Typeable)
3887−
3888−
3889−instance FromJSON SnapshotVerification where
3890− parseJSON = withObject "SnapshotVerification" parse
3891− where
3892− parse o = do
3893− o2 <- o .: "nodes"
3894− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3895− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3896− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3897−
3898−
3899−-- | A node that has verified a snapshot
3900−data SnapshotNodeVerification = SnapshotNodeVerification {
3901− snvFullId :: FullNodeId
3902− , snvNodeName :: NodeName
3903− } deriving (Eq, Generic, Show, Typeable)
3904−
3905−
3906−-- | Unique, automatically-generated name assigned to nodes that are
3907−-- usually returned in node-oriented APIs.
3908−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3909− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3910−
3911−
3912−-- | A human-readable node name that is supplied by the user in the
3913−-- node config or automatically generated by ElasticSearch.
3914−newtype NodeName = NodeName { nodeName :: Text }
3915− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3916−
3917−newtype ClusterName = ClusterName { clusterName :: Text }
3918− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3919−
3920−data NodesInfo = NodesInfo {
3921− nodesInfo :: [NodeInfo]
3922− , nodesClusterName :: ClusterName
3923− } deriving (Eq, Show, Generic, Typeable)
3924−
3925−data NodesStats = NodesStats {
3926− nodesStats :: [NodeStats]
3927− , nodesStatsClusterName :: ClusterName
3928− } deriving (Eq, Show, Generic, Typeable)
3929−
3930−data NodeStats = NodeStats {
3931− nodeStatsName :: NodeName
3932− , nodeStatsFullId :: FullNodeId
3933− , nodeStatsBreakersStats :: Maybe NodeBreakersStats
3934− , nodeStatsHTTP :: NodeHTTPStats
3935− , nodeStatsTransport :: NodeTransportStats
3936− , nodeStatsFS :: NodeFSStats
3937− , nodeStatsNetwork :: Maybe NodeNetworkStats
3938− , nodeStatsThreadPool :: NodeThreadPoolsStats
3939− , nodeStatsJVM :: NodeJVMStats
3940− , nodeStatsProcess :: NodeProcessStats
3941− , nodeStatsOS :: NodeOSStats
3942− , nodeStatsIndices :: NodeIndicesStats
3943− } deriving (Eq, Show, Generic, Typeable)
3944−
3945−data NodeBreakersStats = NodeBreakersStats {
3946− nodeStatsParentBreaker :: NodeBreakerStats
3947− , nodeStatsRequestBreaker :: NodeBreakerStats
3948− , nodeStatsFieldDataBreaker :: NodeBreakerStats
3949− } deriving (Eq, Show, Generic, Typeable)
3950−
3951−data NodeBreakerStats = NodeBreakerStats {
3952− nodeBreakersTripped :: Int
3953− , nodeBreakersOverhead :: Double
3954− , nodeBreakersEstSize :: Bytes
3955− , nodeBreakersLimitSize :: Bytes
3956− } deriving (Eq, Show, Generic, Typeable)
3957−
3958−data NodeHTTPStats = NodeHTTPStats {
3959− nodeHTTPTotalOpened :: Int
3960− , nodeHTTPCurrentOpen :: Int
3961− } deriving (Eq, Show, Generic, Typeable)
3962−
3963−data NodeTransportStats = NodeTransportStats {
3964− nodeTransportTXSize :: Bytes
3965− , nodeTransportCount :: Int
3966− , nodeTransportRXSize :: Bytes
3967− , nodeTransportRXCount :: Int
3968− , nodeTransportServerOpen :: Int
3969− } deriving (Eq, Show, Generic, Typeable)
3970−
3971−data NodeFSStats = NodeFSStats {
3972− nodeFSDataPaths :: [NodeDataPathStats]
3973− , nodeFSTotal :: NodeFSTotalStats
3974− , nodeFSTimestamp :: UTCTime
3975− } deriving (Eq, Show, Generic, Typeable)
3976−
3977−data NodeDataPathStats = NodeDataPathStats {
3978− nodeDataPathDiskServiceTime :: Maybe Double
3979− , nodeDataPathDiskQueue :: Maybe Double
3980− , nodeDataPathIOSize :: Maybe Bytes
3981− , nodeDataPathWriteSize :: Maybe Bytes
3982− , nodeDataPathReadSize :: Maybe Bytes
3983− , nodeDataPathIOOps :: Maybe Int
3984− , nodeDataPathWrites :: Maybe Int
3985− , nodeDataPathReads :: Maybe Int
3986− , nodeDataPathAvailable :: Bytes
3987− , nodeDataPathFree :: Bytes
3988− , nodeDataPathTotal :: Bytes
3989− , nodeDataPathType :: Maybe Text
3990− , nodeDataPathDevice :: Maybe Text
3991− , nodeDataPathMount :: Text
3992− , nodeDataPathPath :: Text
3993− } deriving (Eq, Show, Generic, Typeable)
3994−
3995−data NodeFSTotalStats = NodeFSTotalStats {
3996− nodeFSTotalDiskServiceTime :: Maybe Double
3997− , nodeFSTotalDiskQueue :: Maybe Double
3998− , nodeFSTotalIOSize :: Maybe Bytes
3999− , nodeFSTotalWriteSize :: Maybe Bytes
4000− , nodeFSTotalReadSize :: Maybe Bytes
4001− , nodeFSTotalIOOps :: Maybe Int
4002− , nodeFSTotalWrites :: Maybe Int
4003− , nodeFSTotalReads :: Maybe Int
4004− , nodeFSTotalAvailable :: Bytes
4005− , nodeFSTotalFree :: Bytes
4006− , nodeFSTotalTotal :: Bytes
4007− } deriving (Eq, Show, Generic, Typeable)
4008−
4009−data NodeNetworkStats = NodeNetworkStats {
4010− nodeNetTCPOutRSTs :: Int
4011− , nodeNetTCPInErrs :: Int
4012− , nodeNetTCPAttemptFails :: Int
4013− , nodeNetTCPEstabResets :: Int
4014− , nodeNetTCPRetransSegs :: Int
4015− , nodeNetTCPOutSegs :: Int
4016− , nodeNetTCPInSegs :: Int
4017− , nodeNetTCPCurrEstab :: Int
4018− , nodeNetTCPPassiveOpens :: Int
4019− , nodeNetTCPActiveOpens :: Int
4020− } deriving (Eq, Show, Generic, Typeable)
4021−
4022−data NodeThreadPoolsStats = NodeThreadPoolsStats {
4023− nodeThreadPoolsStatsSnapshot :: NodeThreadPoolStats
4024− , nodeThreadPoolsStatsBulk :: NodeThreadPoolStats
4025− , nodeThreadPoolsStatsMerge :: NodeThreadPoolStats
4026− , nodeThreadPoolsStatsGet :: NodeThreadPoolStats
4027− , nodeThreadPoolsStatsManagement :: NodeThreadPoolStats
4028− , nodeThreadPoolsStatsFetchShardStore :: Maybe NodeThreadPoolStats
4029− , nodeThreadPoolsStatsOptimize :: Maybe NodeThreadPoolStats
4030− , nodeThreadPoolsStatsFlush :: NodeThreadPoolStats
4031− , nodeThreadPoolsStatsSearch :: NodeThreadPoolStats
4032− , nodeThreadPoolsStatsWarmer :: NodeThreadPoolStats
4033− , nodeThreadPoolsStatsGeneric :: NodeThreadPoolStats
4034− , nodeThreadPoolsStatsSuggest :: Maybe NodeThreadPoolStats
4035− , nodeThreadPoolsStatsRefresh :: NodeThreadPoolStats
4036− , nodeThreadPoolsStatsIndex :: NodeThreadPoolStats
4037− , nodeThreadPoolsStatsListener :: Maybe NodeThreadPoolStats
4038− , nodeThreadPoolsStatsFetchShardStarted :: Maybe NodeThreadPoolStats
4039− , nodeThreadPoolsStatsPercolate :: Maybe NodeThreadPoolStats
4040− } deriving (Eq, Show, Generic, Typeable)
4041−
4042−data NodeThreadPoolStats = NodeThreadPoolStats {
4043− nodeThreadPoolCompleted :: Int
4044− , nodeThreadPoolLargest :: Int
4045− , nodeThreadPoolRejected :: Int
4046− , nodeThreadPoolActive :: Int
4047− , nodeThreadPoolQueue :: Int
4048− , nodeThreadPoolThreads :: Int
4049− } deriving (Eq, Show, Generic, Typeable)
4050−
4051−data NodeJVMStats = NodeJVMStats {
4052− nodeJVMStatsMappedBufferPool :: JVMBufferPoolStats
4053− , nodeJVMStatsDirectBufferPool :: JVMBufferPoolStats
4054− , nodeJVMStatsGCOldCollector :: JVMGCStats
4055− , nodeJVMStatsGCYoungCollector :: JVMGCStats
4056− , nodeJVMStatsPeakThreadsCount :: Int
4057− , nodeJVMStatsThreadsCount :: Int
4058− , nodeJVMStatsOldPool :: JVMPoolStats
4059− , nodeJVMStatsSurvivorPool :: JVMPoolStats
4060− , nodeJVMStatsYoungPool :: JVMPoolStats
4061− , nodeJVMStatsNonHeapCommitted :: Bytes
4062− , nodeJVMStatsNonHeapUsed :: Bytes
4063− , nodeJVMStatsHeapMax :: Bytes
4064− , nodeJVMStatsHeapCommitted :: Bytes
4065− , nodeJVMStatsHeapUsedPercent :: Int
4066− , nodeJVMStatsHeapUsed :: Bytes
4067− , nodeJVMStatsUptime :: NominalDiffTime
4068− , nodeJVMStatsTimestamp :: UTCTime
4069− } deriving (Eq, Show, Generic, Typeable)
4070−
4071−data JVMBufferPoolStats = JVMBufferPoolStats {
4072− jvmBufferPoolStatsTotalCapacity :: Bytes
4073− , jvmBufferPoolStatsUsed :: Bytes
4074− , jvmBufferPoolStatsCount :: Int
4075− } deriving (Eq, Show, Generic, Typeable)
4076−
4077−data JVMGCStats = JVMGCStats {
4078− jvmGCStatsCollectionTime :: NominalDiffTime
4079− , jvmGCStatsCollectionCount :: Int
4080− } deriving (Eq, Show, Generic, Typeable)
4081−
4082−data JVMPoolStats = JVMPoolStats {
4083− jvmPoolStatsPeakMax :: Bytes
4084− , jvmPoolStatsPeakUsed :: Bytes
4085− , jvmPoolStatsMax :: Bytes
4086− , jvmPoolStatsUsed :: Bytes
4087− } deriving (Eq, Show, Generic, Typeable)
4088−
4089−data NodeProcessStats = NodeProcessStats {
4090− nodeProcessTimestamp :: UTCTime
4091− , nodeProcessOpenFDs :: Int
4092− , nodeProcessMaxFDs :: Int
4093− , nodeProcessCPUPercent :: Int
4094− , nodeProcessCPUTotal :: NominalDiffTime
4095− , nodeProcessMemTotalVirtual :: Bytes
4096− } deriving (Eq, Show, Generic, Typeable)
4097−
4098−data NodeOSStats = NodeOSStats {
4099− nodeOSTimestamp :: UTCTime
4100− , nodeOSCPUPercent :: Int
4101− , nodeOSLoad :: Maybe LoadAvgs
4102− , nodeOSMemTotal :: Bytes
4103− , nodeOSMemFree :: Bytes
4104− , nodeOSMemFreePercent :: Int
4105− , nodeOSMemUsed :: Bytes
4106− , nodeOSMemUsedPercent :: Int
4107− , nodeOSSwapTotal :: Bytes
4108− , nodeOSSwapFree :: Bytes
4109− , nodeOSSwapUsed :: Bytes
4110− } deriving (Eq, Show, Generic, Typeable)
4111−
4112−data LoadAvgs = LoadAvgs {
4113− loadAvg1Min :: Double
4114− , loadAvg5Min :: Double
4115− , loadAvg15Min :: Double
4116− } deriving (Eq, Show, Generic, Typeable)
4117−
4118−data NodeIndicesStats = NodeIndicesStats {
4119− nodeIndicesStatsRecoveryThrottleTime :: Maybe NominalDiffTime
4120− , nodeIndicesStatsRecoveryCurrentAsTarget :: Maybe Int
4121− , nodeIndicesStatsRecoveryCurrentAsSource :: Maybe Int
4122− , nodeIndicesStatsQueryCacheMisses :: Maybe Int
4123− , nodeIndicesStatsQueryCacheHits :: Maybe Int
4124− , nodeIndicesStatsQueryCacheEvictions :: Maybe Int
4125− , nodeIndicesStatsQueryCacheSize :: Maybe Bytes
4126− , nodeIndicesStatsSuggestCurrent :: Maybe Int
4127− , nodeIndicesStatsSuggestTime :: Maybe NominalDiffTime
4128− , nodeIndicesStatsSuggestTotal :: Maybe Int
4129− , nodeIndicesStatsTranslogSize :: Bytes
4130− , nodeIndicesStatsTranslogOps :: Int
4131− , nodeIndicesStatsSegFixedBitSetMemory :: Maybe Bytes
4132− , nodeIndicesStatsSegVersionMapMemory :: Bytes
4133− , nodeIndicesStatsSegIndexWriterMaxMemory :: Maybe Bytes
4134− , nodeIndicesStatsSegIndexWriterMemory :: Bytes
4135− , nodeIndicesStatsSegMemory :: Bytes
4136− , nodeIndicesStatsSegCount :: Int
4137− , nodeIndicesStatsCompletionSize :: Bytes
4138− , nodeIndicesStatsPercolateQueries :: Maybe Int
4139− , nodeIndicesStatsPercolateMemory :: Maybe Bytes
4140− , nodeIndicesStatsPercolateCurrent :: Maybe Int
4141− , nodeIndicesStatsPercolateTime :: Maybe NominalDiffTime
4142− , nodeIndicesStatsPercolateTotal :: Maybe Int
4143− , nodeIndicesStatsFieldDataEvictions :: Int
4144− , nodeIndicesStatsFieldDataMemory :: Bytes
4145− , nodeIndicesStatsWarmerTotalTime :: NominalDiffTime
4146− , nodeIndicesStatsWarmerTotal :: Int
4147− , nodeIndicesStatsWarmerCurrent :: Int
4148− , nodeIndicesStatsFlushTotalTime :: NominalDiffTime
4149− , nodeIndicesStatsFlushTotal :: Int
4150− , nodeIndicesStatsRefreshTotalTime :: NominalDiffTime
4151− , nodeIndicesStatsRefreshTotal :: Int
4152− , nodeIndicesStatsMergesTotalSize :: Bytes
4153− , nodeIndicesStatsMergesTotalDocs :: Int
4154− , nodeIndicesStatsMergesTotalTime :: NominalDiffTime
4155− , nodeIndicesStatsMergesTotal :: Int
4156− , nodeIndicesStatsMergesCurrentSize :: Bytes
4157− , nodeIndicesStatsMergesCurrentDocs :: Int
4158− , nodeIndicesStatsMergesCurrent :: Int
4159− , nodeIndicesStatsSearchFetchCurrent :: Int
4160− , nodeIndicesStatsSearchFetchTime :: NominalDiffTime
4161− , nodeIndicesStatsSearchFetchTotal :: Int
4162− , nodeIndicesStatsSearchQueryCurrent :: Int
4163− , nodeIndicesStatsSearchQueryTime :: NominalDiffTime
4164− , nodeIndicesStatsSearchQueryTotal :: Int
4165− , nodeIndicesStatsSearchOpenContexts :: Int
4166− , nodeIndicesStatsGetCurrent :: Int
4167− , nodeIndicesStatsGetMissingTime :: NominalDiffTime
4168− , nodeIndicesStatsGetMissingTotal :: Int
4169− , nodeIndicesStatsGetExistsTime :: NominalDiffTime
4170− , nodeIndicesStatsGetExistsTotal :: Int
4171− , nodeIndicesStatsGetTime :: NominalDiffTime
4172− , nodeIndicesStatsGetTotal :: Int
4173− , nodeIndicesStatsIndexingThrottleTime :: Maybe NominalDiffTime
4174− , nodeIndicesStatsIndexingIsThrottled :: Maybe Bool
4175− , nodeIndicesStatsIndexingNoopUpdateTotal :: Maybe Int
4176− , nodeIndicesStatsIndexingDeleteCurrent :: Int
4177− , nodeIndicesStatsIndexingDeleteTime :: NominalDiffTime
4178− , nodeIndicesStatsIndexingDeleteTotal :: Int
4179− , nodeIndicesStatsIndexingIndexCurrent :: Int
4180− , nodeIndicesStatsIndexingIndexTime :: NominalDiffTime
4181− , nodeIndicesStatsIndexingTotal :: Int
4182− , nodeIndicesStatsStoreThrottleTime :: NominalDiffTime
4183− , nodeIndicesStatsStoreSize :: Bytes
4184− , nodeIndicesStatsDocsDeleted :: Int
4185− , nodeIndicesStatsDocsCount :: Int
4186− } deriving (Eq, Show, Generic, Typeable)
4187−
4188−-- | A quirky address format used throughout ElasticSearch. An example
4189−-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
4190−-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
4191−newtype EsAddress = EsAddress { esAddress :: Text }
4192− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4193−
4194−-- | Typically a 7 character hex string.
4195−newtype BuildHash = BuildHash { buildHash :: Text }
4196− deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
4197−
4198−newtype PluginName = PluginName { pluginName :: Text }
4199− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4200−
4201−data NodeInfo = NodeInfo {
4202− nodeInfoHTTPAddress :: Maybe EsAddress
4203− , nodeInfoBuild :: BuildHash
4204− , nodeInfoESVersion :: VersionNumber
4205− , nodeInfoIP :: Server
4206− , nodeInfoHost :: Server
4207− , nodeInfoTransportAddress :: EsAddress
4208− , nodeInfoName :: NodeName
4209− , nodeInfoFullId :: FullNodeId
4210− , nodeInfoPlugins :: [NodePluginInfo]
4211− , nodeInfoHTTP :: NodeHTTPInfo
4212− , nodeInfoTransport :: NodeTransportInfo
4213− , nodeInfoNetwork :: Maybe NodeNetworkInfo
4214− , nodeInfoThreadPool :: NodeThreadPoolsInfo
4215− , nodeInfoJVM :: NodeJVMInfo
4216− , nodeInfoProcess :: NodeProcessInfo
4217− , nodeInfoOS :: NodeOSInfo
4218− , nodeInfoSettings :: Object
4219− -- ^ The members of the settings objects are not consistent,
4220− -- dependent on plugins, etc.
4221− } deriving (Eq, Show, Generic, Typeable)
4222−
4223−data NodePluginInfo = NodePluginInfo {
4224− nodePluginSite :: Maybe Bool
4225− -- ^ Is this a site plugin?
4226− , nodePluginJVM :: Maybe Bool
4227− -- ^ Is this plugin running on the JVM
4228− , nodePluginDescription :: Text
4229− , nodePluginVersion :: MaybeNA VersionNumber
4230− , nodePluginName :: PluginName
4231− } deriving (Eq, Show, Generic, Typeable)
4232−
4233−data NodeHTTPInfo = NodeHTTPInfo {
4234− nodeHTTPMaxContentLength :: Bytes
4235− , nodeHTTPTransportAddress :: BoundTransportAddress
4236− } deriving (Eq, Show, Generic, Typeable)
4237−
4238−data NodeTransportInfo = NodeTransportInfo {
4239− nodeTransportProfiles :: [BoundTransportAddress]
4240− , nodeTransportAddress :: BoundTransportAddress
4241− } deriving (Eq, Show, Generic, Typeable)
4242−
4243−data BoundTransportAddress = BoundTransportAddress {
4244− publishAddress :: EsAddress
4245− , boundAddress :: [EsAddress]
4246− } deriving (Eq, Show, Generic, Typeable)
4247−
4248−data NodeNetworkInfo = NodeNetworkInfo {
4249− nodeNetworkPrimaryInterface :: NodeNetworkInterface
4250− , nodeNetworkRefreshInterval :: NominalDiffTime
4251− } deriving (Eq, Show, Generic, Typeable)
4252−
4253−newtype MacAddress = MacAddress { macAddress :: Text }
4254− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4255−
4256−newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
4257− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4258−
4259−data NodeNetworkInterface = NodeNetworkInterface {
4260− nodeNetIfaceMacAddress :: MacAddress
4261− , nodeNetIfaceName :: NetworkInterfaceName
4262− , nodeNetIfaceAddress :: Server
4263− } deriving (Eq, Show, Generic, Typeable)
4264−
4265−data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
4266− nodeThreadPoolsRefresh :: NodeThreadPoolInfo
4267− , nodeThreadPoolsManagement :: NodeThreadPoolInfo
4268− , nodeThreadPoolsPercolate :: Maybe NodeThreadPoolInfo
4269− , nodeThreadPoolsListener :: Maybe NodeThreadPoolInfo
4270− , nodeThreadPoolsFetchShardStarted :: Maybe NodeThreadPoolInfo
4271− , nodeThreadPoolsSearch :: NodeThreadPoolInfo
4272− , nodeThreadPoolsFlush :: NodeThreadPoolInfo
4273− , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
4274− , nodeThreadPoolsOptimize :: Maybe NodeThreadPoolInfo
4275− , nodeThreadPoolsBulk :: NodeThreadPoolInfo
4276− , nodeThreadPoolsSuggest :: Maybe NodeThreadPoolInfo
4277− , nodeThreadPoolsMerge :: NodeThreadPoolInfo
4278− , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
4279− , nodeThreadPoolsGet :: NodeThreadPoolInfo
4280− , nodeThreadPoolsFetchShardStore :: Maybe NodeThreadPoolInfo
4281− , nodeThreadPoolsIndex :: NodeThreadPoolInfo
4282− , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
4283− } deriving (Eq, Show, Generic, Typeable)
4284−
4285−data NodeThreadPoolInfo = NodeThreadPoolInfo {
4286− nodeThreadPoolQueueSize :: ThreadPoolSize
4287− , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
4288− , nodeThreadPoolMin :: Maybe Int
4289− , nodeThreadPoolMax :: Maybe Int
4290− , nodeThreadPoolType :: ThreadPoolType
4291− } deriving (Eq, Show, Generic, Typeable)
4292−
4293−data ThreadPoolSize = ThreadPoolBounded Int
4294− | ThreadPoolUnbounded
4295− deriving (Eq, Show, Generic, Typeable)
4296−
4297−data ThreadPoolType = ThreadPoolScaling
4298− | ThreadPoolFixed
4299− | ThreadPoolCached
4300− deriving (Eq, Show, Generic, Typeable)
4301−
4302−data NodeJVMInfo = NodeJVMInfo {
4303− nodeJVMInfoMemoryPools :: [JVMMemoryPool]
4304− , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
4305− , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
4306− , nodeJVMInfoStartTime :: UTCTime
4307− , nodeJVMInfoVMVendor :: Text
4308− , nodeJVMVMVersion :: VersionNumber
4309− -- ^ JVM doesn't seme to follow normal version conventions
4310− , nodeJVMVMName :: Text
4311− , nodeJVMVersion :: VersionNumber
4312− , nodeJVMPID :: PID
4313− } deriving (Eq, Show, Generic, Typeable)
4314−
4315−-- | Handles quirks in the way JVM versions are rendered (1.7.0_101 -> 1.7.0.101)
4316−newtype JVMVersion = JVMVersion { unJVMVersion :: VersionNumber }
4317−
4318−data JVMMemoryInfo = JVMMemoryInfo {
4319− jvmMemoryInfoDirectMax :: Bytes
4320− , jvmMemoryInfoNonHeapMax :: Bytes
4321− , jvmMemoryInfoNonHeapInit :: Bytes
4322− , jvmMemoryInfoHeapMax :: Bytes
4323− , jvmMemoryInfoHeapInit :: Bytes
4324− } deriving (Eq, Show, Generic, Typeable)
4325−
4326−newtype JVMMemoryPool = JVMMemoryPool {
4327− jvmMemoryPool :: Text
4328− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4329−
4330−newtype JVMGCCollector = JVMGCCollector {
4331− jvmGCCollector :: Text
4332− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4333−
4334−newtype PID = PID {
4335− pid :: Int
4336− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4337−
4338−data NodeOSInfo = NodeOSInfo {
4339− nodeOSRefreshInterval :: NominalDiffTime
4340− , nodeOSName :: Text
4341− , nodeOSArch :: Text
4342− , nodeOSVersion :: VersionNumber
4343− , nodeOSAvailableProcessors :: Int
4344− , nodeOSAllocatedProcessors :: Int
4345− } deriving (Eq, Show, Generic, Typeable)
4346−
4347−data CPUInfo = CPUInfo {
4348− cpuCacheSize :: Bytes
4349− , cpuCoresPerSocket :: Int
4350− , cpuTotalSockets :: Int
4351− , cpuTotalCores :: Int
4352− , cpuMHZ :: Int
4353− , cpuModel :: Text
4354− , cpuVendor :: Text
4355− } deriving (Eq, Show, Generic, Typeable)
4356−
4357−data NodeProcessInfo = NodeProcessInfo {
4358− nodeProcessMLockAll :: Bool
4359− -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
4360− , nodeProcessMaxFileDescriptors :: Maybe Int
4361− , nodeProcessId :: PID
4362− , nodeProcessRefreshInterval :: NominalDiffTime
4363− } deriving (Eq, Show, Generic, Typeable)
4364−
4365−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
4366− repoUpdateVerify :: Bool
4367− -- ^ After creation/update, synchronously check that nodes can
4368− -- write to this repo. Defaults to True. You may use False if you
4369− -- need a faster response and plan on verifying manually later
4370− -- with 'verifySnapshotRepo'.
4371− } deriving (Eq, Show, Generic, Typeable)
4372−
4373−
4374−-- | Reasonable defaults for repo creation/update
4375−--
4376−-- * repoUpdateVerify True
4377−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4378−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4379−
4380−
4381−-- | A filesystem-based snapshot repo that ships with
4382−-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4383−-- used with 'updateSnapshotRepo'
4384−data FsSnapshotRepo = FsSnapshotRepo {
4385− fsrName :: SnapshotRepoName
4386− , fsrLocation :: FilePath
4387− , fsrCompressMetadata :: Bool
4388− , fsrChunkSize :: Maybe Bytes
4389− -- ^ Size by which to split large files during snapshotting.
4390− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4391− -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4392− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4393− -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4394− } deriving (Eq, Generic, Show, Typeable)
4395−
4396−
4397−instance SnapshotRepo FsSnapshotRepo where
4398− toGSnapshotRepo FsSnapshotRepo {..} =
4399− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4400− where
4401− Object settings = object $ [ "location" .= fsrLocation
4402− , "compress" .= fsrCompressMetadata
4403− ] ++ optionalPairs
4404− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4405− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4406− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4407− ]
4408− fromGSnapshotRepo GenericSnapshotRepo {..}
4409− | gSnapshotRepoType == fsRepoType = do
4410− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4411− parseRepo $ do
4412− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4413− <*> o .:? "compress" .!= False
4414− <*> o .:? "chunk_size"
4415− <*> o .:? "max_restore_bytes_per_sec"
4416− <*> o .:? "max_snapshot_bytes_per_sec"
4417− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4418−
4419−
4420−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4421−parseRepo parser = case parseEither (const parser) () of
4422− Left e -> Left (OtherRepoConversionError (T.pack e))
4423− Right a -> Right a
4424−
4425−
4426−fsRepoType :: SnapshotRepoType
4427−fsRepoType = SnapshotRepoType "fs"
4428−
4429−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4430−class SnapshotRepo r where
4431− toGSnapshotRepo :: r -> GenericSnapshotRepo
4432− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4433−
4434−
4435−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4436− -- ^ Expected type and actual type
4437− | OtherRepoConversionError Text
4438− deriving (Show, Eq, Generic, Typeable)
4439−
4440−
4441−instance Exception SnapshotRepoConversionError
4442−
4443−
4444−data SnapshotCreateSettings = SnapshotCreateSettings {
4445− snapWaitForCompletion :: Bool
4446− -- ^ Should the API call return immediately after initializing
4447− -- the snapshot or wait until completed? Note that if this is
4448− -- enabled it could wait a long time, so you should adjust your
4449− -- 'ManagerSettings' accordingly to set long timeouts or
4450− -- explicitly handle timeouts.
4451− , snapIndices :: Maybe IndexSelection
4452− -- ^ Nothing will snapshot all indices. Just [] is permissable and
4453− -- will essentially be a no-op snapshot.
4454− , snapIgnoreUnavailable :: Bool
4455− -- ^ If set to True, any matched indices that don't exist will be
4456− -- ignored. Otherwise it will be an error and fail.
4457− , snapIncludeGlobalState :: Bool
4458− , snapPartial :: Bool
4459− -- ^ If some indices failed to snapshot (e.g. if not all primary
4460− -- shards are available), should the process proceed?
4461− } deriving (Eq, Generic, Show, Typeable)
4462−
4463−
4464−-- | Reasonable defaults for snapshot creation
4465−--
4466−-- * snapWaitForCompletion False
4467−-- * snapIndices Nothing
4468−-- * snapIgnoreUnavailable False
4469−-- * snapIncludeGlobalState True
4470−-- * snapPartial False
4471−defaultSnapshotCreateSettings :: SnapshotCreateSettings
4472−defaultSnapshotCreateSettings = SnapshotCreateSettings {
4473− snapWaitForCompletion = False
4474− , snapIndices = Nothing
4475− , snapIgnoreUnavailable = False
4476− , snapIncludeGlobalState = True
4477− , snapPartial = False
4478− }
4479−
4480−
4481−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4482− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4483−
4484−
4485−-- | Either specifies an exact snapshot name or one with globs in it,
4486−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4487−-- ES < 1.7
4488−data SnapshotPattern = ExactSnap SnapshotName
4489− | SnapPattern Text
4490− deriving (Eq, Generic, Show, Typeable)
4491−
4492−
4493−-- | General information about the state of a snapshot. Has some
4494−-- redundancies with 'SnapshotStatus'
4495−data SnapshotInfo = SnapshotInfo {
4496− snapInfoShards :: ShardResult
4497− , snapInfoFailures :: [SnapshotShardFailure]
4498− , snapInfoDuration :: NominalDiffTime
4499− , snapInfoEndTime :: UTCTime
4500− , snapInfoStartTime :: UTCTime
4501− , snapInfoState :: SnapshotState
4502− , snapInfoIndices :: [IndexName]
4503− , snapInfoName :: SnapshotName
4504− } deriving (Eq, Generic, Show, Typeable)
4505−
4506−
4507−instance FromJSON SnapshotInfo where
4508− parseJSON = withObject "SnapshotInfo" parse
4509− where
4510− parse o = SnapshotInfo <$> o .: "shards"
4511− <*> o .: "failures"
4512− <*> (unMS <$> o .: "duration_in_millis")
4513− <*> (posixMS <$> o .: "end_time_in_millis")
4514− <*> (posixMS <$> o .: "start_time_in_millis")
4515− <*> o .: "state"
4516− <*> o .: "indices"
4517− <*> o .: "snapshot"
4518−
4519−data SnapshotShardFailure = SnapshotShardFailure {
4520− snapShardFailureIndex :: IndexName
4521− , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4522− , snapShardFailureReason :: Text
4523− , snapShardFailureShardId :: ShardId
4524− } deriving (Eq, Show, Generic, Typeable)
4525−
4526−
4527−instance FromJSON SnapshotShardFailure where
4528− parseJSON = withObject "SnapshotShardFailure" parse
4529− where
4530− parse o = SnapshotShardFailure <$> o .: "index"
4531− <*> o .:? "node_id"
4532− <*> o .: "reason"
4533− <*> o .: "shard_id"
4534−
4535−
4536−newtype ShardId = ShardId { shardId :: Int }
4537− deriving (Eq, Show, Generic, Typeable, FromJSON)
4538−
4539−-- | Milliseconds
4540−newtype MS = MS NominalDiffTime
4541−
4542−
4543−-- keeps the unexported constructor warnings at bay
4544−unMS :: MS -> NominalDiffTime
4545−unMS (MS t) = t
4546−
4547−
4548−instance FromJSON MS where
4549− parseJSON = withScientific "MS" (return . MS . parse)
4550− where
4551− parse n = fromInteger ((truncate n) * 1000)
4552−
4553−
4554−data SnapshotState = SnapshotInit
4555− | SnapshotStarted
4556− | SnapshotSuccess
4557− | SnapshotFailed
4558− | SnapshotAborted
4559− | SnapshotMissing
4560− | SnapshotWaiting
4561− deriving (Show, Eq, Generic, Typeable)
4562−
4563−instance FromJSON SnapshotState where
4564− parseJSON = withText "SnapshotState" parse
4565− where
4566− parse "INIT" = return SnapshotInit
4567− parse "STARTED" = return SnapshotStarted
4568− parse "SUCCESS" = return SnapshotSuccess
4569− parse "FAILED" = return SnapshotFailed
4570− parse "ABORTED" = return SnapshotAborted
4571− parse "MISSING" = return SnapshotMissing
4572− parse "WAITING" = return SnapshotWaiting
4573− parse t = fail ("Invalid snapshot state " <> T.unpack t)
4574−
4575−
4576−newtype SnapshotName = SnapshotName { snapshotName :: Text }
4577− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4578−
4579−
4580−data SnapshotRestoreSettings = SnapshotRestoreSettings {
4581− snapRestoreWaitForCompletion :: Bool
4582− -- ^ Should the API call return immediately after initializing
4583− -- the restore or wait until completed? Note that if this is
4584− -- enabled, it could wait a long time, so you should adjust your
4585− -- 'ManagerSettings' accordingly to set long timeouts or
4586− -- explicitly handle timeouts.
4587− , snapRestoreIndices :: Maybe IndexSelection
4588− -- ^ Nothing will restore all indices in the snapshot. Just [] is
4589− -- permissable and will essentially be a no-op restore.
4590− , snapRestoreIgnoreUnavailable :: Bool
4591− -- ^ If set to True, any indices that do not exist will be ignored
4592− -- during snapshot rather than failing the restore.
4593− , snapRestoreIncludeGlobalState :: Bool
4594− -- ^ If set to false, will ignore any global state in the snapshot
4595− -- and will not restore it.
4596− , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4597− -- ^ A regex pattern for matching indices. Used with
4598− -- 'snapRestoreRenameReplacement', the restore can reference the
4599− -- matched index and create a new index name upon restore.
4600− , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4601− -- ^ Expression of how index renames should be constructed.
4602− , snapRestorePartial :: Bool
4603− -- ^ If some indices fail to restore, should the process proceed?
4604− , snapRestoreIncludeAliases :: Bool
4605− -- ^ Should the restore also restore the aliases captured in the
4606− -- snapshot.
4607− , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4608− -- ^ Settings to apply during the restore process. __NOTE:__ This
4609− -- option is not supported in ES < 1.5 and should be set to
4610− -- Nothing in that case.
4611− , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4612− -- ^ This type could be more rich but it isn't clear which
4613− -- settings are allowed to be ignored during restore, so we're
4614− -- going with including this feature in a basic form rather than
4615− -- omitting it. One example here would be
4616− -- "index.refresh_interval". Any setting specified here will
4617− -- revert back to the server default during the restore process.
4618− } deriving (Eq, Generic, Show, Typeable)
4619−
4620−-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4621−newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4622− deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4623−
4624−
4625−-- | A single token in a index renaming scheme for a restore. These
4626−-- are concatenated into a string before being sent to
4627−-- ElasticSearch. Check out these Java
4628−-- <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.
4629−data RestoreRenameToken = RRTLit Text
4630− -- ^ Just a literal string of characters
4631− | RRSubWholeMatch
4632− -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4633− | RRSubGroup RRGroupRefNum
4634− -- ^ A specific reference to a group number
4635− deriving (Show, Eq, Generic, Typeable)
4636−
4637−
4638−-- | A group number for regex matching. Only values from 1-9 are
4639−-- supported. Construct with 'mkRRGroupRefNum'
4640−newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4641− deriving (Show, Eq, Generic, Typeable, Ord)
4642−
4643−instance Bounded RRGroupRefNum where
4644− minBound = RRGroupRefNum 1
4645− maxBound = RRGroupRefNum 9
4646−
4647−
4648−-- | Only allows valid group number references (1-9).
4649−mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4650−mkRRGroupRefNum i
4651− | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4652− Just $ RRGroupRefNum i
4653− | otherwise = Nothing
4654−
4655−
4656−-- | Reasonable defaults for snapshot restores
4657−--
4658−-- * snapRestoreWaitForCompletion False
4659−-- * snapRestoreIndices Nothing
4660−-- * snapRestoreIgnoreUnavailable False
4661−-- * snapRestoreIncludeGlobalState True
4662−-- * snapRestoreRenamePattern Nothing
4663−-- * snapRestoreRenameReplacement Nothing
4664−-- * snapRestorePartial False
4665−-- * snapRestoreIncludeAliases True
4666−-- * snapRestoreIndexSettingsOverrides Nothing
4667−-- * snapRestoreIgnoreIndexSettings Nothing
4668−defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4669−defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4670− snapRestoreWaitForCompletion = False
4671− , snapRestoreIndices = Nothing
4672− , snapRestoreIgnoreUnavailable = False
4673− , snapRestoreIncludeGlobalState = True
4674− , snapRestoreRenamePattern = Nothing
4675− , snapRestoreRenameReplacement = Nothing
4676− , snapRestorePartial = False
4677− , snapRestoreIncludeAliases = True
4678− , snapRestoreIndexSettingsOverrides = Nothing
4679− , snapRestoreIgnoreIndexSettings = Nothing
4680− }
4681−
4682−
4683−-- | Index settings that can be overridden. The docs only mention you
4684−-- can update number of replicas, but there may be more. You
4685−-- definitely cannot override shard count.
4686−data RestoreIndexSettings = RestoreIndexSettings {
4687− restoreOverrideReplicas :: Maybe ReplicaCount
4688− } deriving (Show, Eq, Generic, Typeable)
4689−
4690−
4691−instance ToJSON RestoreIndexSettings where
4692− toJSON RestoreIndexSettings {..} = object prs
4693− where
4694− prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
4695−
4696−
4697−instance FromJSON NodesInfo where
4698− parseJSON = withObject "NodesInfo" parse
4699− where
4700− parse o = do
4701− nodes <- o .: "nodes"
4702− infos <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4703− node <- parseJSON v
4704− parseNodeInfo (FullNodeId fullNID) node
4705− cn <- o .: "cluster_name"
4706− return (NodesInfo infos cn)
4707−
4708−instance FromJSON NodesStats where
4709− parseJSON = withObject "NodesStats" parse
4710− where
4711− parse o = do
4712− nodes <- o .: "nodes"
4713− stats <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4714− node <- parseJSON v
4715− parseNodeStats (FullNodeId fullNID) node
4716− cn <- o .: "cluster_name"
4717− return (NodesStats stats cn)
4718−
4719−instance FromJSON NodeBreakerStats where
4720− parseJSON = withObject "NodeBreakerStats" parse
4721− where
4722− parse o = NodeBreakerStats <$> o .: "tripped"
4723− <*> o .: "overhead"
4724− <*> o .: "estimated_size_in_bytes"
4725− <*> o .: "limit_size_in_bytes"
4726−
4727−instance FromJSON NodeHTTPStats where
4728− parseJSON = withObject "NodeHTTPStats" parse
4729− where
4730− parse o = NodeHTTPStats <$> o .: "total_opened"
4731− <*> o .: "current_open"
4732−
4733−instance FromJSON NodeTransportStats where
4734− parseJSON = withObject "NodeTransportStats" parse
4735− where
4736− parse o = NodeTransportStats <$> o .: "tx_size_in_bytes"
4737− <*> o .: "tx_count"
4738− <*> o .: "rx_size_in_bytes"
4739− <*> o .: "rx_count"
4740− <*> o .: "server_open"
4741−
4742−instance FromJSON NodeFSStats where
4743− parseJSON = withObject "NodeFSStats" parse
4744− where
4745− parse o = NodeFSStats <$> o .: "data"
4746− <*> o .: "total"
4747− <*> (posixMS <$> o .: "timestamp")
4748−
4749−instance FromJSON NodeDataPathStats where
4750− parseJSON = withObject "NodeDataPathStats" parse
4751− where
4752− parse o =
4753− NodeDataPathStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4754− <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4755− <*> o .:? "disk_io_size_in_bytes"
4756− <*> o .:? "disk_write_size_in_bytes"
4757− <*> o .:? "disk_read_size_in_bytes"
4758− <*> o .:? "disk_io_op"
4759− <*> o .:? "disk_writes"
4760− <*> o .:? "disk_reads"
4761− <*> o .: "available_in_bytes"
4762− <*> o .: "free_in_bytes"
4763− <*> o .: "total_in_bytes"
4764− <*> o .:? "type"
4765− <*> o .:? "dev"
4766− <*> o .: "mount"
4767− <*> o .: "path"
4768−
4769−newtype StringlyTypedDouble = StringlyTypedDouble { unStringlyTypedDouble :: Double }
4770−
4771−instance FromJSON StringlyTypedDouble where
4772− parseJSON = fmap StringlyTypedDouble . parseJSON . unStringlyTypeJSON
4773−
4774−newtype StringlyTypedInt = StringlyTypedInt { unStringlyTypedInt :: Int }
4775−
4776−instance FromJSON StringlyTypedInt where
4777− parseJSON = fmap StringlyTypedInt . parseJSON . unStringlyTypeJSON
4778−
4779−instance FromJSON NodeFSTotalStats where
4780− parseJSON = withObject "NodeFSTotalStats" parse
4781− where
4782− parse o = NodeFSTotalStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4783− <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4784− <*> o .:? "disk_io_size_in_bytes"
4785− <*> o .:? "disk_write_size_in_bytes"
4786− <*> o .:? "disk_read_size_in_bytes"
4787− <*> o .:? "disk_io_op"
4788− <*> o .:? "disk_writes"
4789− <*> o .:? "disk_reads"
4790− <*> o .: "available_in_bytes"
4791− <*> o .: "free_in_bytes"
4792− <*> o .: "total_in_bytes"
4793−
4794−instance FromJSON NodeNetworkStats where
4795− parseJSON = withObject "NodeNetworkStats" parse
4796− where
4797− parse o = do
4798− tcp <- o .: "tcp"
4799− NodeNetworkStats <$> tcp .: "out_rsts"
4800− <*> tcp .: "in_errs"
4801− <*> tcp .: "attempt_fails"
4802− <*> tcp .: "estab_resets"
4803− <*> tcp .: "retrans_segs"
4804− <*> tcp .: "out_segs"
4805− <*> tcp .: "in_segs"
4806− <*> tcp .: "curr_estab"
4807− <*> tcp .: "passive_opens"
4808− <*> tcp .: "active_opens"
4809−
4810−instance FromJSON NodeThreadPoolsStats where
4811− parseJSON = withObject "NodeThreadPoolsStats" parse
4812− where
4813− parse o = NodeThreadPoolsStats <$> o .: "snapshot"
4814− <*> o .: "bulk"
4815− <*> o .: "force_merge"
4816− <*> o .: "get"
4817− <*> o .: "management"
4818− <*> o .:? "fetch_shard_store"
4819− <*> o .:? "optimize"
4820− <*> o .: "flush"
4821− <*> o .: "search"
4822− <*> o .: "warmer"
4823− <*> o .: "generic"
4824− <*> o .:? "suggest"
4825− <*> o .: "refresh"
4826− <*> o .: "index"
4827− <*> o .:? "listener"
4828− <*> o .:? "fetch_shard_started"
4829− <*> o .:? "percolate"
4830−instance FromJSON NodeThreadPoolStats where
4831− parseJSON = withObject "NodeThreadPoolStats" parse
4832− where
4833− parse o = NodeThreadPoolStats <$> o .: "completed"
4834− <*> o .: "largest"
4835− <*> o .: "rejected"
4836− <*> o .: "active"
4837− <*> o .: "queue"
4838− <*> o .: "threads"
4839−
4840−instance FromJSON NodeJVMStats where
4841− parseJSON = withObject "NodeJVMStats" parse
4842− where
4843− parse o = do
4844− bufferPools <- o .: "buffer_pools"
4845− mapped <- bufferPools .: "mapped"
4846− direct <- bufferPools .: "direct"
4847− gc <- o .: "gc"
4848− collectors <- gc .: "collectors"
4849− oldC <- collectors .: "old"
4850− youngC <- collectors .: "young"
4851− threads <- o .: "threads"
4852− mem <- o .: "mem"
4853− pools <- mem .: "pools"
4854− oldM <- pools .: "old"
4855− survivorM <- pools .: "survivor"
4856− youngM <- pools .: "young"
4857− NodeJVMStats <$> pure mapped
4858− <*> pure direct
4859− <*> pure oldC
4860− <*> pure youngC
4861− <*> threads .: "peak_count"
4862− <*> threads .: "count"
4863− <*> pure oldM
4864− <*> pure survivorM
4865− <*> pure youngM
4866− <*> mem .: "non_heap_committed_in_bytes"
4867− <*> mem .: "non_heap_used_in_bytes"
4868− <*> mem .: "heap_max_in_bytes"
4869− <*> mem .: "heap_committed_in_bytes"
4870− <*> mem .: "heap_used_percent"
4871− <*> mem .: "heap_used_in_bytes"
4872− <*> (unMS <$> o .: "uptime_in_millis")
4873− <*> (posixMS <$> o .: "timestamp")
4874−
4875−instance FromJSON JVMBufferPoolStats where
4876− parseJSON = withObject "JVMBufferPoolStats" parse
4877− where
4878− parse o = JVMBufferPoolStats <$> o .: "total_capacity_in_bytes"
4879− <*> o .: "used_in_bytes"
4880− <*> o .: "count"
4881−
4882−instance FromJSON JVMGCStats where
4883− parseJSON = withObject "JVMGCStats" parse
4884− where
4885− parse o = JVMGCStats <$> (unMS <$> o .: "collection_time_in_millis")
4886− <*> o .: "collection_count"
4887−
4888−instance FromJSON JVMPoolStats where
4889− parseJSON = withObject "JVMPoolStats" parse
4890− where
4891− parse o = JVMPoolStats <$> o .: "peak_max_in_bytes"
4892− <*> o .: "peak_used_in_bytes"
4893− <*> o .: "max_in_bytes"
4894− <*> o .: "used_in_bytes"
4895−
4896−instance FromJSON NodeProcessStats where
4897− parseJSON = withObject "NodeProcessStats" parse
4898− where
4899− parse o = do
4900− mem <- o .: "mem"
4901− cpu <- o .: "cpu"
4902− NodeProcessStats <$> (posixMS <$> o .: "timestamp")
4903− <*> o .: "open_file_descriptors"
4904− <*> o .: "max_file_descriptors"
4905− <*> cpu .: "percent"
4906− <*> (unMS <$> cpu .: "total_in_millis")
4907− <*> mem .: "total_virtual_in_bytes"
4908−
4909−instance FromJSON NodeOSStats where
4910− parseJSON = withObject "NodeOSStats" parse
4911− where
4912− parse o = do
4913− swap <- o .: "swap"
4914− mem <- o .: "mem"
4915− cpu <- o .: "cpu"
4916− load <- o .:? "load_average"
4917− NodeOSStats <$> (posixMS <$> o .: "timestamp")
4918− <*> cpu .: "percent"
4919− <*> pure load
4920− <*> mem .: "total_in_bytes"
4921− <*> mem .: "free_in_bytes"
4922− <*> mem .: "free_percent"
4923− <*> mem .: "used_in_bytes"
4924− <*> mem .: "used_percent"
4925− <*> swap .: "total_in_bytes"
4926− <*> swap .: "free_in_bytes"
4927− <*> swap .: "used_in_bytes"
4928−
4929−instance FromJSON LoadAvgs where
4930− parseJSON = withArray "LoadAvgs" parse
4931− where
4932− parse v = case V.toList v of
4933− [one, five, fifteen] -> LoadAvgs <$> parseJSON one
4934− <*> parseJSON five
4935− <*> parseJSON fifteen
4936− _ -> fail "Expecting a triple of Doubles"
4937−
4938−instance FromJSON NodeIndicesStats where
4939− parseJSON = withObject "NodeIndicesStats" parse
4940− where
4941− parse o = do
4942− let (.::) mv k = case mv of
4943− Just v -> Just <$> v .: k
4944− Nothing -> pure Nothing
4945− mRecovery <- o .:? "recovery"
4946− mQueryCache <- o .:? "query_cache"
4947− mSuggest <- o .:? "suggest"
4948− translog <- o .: "translog"
4949− segments <- o .: "segments"
4950− completion <- o .: "completion"
4951− mPercolate <- o .:? "percolate"
4952− fielddata <- o .: "fielddata"
4953− warmer <- o .: "warmer"
4954− flush <- o .: "flush"
4955− refresh <- o .: "refresh"
4956− merges <- o .: "merges"
4957− search <- o .: "search"
4958− getStats <- o .: "get"
4959− indexing <- o .: "indexing"
4960− store <- o .: "store"
4961− docs <- o .: "docs"
4962− NodeIndicesStats <$> (fmap unMS <$> mRecovery .:: "throttle_time_in_millis")
4963− <*> mRecovery .:: "current_as_target"
4964− <*> mRecovery .:: "current_as_source"
4965− <*> mQueryCache .:: "miss_count"
4966− <*> mQueryCache .:: "hit_count"
4967− <*> mQueryCache .:: "evictions"
4968− <*> mQueryCache .:: "memory_size_in_bytes"
4969− <*> mSuggest .:: "current"
4970− <*> (fmap unMS <$> mSuggest .:: "time_in_millis")
4971− <*> mSuggest .:: "total"
4972− <*> translog .: "size_in_bytes"
4973− <*> translog .: "operations"
4974− <*> segments .:? "fixed_bit_set_memory_in_bytes"
4975− <*> segments .: "version_map_memory_in_bytes"
4976− <*> segments .:? "index_writer_max_memory_in_bytes"
4977− <*> segments .: "index_writer_memory_in_bytes"
4978− <*> segments .: "memory_in_bytes"
4979− <*> segments .: "count"
4980− <*> completion .: "size_in_bytes"
4981− <*> mPercolate .:: "queries"
4982− <*> mPercolate .:: "memory_size_in_bytes"
4983− <*> mPercolate .:: "current"
4984− <*> (fmap unMS <$> mPercolate .:: "time_in_millis")
4985− <*> mPercolate .:: "total"
4986− <*> fielddata .: "evictions"
4987− <*> fielddata .: "memory_size_in_bytes"
4988− <*> (unMS <$> warmer .: "total_time_in_millis")
4989− <*> warmer .: "total"
4990− <*> warmer .: "current"
4991− <*> (unMS <$> flush .: "total_time_in_millis")
4992− <*> flush .: "total"
4993− <*> (unMS <$> refresh .: "total_time_in_millis")
4994− <*> refresh .: "total"
4995− <*> merges .: "total_size_in_bytes"
4996− <*> merges .: "total_docs"
4997− <*> (unMS <$> merges .: "total_time_in_millis")
4998− <*> merges .: "total"
4999− <*> merges .: "current_size_in_bytes"
5000− <*> merges .: "current_docs"
5001− <*> merges .: "current"
5002− <*> search .: "fetch_current"
5003− <*> (unMS <$> search .: "fetch_time_in_millis")
5004− <*> search .: "fetch_total"
5005− <*> search .: "query_current"
5006− <*> (unMS <$> search .: "query_time_in_millis")
5007− <*> search .: "query_total"
5008− <*> search .: "open_contexts"
5009− <*> getStats .: "current"
5010− <*> (unMS <$> getStats .: "missing_time_in_millis")
5011− <*> getStats .: "missing_total"
5012− <*> (unMS <$> getStats .: "exists_time_in_millis")
5013− <*> getStats .: "exists_total"
5014− <*> (unMS <$> getStats .: "time_in_millis")
5015− <*> getStats .: "total"
5016− <*> (fmap unMS <$> indexing .:? "throttle_time_in_millis")
5017− <*> indexing .:? "is_throttled"
5018− <*> indexing .:? "noop_update_total"
5019− <*> indexing .: "delete_current"
5020− <*> (unMS <$> indexing .: "delete_time_in_millis")
5021− <*> indexing .: "delete_total"
5022− <*> indexing .: "index_current"
5023− <*> (unMS <$> indexing .: "index_time_in_millis")
5024− <*> indexing .: "index_total"
5025− <*> (unMS <$> store .: "throttle_time_in_millis")
5026− <*> store .: "size_in_bytes"
5027− <*> docs .: "deleted"
5028− <*> docs .: "count"
5029−
5030−instance FromJSON NodeBreakersStats where
5031− parseJSON = withObject "NodeBreakersStats" parse
5032− where
5033− parse o = NodeBreakersStats <$> o .: "parent"
5034− <*> o .: "request"
5035− <*> o .: "fielddata"
5036−
5037−parseNodeStats :: FullNodeId -> Object -> Parser NodeStats
5038−parseNodeStats fnid o = do
5039− NodeStats <$> o .: "name"
5040− <*> pure fnid
5041− <*> o .:? "breakers"
5042− <*> o .: "http"
5043− <*> o .: "transport"
5044− <*> o .: "fs"
5045− <*> o .:? "network"
5046− <*> o .: "thread_pool"
5047− <*> o .: "jvm"
5048− <*> o .: "process"
5049− <*> o .: "os"
5050− <*> o .: "indices"
5051−
5052−parseNodeInfo :: FullNodeId -> Object -> Parser NodeInfo
5053−parseNodeInfo nid o =
5054− NodeInfo <$> o .:? "http_address"
5055− <*> o .: "build_hash"
5056− <*> o .: "version"
5057− <*> o .: "ip"
5058− <*> o .: "host"
5059− <*> o .: "transport_address"
5060− <*> o .: "name"
5061− <*> pure nid
5062− <*> o .: "plugins"
5063− <*> o .: "http"
5064− <*> o .: "transport"
5065− <*> o .:? "network"
5066− <*> o .: "thread_pool"
5067− <*> o .: "jvm"
5068− <*> o .: "process"
5069− <*> o .: "os"
5070− <*> o .: "settings"
5071−
5072−instance FromJSON NodePluginInfo where
5073− parseJSON = withObject "NodePluginInfo" parse
5074− where
5075− parse o = NodePluginInfo <$> o .:? "site"
5076− <*> o .:? "jvm"
5077− <*> o .: "description"
5078− <*> o .: "version"
5079− <*> o .: "name"
5080−
5081−instance FromJSON NodeHTTPInfo where
5082− parseJSON = withObject "NodeHTTPInfo" parse
5083− where
5084− parse o = NodeHTTPInfo <$> o .: "max_content_length_in_bytes"
5085− <*> parseJSON (Object o)
5086−
5087−instance FromJSON BoundTransportAddress where
5088− parseJSON = withObject "BoundTransportAddress" parse
5089− where
5090− parse o = BoundTransportAddress <$> o .: "publish_address"
5091− <*> o .: "bound_address"
5092−
5093−instance FromJSON NodeOSInfo where
5094− parseJSON = withObject "NodeOSInfo" parse
5095− where
5096− parse o = do
5097− NodeOSInfo <$> (unMS <$> o .: "refresh_interval_in_millis")
5098− <*> o .: "name"
5099− <*> o .: "arch"
5100− <*> o .: "version"
5101− <*> o .: "available_processors"
5102− <*> o .: "allocated_processors"
5103−
5104−
5105−instance FromJSON CPUInfo where
5106− parseJSON = withObject "CPUInfo" parse
5107− where
5108− parse o = CPUInfo <$> o .: "cache_size_in_bytes"
5109− <*> o .: "cores_per_socket"
5110− <*> o .: "total_sockets"
5111− <*> o .: "total_cores"
5112− <*> o .: "mhz"
5113− <*> o .: "model"
5114− <*> o .: "vendor"
5115−
5116−instance FromJSON NodeProcessInfo where
5117− parseJSON = withObject "NodeProcessInfo" parse
5118− where
5119− parse o = NodeProcessInfo <$> o .: "mlockall"
5120− <*> o .:? "max_file_descriptors"
5121− <*> o .: "id"
5122− <*> (unMS <$> o .: "refresh_interval_in_millis")
5123−
5124−instance FromJSON NodeJVMInfo where
5125− parseJSON = withObject "NodeJVMInfo" parse
5126− where
5127− parse o = NodeJVMInfo <$> o .: "memory_pools"
5128− <*> o .: "gc_collectors"
5129− <*> o .: "mem"
5130− <*> (posixMS <$> o .: "start_time_in_millis")
5131− <*> o .: "vm_vendor"
5132− <*> o .: "vm_version"
5133− <*> o .: "vm_name"
5134− <*> (unJVMVersion <$> o .: "version")
5135− <*> o .: "pid"
5136−
5137−instance FromJSON JVMVersion where
5138− parseJSON (String t) =
5139− JVMVersion <$> parseJSON (String (T.replace "_" "." t))
5140− parseJSON v = JVMVersion <$> parseJSON v
5141−
5142−instance FromJSON JVMMemoryInfo where
5143− parseJSON = withObject "JVMMemoryInfo" parse
5144− where
5145− parse o = JVMMemoryInfo <$> o .: "direct_max_in_bytes"
5146− <*> o .: "non_heap_max_in_bytes"
5147− <*> o .: "non_heap_init_in_bytes"
5148− <*> o .: "heap_max_in_bytes"
5149− <*> o .: "heap_init_in_bytes"
5150−
5151−instance FromJSON NodeThreadPoolsInfo where
5152− parseJSON = withObject "NodeThreadPoolsInfo" parse
5153− where
5154− parse o = NodeThreadPoolsInfo <$> o .: "refresh"
5155− <*> o .: "management"
5156− <*> o .:? "percolate"
5157− <*> o .:? "listener"
5158− <*> o .:? "fetch_shard_started"
5159− <*> o .: "search"
5160− <*> o .: "flush"
5161− <*> o .: "warmer"
5162− <*> o .:? "optimize"
5163− <*> o .: "bulk"
5164− <*> o .:? "suggest"
5165− <*> o .: "force_merge"
5166− <*> o .: "snapshot"
5167− <*> o .: "get"
5168− <*> o .:? "fetch_shard_store"
5169− <*> o .: "index"
5170− <*> o .: "generic"
5171−
5172−instance FromJSON NodeThreadPoolInfo where
5173− parseJSON = withObject "NodeThreadPoolInfo" parse
5174− where
5175− parse o = do
5176− ka <- maybe (return Nothing) (fmap Just . parseStringInterval) =<< o .:? "keep_alive"
5177− NodeThreadPoolInfo <$> (parseJSON . unStringlyTypeJSON =<< o .: "queue_size")
5178− <*> pure ka
5179− <*> o .:? "min"
5180− <*> o .:? "max"
5181− <*> o .: "type"
5182−
5183−parseStringInterval :: (Monad m) => String -> m NominalDiffTime
5184−parseStringInterval s = case span isNumber s of
5185− ("", _) -> fail "Invalid interval"
5186− (nS, unitS) -> case (readMay nS, readMay unitS) of
5187− (Just n, Just unit) -> return (fromInteger (n * unitNDT unit))
5188− (Nothing, _) -> fail "Invalid interval number"
5189− (_, Nothing) -> fail "Invalid interval unit"
5190− where
5191− unitNDT Seconds = 1
5192− unitNDT Minutes = 60
5193− unitNDT Hours = 60 * 60
5194− unitNDT Days = 24 * 60 * 60
5195− unitNDT Weeks = 7 * 24 * 60 * 60
5196−
5197−instance FromJSON ThreadPoolSize where
5198− parseJSON v = parseAsNumber v <|> parseAsString v
5199− where
5200− parseAsNumber = parseAsInt <=< parseJSON
5201− parseAsInt (-1) = return ThreadPoolUnbounded
5202− parseAsInt n
5203− | n >= 0 = return (ThreadPoolBounded n)
5204− | otherwise = fail "Thread pool size must be >= -1."
5205− parseAsString = withText "ThreadPoolSize" $ \t ->
5206− case first (readMay . T.unpack) (T.span isNumber t) of
5207− (Just n, "k") -> return (ThreadPoolBounded (n * 1000))
5208− (Just n, "") -> return (ThreadPoolBounded n)
5209− _ -> fail ("Invalid thread pool size " <> T.unpack t)
5210−
5211−instance FromJSON ThreadPoolType where
5212− parseJSON = withText "ThreadPoolType" parse
5213− where
5214− parse "scaling" = return ThreadPoolScaling
5215− parse "fixed" = return ThreadPoolFixed
5216− parse "cached" = return ThreadPoolCached
5217− parse e = fail ("Unexpected thread pool type" <> T.unpack e)
5218−
5219−instance FromJSON NodeTransportInfo where
5220− parseJSON = withObject "NodeTransportInfo" parse
5221− where
5222− parse o = NodeTransportInfo <$> (maybe (return mempty) parseProfiles =<< o .:? "profiles")
5223− <*> parseJSON (Object o)
5224− parseProfiles (Object o) | HM.null o = return []
5225− parseProfiles v@(Array _) = parseJSON v
5226− parseProfiles Null = return []
5227− parseProfiles _ = fail "Could not parse profiles"
5228−
5229−instance FromJSON NodeNetworkInfo where
5230− parseJSON = withObject "NodeNetworkInfo" parse
5231− where
5232− parse o = NodeNetworkInfo <$> o .: "primary_interface"
5233− <*> (unMS <$> o .: "refresh_interval_in_millis")
5234−
5235−
5236−instance FromJSON NodeNetworkInterface where
5237− parseJSON = withObject "NodeNetworkInterface" parse
5238− where
5239− parse o = NodeNetworkInterface <$> o .: "mac_address"
5240− <*> o .: "name"
5241− <*> o .: "address"
52421581
5243−newtype MaybeNA a = MaybeNA { unMaybeNA :: Maybe a }
5244− deriving (Show, Eq)
52451582
5246−instance FromJSON a => FromJSON (MaybeNA a) where
5247− parseJSON (String "NA") = pure $ MaybeNA Nothing
5248− parseJSON o = MaybeNA . Just <$> parseJSON o
52491583
52501584data Suggest = Suggest { suggestText :: Text
52511585 , suggestName :: Text
52521586 , suggestType :: SuggestType
52531587 }
5254− deriving (Show, Generic, Eq, Read)
1588+ deriving (Eq, Show)
52551589
52561590instance ToJSON Suggest where
52571591 toJSON Suggest{..} = object [ "text" .= suggestText
@@ -5270,7 +1604,7 @@ instance FromJSON Suggest where
52701604 parseJSON x = typeMismatch "Suggest" x
52711605
52721606data SuggestType = SuggestTypePhraseSuggester PhraseSuggester
5273− deriving (Show, Generic, Eq, Read)
1607+ deriving (Eq, Show)
52741608
52751609instance ToJSON SuggestType where
52761610 toJSON (SuggestTypePhraseSuggester x) = object ["phrase" .= x]
@@ -5294,7 +1628,7 @@ data PhraseSuggester =
52941628 , phraseSuggesterHighlight :: Maybe PhraseSuggesterHighlighter
52951629 , phraseSuggesterCollate :: Maybe PhraseSuggesterCollate
52961630 }
5297− deriving (Show, Generic, Eq, Read)
1631+ deriving (Eq, Show)
52981632
52991633instance ToJSON PhraseSuggester where
53001634 toJSON PhraseSuggester{..} = omitNulls [ "field" .= phraseSuggesterField
@@ -5334,7 +1668,7 @@ data PhraseSuggesterHighlighter =
53341668 PhraseSuggesterHighlighter { phraseSuggesterHighlighterPreTag :: Text
53351669 , phraseSuggesterHighlighterPostTag :: Text
53361670 }
5337− deriving (Show, Generic, Eq, Read)
1671+ deriving (Eq, Show)
53381672
53391673instance ToJSON PhraseSuggesterHighlighter where
53401674 toJSON PhraseSuggesterHighlighter{..} =
@@ -5352,7 +1686,7 @@ data PhraseSuggesterCollate =
53521686 PhraseSuggesterCollate { phraseSuggesterCollateTemplateQuery :: TemplateQueryInline
53531687 , phraseSuggesterCollatePrune :: Bool
53541688 }
5355− deriving (Show, Generic, Eq, Read)
1689+ deriving (Eq, Show)
53561690
53571691instance ToJSON PhraseSuggesterCollate where
53581692 toJSON PhraseSuggesterCollate{..} = object [ "query" .= object