@@ -378,535 +378,30 @@ module Database.V1.Bloodhound.Types
378 , EsPassword(..)
378 , EsPassword(..)
381−import Control.Applicative as A
381+import Bloodhound.Import
382−import Control.Arrow (first)
383−import Control.Monad.Catch
384−import Control.Monad.Except
385−import Control.Monad.Reader (MonadReader (..),
387−import Control.Monad.State (MonadState)
388−import Control.Monad.Writer (MonadWriter)
390−import Data.Aeson.Types (Pair, Parser,
395−import qualified Data.ByteString.Lazy.Char8 as L
397−import Data.Hashable (Hashable)
398−import qualified Data.HashMap.Strict as HM
399−import Data.List (foldl', intercalate,
401−import Data.List.NonEmpty (NonEmpty (..), toList)
402−import qualified Data.Map.Strict as M
404−import Data.Scientific (Scientific)
405−import Data.Semigroup
406−import Data.Text (Text)
407−import qualified Data.Text as T
408−import Data.Time.Calendar
409−import Data.Time.Clock (NominalDiffTime,
411−import Data.Time.Clock.POSIX
412−import qualified Data.Traversable as DT
413−import Data.Typeable (Typeable)
414−import qualified Data.Vector as V
415−import qualified Data.Version as Vers
417−import GHC.Generics (Generic)
418−import Network.HTTP.Client
419−import qualified Network.HTTP.Types.Method as NHTM
420−import qualified Text.ParserCombinators.ReadP as RP
421−import qualified Text.Read as TR
423−import Database.V1.Bloodhound.Internal.Client
424import Database.V1.Bloodhound.Types.Class
383import Database.V1.Bloodhound.Types.Class
384+import Database.V1.Bloodhound.Internal.Aggregation
385+import Database.V1.Bloodhound.Internal.Client
386+import Database.V1.Bloodhound.Internal.Highlight
387+import Database.V1.Bloodhound.Internal.Newtypes
388+import Database.V1.Bloodhound.Internal.Query
389+import Database.V1.Bloodhound.Internal.Sort
390+import Database.V1.Bloodhound.Internal.Suggest
392+data SearchResult a =
393+ SearchResult { took :: Int
395+ , shards :: ShardResult
396+ , searchHits :: SearchHits a
397+ , aggregations :: Maybe AggregationResults
398+ , scrollId :: Maybe ScrollId
399+ , suggest :: Maybe NamedSuggestionResponse -- ^ Only one Suggestion request / response per Search is supported.
428−data FSType = FSSimple
429− | FSBuffered deriving (Eq, Read, Show, Generic, Typeable, Ord)
431−data InitialShardCount = QuorumShards
432− | QuorumMinus1Shards
435− | ExplicitShards Int
436− deriving (Eq, Read, Show, Generic, Typeable)
438−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
439− , nodeAttrFilterValues :: NonEmpty Text}
440− deriving (Eq, Read, Show, Generic, Ord, Typeable)
442−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Read, Show, Ord, Generic, Typeable)
444−data CompoundFormat = CompoundFileFormat Bool
445− | MergeSegmentVsTotalIndex Double
446− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
447− deriving (Eq, Read, Show, Generic, Typeable)
449−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
451−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
452− , sSummaryFixedSettings :: IndexSettings
453− , sSummaryUpdateable :: [UpdatableIndexSetting]}
454− deriving (Eq, Show, Generic, Typeable)
456−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
457−type Reply = Network.HTTP.Client.Response L.ByteString
458−type Method = NHTM.Method
460−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
462− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
464−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Read, Show, Generic, Typeable)
466−data FieldType = GeoPointType
472− | ByteType deriving (Eq, Read, Show, Generic, Typeable)
474−data FieldDefinition =
475− FieldDefinition { fieldType :: FieldType } deriving (Eq, Read, Show, Generic, Typeable)
477−{-| An 'IndexTemplate' defines a template that will automatically be
478− applied to new indices created. The templates include both
479− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
480− controls if the template will be applied to the index created.
481− Specify mappings as follows: @[toJSON TweetMapping, ...]@
483− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
486− IndexTemplate { templatePattern :: TemplatePattern
487− , templateSettings :: Maybe IndexSettings
488− , templateMappings :: [Value]
492− MappingField { mappingFieldName :: FieldName
493− , fieldDefinition :: FieldDefinition } deriving (Eq, Read, Show, Generic, Typeable)
495−{-| Support for type reification of 'Mapping's is currently incomplete, for
496− now the mapping API verbiage expects a 'ToJSON'able blob.
498− Indexes have mappings, mappings are schemas for the documents contained in the
499− index. I'd recommend having only one mapping per index, always having a mapping,
500− and keeping different kinds of documents separated if possible.
502−data Mapping = Mapping { typeName :: TypeName
503− , mappingFields :: [MappingField] } deriving (Eq, Read, Show, Generic, Typeable)
505−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
506− operation index, create, delete, and update. 'BulkIndex' behaves like an
507− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
509− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
512− BulkIndex IndexName MappingName DocId Value
513− | BulkCreate IndexName MappingName DocId Value
514− | BulkDelete IndexName MappingName DocId
515− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Read, Show, Generic, Typeable)
517−{-| 'EsResult' describes the standard wrapper JSON document that you see in
518− successful Elasticsearch lookups or lookups that couldn't find the document.
520−data EsResult a = EsResult { _index :: Text
523− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Read, Show, Generic, Typeable)
525−{-| 'EsResultFound' contains the document and its metadata inside of an
526− 'EsResult' when the document was successfully found.
528−data EsResultFound a = EsResultFound { _version :: DocVersion
529− , _source :: a } deriving (Eq, Read, Show, Generic, Typeable)
531−{-| 'EsError' is the generic type that will be returned when there was a
532− problem. If you can't parse the expected response, its a good idea to
535−data EsError = EsError { errorStatus :: Int
536− , errorMessage :: Text } deriving (Eq, Read, Show, Generic, Typeable)
538−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
539−returned by the ElasticSearch server. If you encounter this error, please
540−verify that your domain data types and FromJSON instances are working properly
541−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
542−sure that your mappings are correct, then this error may be an indication of an
543−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
544−and be sure to include the exception body.
546−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
547− deriving (Eq, Read, Show, Generic, Typeable)
549−instance Exception EsProtocolException
551−data IndexAlias = IndexAlias { srcIndex :: IndexName
552− , indexAlias :: IndexAliasName } deriving (Eq, Read, Show, Generic, Typeable)
554−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Read, Show, Generic, ToJSON)
556−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
557− | RemoveAlias IndexAlias deriving (Read, Show, Eq, Generic, Typeable)
559−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
560− , aliasCreateFilter :: Maybe Filter}
561− deriving (Read, Show, Eq, Generic, Typeable)
563−data AliasRouting = AllAliasRouting RoutingValue
564− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
565− deriving (Read, Show, Eq, Generic, Typeable)
567−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Read, Show, Eq, Generic, Typeable)
569−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
571−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Read, Show, Eq, Generic, ToJSON, FromJSON, Typeable)
573−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Read, Show, Eq, Generic, Typeable)
575−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
576−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
577− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Read, Show, Eq, Generic, Typeable)
579−{-| 'DocVersion' is an integer version number for a document between 1
580−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
582−newtype DocVersion = DocVersion {
583− docVersionNumber :: Int
584− } deriving (Eq, Read, Show, Generic, Ord, ToJSON)
586−-- | Smart constructor for in-range doc version
587−mkDocVersion :: Int -> Maybe DocVersion
589− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
591− | otherwise = Nothing
594−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
595−own version numbers instead of ones from ES.
597−newtype ExternalDocVersion = ExternalDocVersion DocVersion
598− deriving (Eq, Read, Show, Generic, Ord, Bounded, Enum, ToJSON)
600−{-| 'VersionControl' is specified when indexing documents as a
601−optimistic concurrency control.
603−data VersionControl = NoVersionControl
604− -- ^ Don't send a version. This is a pure overwrite.
605− | InternalVersion DocVersion
606− -- ^ Use the default ES versioning scheme. Only
607− -- index the document if the version is the same
608− -- as the one specified. Only applicable to
609− -- updates, as you should be getting Version from
611− | ExternalGT ExternalDocVersion
612− -- ^ Use your own version numbering. Only index
613− -- the document if the version is strictly higher
614− -- OR the document doesn't exist. The given
615− -- version will be used as the new version number
616− -- for the stored document. N.B. All updates must
617− -- increment this number, meaning there is some
618− -- global, external ordering of updates.
619− | ExternalGTE ExternalDocVersion
620− -- ^ Use your own version numbering. Only index
621− -- the document if the version is equal or higher
622− -- than the stored version. Will succeed if there
623− -- is no existing document. The given version will
624− -- be used as the new version number for the
625− -- stored document. Use with care, as this could
626− -- result in data loss.
627− | ForceVersion ExternalDocVersion
628− -- ^ The document will always be indexed and the
629− -- given version will be the new version. This is
630− -- typically used for correcting errors. Use with
631− -- care, as this could result in data loss.
632− deriving (Read, Show, Eq, Generic, Ord)
634−{-| 'DocumentParent' is used to specify a parent document.
636−newtype DocumentParent = DocumentParent DocId
637− deriving (Eq, Read, Show, Generic, Typeable)
639−{-| 'IndexDocumentSettings' are special settings supplied when indexing
640−a document. For the best backwards compatiblity when new fields are
641−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
643−data IndexDocumentSettings =
644− IndexDocumentSettings { idsVersionControl :: VersionControl
645− , idsParent :: Maybe DocumentParent
646− } deriving (Eq, Read, Show, Generic, Typeable)
648−{-| Reasonable default settings. Chooses no version control and no parent.
650−defaultIndexDocumentSettings :: IndexDocumentSettings
651−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
653−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
654− dependent with later sorts acting as tie-breakers for earlier sorts.
656−type Sort = [SortSpec]
658−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
659− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
660− 'DistanceUnit' to express "nearness" to a single geographical point as a
663−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
665−data SortSpec = DefaultSortSpec DefaultSort
666− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Read, Show, Generic, Typeable)
668−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
669− 'mkSort' convenience function for when you want to specify only the most
672−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
675− DefaultSort { sortFieldName :: FieldName
676− , sortOrder :: SortOrder
678− , ignoreUnmapped :: Bool
679− , sortMode :: Maybe SortMode
680− , missingSort :: Maybe Missing
681− , nestedFilter :: Maybe Filter } deriving (Eq, Read, Show, Generic, Typeable)
683−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
684− encoded into "asc" or "desc" when turned into JSON.
686−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
688−data SortOrder = Ascending
689− | Descending deriving (Eq, Read, Show, Generic, Typeable)
691−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
692− sorted last, first, or using a custom value as a substitute.
694−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
696−data Missing = LastMissing
698− | CustomMissing Text deriving (Eq, Read, Show, Generic, Typeable)
700−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
702−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
704−data SortMode = SortMin
707− | SortAvg deriving (Eq, Read, Show, Generic, Typeable)
709−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
710− that you can concisely describe the usual kind of 'SortSpec's you want.
712−mkSort :: FieldName -> SortOrder -> DefaultSort
713−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
715−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
716− 'Query's cannot be cached.
718−type Cache = Bool -- caching on/off
719−defaultCache :: Cache
722−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
724−type PrefixValue = Text
726−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
727− JSON encoding baked in. Used all over the place.
729−data BooleanOperator = And | Or deriving (Eq, Read, Show, Generic, Typeable)
731−{-| 'ShardCount' is part of 'IndexSettings'
733−newtype ShardCount = ShardCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
735−{-| 'ReplicaCount' is part of 'IndexSettings'
737−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Read, Show, Generic, ToJSON, Typeable)
739−{-| 'IndexName' is used to describe which index to query/create/delete
741−newtype IndexName = IndexName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
743−{-| 'IndexSelection' is used for APIs which take a single index, a list of
744− indexes, or the special @_all@ index.
746−--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.
747−data IndexSelection = IndexList (NonEmpty IndexName)
748− | AllIndexes deriving (Eq, Generic, Show, Typeable)
750−{-| '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.
752−data NodeSelection = LocalNode
753− -- ^ Whatever node receives this request
754− | NodeList (NonEmpty NodeSelector)
755− | AllNodes deriving (Eq, Generic, Show, Typeable)
758−-- | An exact match or pattern to identify a node. Note that All of
759−-- these options support wildcarding, so your node name, server, attr
760−-- name can all contain * characters to be a fuzzy match.
761−data NodeSelector = NodeByName NodeName
762− | NodeByFullNodeId FullNodeId
764− -- ^ e.g. 10.0.0.1 or even 10.0.0.*
765− | NodeByAttribute NodeAttrName Text
766− -- ^ NodeAttrName can be a pattern, e.g. rack*. The value can too.
767− deriving (Eq, Generic, Show, Typeable)
769−{-| 'TemplateName' is used to describe which template to query/create/delete
771−newtype TemplateName = TemplateName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
773−{-| 'TemplatePattern' represents a pattern which is matched against index names
775−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
777−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
778− the data in the indices.
780−newtype MappingName = MappingName Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
782−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
783− Can be set by the user or created by ES itself. Often used in client
784− functions for poking at specific documents.
786−newtype DocId = DocId Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
788−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
790−newtype QueryString = QueryString Text deriving (Eq, Generic, Read, Show, ToJSON, FromJSON, Typeable)
792−{-| 'FieldName' is used all over the place wherever a specific field within
793− a document needs to be specified, usually in 'Query's or 'Filter's.
795−newtype FieldName = FieldName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
798−{-| 'Script' is often used in place of 'FieldName' to specify more
799−complex ways of extracting a value from a document.
801−newtype Script = Script { scriptText :: Text } deriving (Eq, Read, Show, Generic, Typeable)
803−{-| 'CacheName' is used in 'RegexpFilter' for describing the
804− 'CacheKey' keyed caching behavior.
806−newtype CacheName = CacheName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
808−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
811− CacheKey Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
813− Existence Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
815− NullValue Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
816−newtype CutoffFrequency =
817− CutoffFrequency Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
819− Analyzer Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
820−newtype MaxExpansions =
821− MaxExpansions Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
823−{-| 'Lenient', if set to true, will cause format based failures to be
824− ignored. I don't know what the bloody default is, Elasticsearch
825− documentation didn't say what it was. Let me know if you figure it out.
828− Lenient Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
830− Tiebreaker Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
832− Boost Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
834− BoostTerms Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
836−{-| 'MinimumMatch' controls how many should clauses in the bool query should
837− match. Can be an absolute value (2) or a percentage (30%) or a
838− combination of both.
840−newtype MinimumMatch =
841− MinimumMatch Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
842−newtype DisableCoord =
843− DisableCoord Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
844−newtype IgnoreTermFrequency =
845− IgnoreTermFrequency Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
846−newtype MinimumTermFrequency =
847− MinimumTermFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
848−newtype MaxQueryTerms =
849− MaxQueryTerms Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
851− Fuzziness Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
853−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
854−newtype PrefixLength =
855− PrefixLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
857− TypeName Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
858−newtype PercentMatch =
859− PercentMatch Double deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
861− StopWord Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
863− QueryPath Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
865−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
866− heavy, because all terms in the index need to be examined, just in case
867− they match. Leading wildcards can be disabled by setting
868− 'AllowLeadingWildcard' to false. -}
869−newtype AllowLeadingWildcard =
870− AllowLeadingWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
871−newtype LowercaseExpanded =
872− LowercaseExpanded Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
873−newtype EnablePositionIncrements =
874− EnablePositionIncrements Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
876−{-| By default, wildcard terms in a query are not analyzed.
877− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
879−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
881−{-| 'GeneratePhraseQueries' defaults to false.
883−newtype GeneratePhraseQueries =
884− GeneratePhraseQueries Bool deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
886−{-| 'Locale' is used for string conversions - defaults to ROOT.
888−newtype Locale = Locale Text deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
889−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
890−newtype MinWordLength = MinWordLength Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
892−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
893− phrase matches. Default is 0.
895−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
896−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
897−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
899−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
900−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
902−{-| 'unpackId' is a silly convenience function that gets used once.
904−unpackId :: DocId -> Text
905−unpackId (DocId docId) = docId
907type TrackSortScores = Bool
404type TrackSortScores = Bool
908−newtype From = From Int deriving (Eq, Read, Show, Generic, ToJSON)
909−newtype Size = Size Int deriving (Eq, Read, Show, Generic, ToJSON, FromJSON, Typeable)
911data Search = Search { queryBody :: Maybe Query
406data Search = Search { queryBody :: Maybe Query
912 , filterBody :: Maybe Filter
407 , filterBody :: Maybe Filter
@@ -921,7 +416,7 @@ data Search = Search { queryBody :: Maybe Query
921 , fields :: Maybe [FieldName]
416 , fields :: Maybe [FieldName]
922 , source :: Maybe Source
417 , source :: Maybe Source
923 , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
418 , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
924− } deriving (Eq, Read, Show, Generic, Typeable)
419+ } deriving (Eq, Show)
926data SearchType = SearchTypeQueryThenFetch
421data SearchType = SearchTypeQueryThenFetch
927 | SearchTypeDfsQueryThenFetch
422 | SearchTypeDfsQueryThenFetch
@@ -929,2570 +424,22 @@ data SearchType = SearchTypeQueryThenFetch
929 | SearchTypeScan
424 | SearchTypeScan
930 | SearchTypeQueryAndFetch
425 | SearchTypeQueryAndFetch
931 | SearchTypeDfsQueryAndFetch
426 | SearchTypeDfsQueryAndFetch
932− deriving (Eq, Read, Show, Generic, Typeable)
427+ deriving (Eq, Show)
936− | SourcePatterns PatternOrPatterns
937− | SourceIncludeExclude Include Exclude
938− deriving (Read, Show, Eq, Generic, Typeable)
940−data PatternOrPatterns =
942− | PopPatterns [Pattern]
943− deriving (Eq, Read, Show, Generic, Typeable)
945−data Include = Include [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
946−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show, Generic, Typeable)
948−newtype Pattern = Pattern Text deriving (Eq, Read, Show, Generic, Typeable)
950−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
951− , highlightFields :: [FieldHighlight]
952− } deriving (Read, Show, Eq, Generic, Typeable)
954−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
955− deriving (Read, Show, Eq, Generic, Typeable)
958−data HighlightSettings = Plain PlainHighlight
959− | Postings PostingsHighlight
960− | FastVector FastVectorHighlight
961− deriving (Read, Show, Eq, Generic, Typeable)
962−data PlainHighlight =
963− PlainHighlight { plainCommon :: Maybe CommonHighlight
964− , plainNonPost :: Maybe NonPostings } deriving (Read, Show, Eq, Generic, Typeable)
966− -- This requires that index_options are set to 'offset' in the mapping.
967−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Read, Show, Eq, Generic, Typeable)
969−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
970−data FastVectorHighlight =
971− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
972− , fvNonPostSettings :: Maybe NonPostings
973− , boundaryChars :: Maybe Text
974− , boundaryMaxScan :: Maybe Int
975− , fragmentOffset :: Maybe Int
976− , matchedFields :: [Text]
977− , phraseLimit :: Maybe Int
978− } deriving (Read, Show, Eq, Generic, Typeable)
980−data CommonHighlight =
981− CommonHighlight { order :: Maybe Text
982− , forceSource :: Maybe Bool
983− , tag :: Maybe HighlightTag
984− , encoder :: Maybe HighlightEncoder
985− , noMatchSize :: Maybe Int
986− , highlightQuery :: Maybe Query
987− , requireFieldMatch :: Maybe Bool
988− } deriving (Read, Show, Eq, Generic, Typeable)
990−-- Settings that are only applicable to FastVector and Plain highlighters.
992− NonPostings { fragmentSize :: Maybe Int
993− , numberOfFragments :: Maybe Int} deriving (Read, Show, Eq, Generic, Typeable)
995−data HighlightEncoder = DefaultEncoder
997− deriving (Read, Show, Eq, Generic, Typeable)
999−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
1000−data HighlightTag = TagSchema Text
1001− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1002− deriving (Read, Show, Eq, Generic, Typeable)
1006− TermQuery Term (Maybe Boost)
1007− | TermsQuery Text (NonEmpty Text)
1008− | QueryMatchQuery MatchQuery
1009− | QueryMultiMatchQuery MultiMatchQuery
1010− | QueryBoolQuery BoolQuery
1011− | QueryBoostingQuery BoostingQuery
1012− | QueryCommonTermsQuery CommonTermsQuery
1013− | ConstantScoreFilter Filter Boost
1014− | ConstantScoreQuery Query Boost
1015− | QueryDisMaxQuery DisMaxQuery
1016− | QueryFilteredQuery FilteredQuery
1017− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1018− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1019− | QueryFuzzyQuery FuzzyQuery
1020− | QueryHasChildQuery HasChildQuery
1021− | QueryHasParentQuery HasParentQuery
1022− | IdsQuery MappingName [DocId]
1023− | QueryIndicesQuery IndicesQuery
1024− | MatchAllQuery (Maybe Boost)
1025− | QueryMoreLikeThisQuery MoreLikeThisQuery
1026− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1027− | QueryNestedQuery NestedQuery
1028− | QueryPrefixQuery PrefixQuery
1029− | QueryQueryStringQuery QueryStringQuery
1030− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1031− | QueryRangeQuery RangeQuery
1032− | QueryRegexpQuery RegexpQuery
1033− | QueryTemplateQueryInline TemplateQueryInline
1034− deriving (Eq, Read, Show, Generic, Typeable)
1037− RegexpQuery { regexpQueryField :: FieldName
1038− , regexpQuery :: Regexp
1039− , regexpQueryFlags :: RegexpFlags
1040− , regexpQueryBoost :: Maybe Boost
1041− } deriving (Eq, Read, Show, Generic, Typeable)
1044− RangeQuery { rangeQueryField :: FieldName
1045− , rangeQueryRange :: RangeValue
1046− , rangeQueryBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1048−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1049−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1051−data SimpleQueryStringQuery =
1052− SimpleQueryStringQuery
1053− { simpleQueryStringQuery :: QueryString
1054− , simpleQueryStringField :: Maybe FieldOrFields
1055− , simpleQueryStringOperator :: Maybe BooleanOperator
1056− , simpleQueryStringAnalyzer :: Maybe Analyzer
1057− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1058− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1059− , simpleQueryStringLocale :: Maybe Locale
1060− } deriving (Eq, Read, Show, Generic, Typeable)
1062−data SimpleQueryFlag =
1067− | SimpleQueryPrefix
1068− | SimpleQueryPhrase
1069− | SimpleQueryPrecedence
1070− | SimpleQueryEscape
1071− | SimpleQueryWhitespace
1074− | SimpleQuerySlop deriving (Eq, Read, Show, Generic, Typeable)
1076−-- use_dis_max and tie_breaker when fields are plural?
1077−data QueryStringQuery =
1079− { queryStringQuery :: QueryString
1080− , queryStringDefaultField :: Maybe FieldName
1081− , queryStringOperator :: Maybe BooleanOperator
1082− , queryStringAnalyzer :: Maybe Analyzer
1083− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1084− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1085− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1086− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1087− , queryStringFuzziness :: Maybe Fuzziness
1088− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1089− , queryStringPhraseSlop :: Maybe PhraseSlop
1090− , queryStringBoost :: Maybe Boost
1091− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1092− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1093− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1094− , queryStringLenient :: Maybe Lenient
1095− , queryStringLocale :: Maybe Locale
1096− } deriving (Eq, Read, Show, Generic, Typeable)
1098−mkQueryStringQuery :: QueryString -> QueryStringQuery
1099−mkQueryStringQuery qs =
1100− QueryStringQuery qs Nothing Nothing
1101− Nothing Nothing Nothing Nothing
1102− Nothing Nothing Nothing Nothing
1103− Nothing Nothing Nothing Nothing
1106−data FieldOrFields = FofField FieldName
1107− | FofFields (NonEmpty FieldName) deriving (Eq, Read, Show, Generic, Typeable)
1111− { prefixQueryField :: FieldName
1112− , prefixQueryPrefixValue :: Text
1113− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1117− { nestedQueryPath :: QueryPath
1118− , nestedQueryScoreType :: ScoreType
1119− , nestedQuery :: Query } deriving (Eq, Read, Show, Generic, Typeable)
1121−data MoreLikeThisFieldQuery =
1122− MoreLikeThisFieldQuery
1123− { moreLikeThisFieldText :: Text
1124− , moreLikeThisFieldFields :: FieldName
1125− -- default 0.3 (30%)
1126− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1127− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1128− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1129− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1130− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1131− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1132− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1133− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1134− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1135− , moreLikeThisFieldBoost :: Maybe Boost
1136− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1137− } deriving (Eq, Read, Show, Generic, Typeable)
1139−data MoreLikeThisQuery =
1141− { moreLikeThisText :: Text
1142− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1143− -- default 0.3 (30%)
1144− , moreLikeThisPercentMatch :: Maybe PercentMatch
1145− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1146− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1147− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1148− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1149− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1150− , moreLikeThisMinWordLength :: Maybe MinWordLength
1151− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1152− , moreLikeThisBoostTerms :: Maybe BoostTerms
1153− , moreLikeThisBoost :: Maybe Boost
1154− , moreLikeThisAnalyzer :: Maybe Analyzer
1155− } deriving (Eq, Read, Show, Generic, Typeable)
1159− { indicesQueryIndices :: [IndexName]
1160− , indicesQuery :: Query
1162− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Read, Show, Generic, Typeable)
1164−data HasParentQuery =
1166− { hasParentQueryType :: TypeName
1167− , hasParentQuery :: Query
1168− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1170−data HasChildQuery =
1172− { hasChildQueryType :: TypeName
1173− , hasChildQuery :: Query
1174− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Read, Show, Generic, Typeable)
1180− | ScoreTypeNone deriving (Eq, Read, Show, Generic, Typeable)
1183− FuzzyQuery { fuzzyQueryField :: FieldName
1184− , fuzzyQueryValue :: Text
1185− , fuzzyQueryPrefixLength :: PrefixLength
1186− , fuzzyQueryMaxExpansions :: MaxExpansions
1187− , fuzzyQueryFuzziness :: Fuzziness
1188− , fuzzyQueryBoost :: Maybe Boost
1189− } deriving (Eq, Read, Show, Generic, Typeable)
1191−data FuzzyLikeFieldQuery =
429+instance ToJSON Search where
1192− FuzzyLikeFieldQuery
430+ toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource sSuggest) =
1193− { fuzzyLikeField :: FieldName
431+ omitNulls [ "query" .= query
1194− -- anaphora is good for the soul.
432+ , "filter" .= sFilter
1195− , fuzzyLikeFieldText :: Text
433+ , "sort" .= sort
1196− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
434+ , "aggregations" .= searchAggs
1197− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
435+ , "highlight" .= highlight
1198− , fuzzyLikeFieldFuzziness :: Fuzziness
436+ , "from" .= sFrom
1199− , fuzzyLikeFieldPrefixLength :: PrefixLength
437+ , "size" .= sSize
1200− , fuzzyLikeFieldBoost :: Boost
438+ , "track_scores" .= sTrackSortScores
1201− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
439+ , "fields" .= sFields
1202− } deriving (Eq, Read, Show, Generic, Typeable)
440+ , "_source" .= sSource
1203−
441+ , "suggest" .= sSuggest]
1204−data FuzzyLikeThisQuery =
1206− { fuzzyLikeFields :: [FieldName]
1207− , fuzzyLikeText :: Text
1208− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1209− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1210− , fuzzyLikeFuzziness :: Fuzziness
1211− , fuzzyLikePrefixLength :: PrefixLength
1212− , fuzzyLikeBoost :: Boost
1213− , fuzzyLikeAnalyzer :: Maybe Analyzer
1214− } deriving (Eq, Read, Show, Generic, Typeable)
1216−data FilteredQuery =
1218− { filteredQuery :: Query
1219− , filteredFilter :: Filter } deriving (Eq, Read, Show, Generic, Typeable)
1222− DisMaxQuery { disMaxQueries :: [Query]
1224− , disMaxTiebreaker :: Tiebreaker
1225− , disMaxBoost :: Maybe Boost
1226− } deriving (Eq, Read, Show, Generic, Typeable)
1229− MatchQuery { matchQueryField :: FieldName
1230− , matchQueryQueryString :: QueryString
1231− , matchQueryOperator :: BooleanOperator
1232− , matchQueryZeroTerms :: ZeroTermsQuery
1233− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1234− , matchQueryMatchType :: Maybe MatchQueryType
1235− , matchQueryAnalyzer :: Maybe Analyzer
1236− , matchQueryMaxExpansions :: Maybe MaxExpansions
1237− , matchQueryLenient :: Maybe Lenient
1238− , matchQueryBoost :: Maybe Boost } deriving (Eq, Read, Show, Generic, Typeable)
1240−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1241− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1243−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1244−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1246−data MatchQueryType =
1248− | MatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1250−data MultiMatchQuery =
1251− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1252− , multiMatchQueryString :: QueryString
1253− , multiMatchQueryOperator :: BooleanOperator
1254− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1255− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1256− , multiMatchQueryType :: Maybe MultiMatchQueryType
1257− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1258− , multiMatchQueryAnalyzer :: Maybe Analyzer
1259− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1260− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Read, Show, Generic, Typeable)
1262−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1263− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1264− make a 'MultiMatchQuery'.
1267−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1268−mkMultiMatchQuery matchFields query =
1269− MultiMatchQuery matchFields query
1270− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1272−data MultiMatchQueryType =
1273− MultiMatchBestFields
1274− | MultiMatchMostFields
1275− | MultiMatchCrossFields
1277− | MultiMatchPhrasePrefix deriving (Eq, Read, Show, Generic, Typeable)
1280− BoolQuery { boolQueryMustMatch :: [Query]
1281− , boolQueryMustNotMatch :: [Query]
1282− , boolQueryShouldMatch :: [Query]
1283− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1284− , boolQueryBoost :: Maybe Boost
1285− , boolQueryDisableCoord :: Maybe DisableCoord
1286− } deriving (Eq, Read, Show, Generic, Typeable)
1288−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1289−mkBoolQuery must mustNot should =
1290− BoolQuery must mustNot should Nothing Nothing Nothing
1292−data BoostingQuery =
1293− BoostingQuery { positiveQuery :: Query
1294− , negativeQuery :: Query
1295− , negativeBoost :: Boost } deriving (Eq, Read, Show, Generic, Typeable)
1297−data CommonTermsQuery =
1298− CommonTermsQuery { commonField :: FieldName
1299− , commonQuery :: QueryString
1300− , commonCutoffFrequency :: CutoffFrequency
1301− , commonLowFreqOperator :: BooleanOperator
1302− , commonHighFreqOperator :: BooleanOperator
1303− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1304− , commonBoost :: Maybe Boost
1305− , commonAnalyzer :: Maybe Analyzer
1306− , commonDisableCoord :: Maybe DisableCoord
1307− } deriving (Eq, Read, Show, Generic, Typeable)
1309−data CommonMinimumMatch =
1310− CommonMinimumMatchHighLow MinimumMatchHighLow
1311− | CommonMinimumMatch MinimumMatch
1312− deriving (Eq, Read, Show, Generic, Typeable)
1314−data MinimumMatchHighLow =
1315− MinimumMatchHighLow { lowFreq :: MinimumMatch
1316− , highFreq :: MinimumMatch } deriving (Eq, Read, Show, Generic, Typeable)
1318−data Filter = AndFilter [Filter] Cache
1319− | OrFilter [Filter] Cache
1320− | NotFilter Filter Cache
1322− | BoolFilter BoolMatch
1323− | ExistsFilter FieldName -- always cached
1324− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1325− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1326− | GeoDistanceRangeFilter GeoPoint DistanceRange
1327− | GeoPolygonFilter FieldName [LatLon]
1328− | IdsFilter MappingName [DocId]
1330− | MissingFilter FieldName Existence NullValue
1331− | PrefixFilter FieldName PrefixValue Cache
1332− | QueryFilter Query Cache
1333− | RangeFilter FieldName RangeValue RangeExecution Cache
1334− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1335− | TermFilter Term Cache
1336− deriving (Eq, Read, Show, Generic, Typeable)
1338−data ZeroTermsQuery = ZeroTermsNone
1339− | ZeroTermsAll deriving (Eq, Read, Show, Generic, Typeable)
1341−data RangeExecution = RangeExecutionIndex
1342− | RangeExecutionFielddata deriving (Eq, Read, Show, Generic, Typeable)
1344−newtype Regexp = Regexp Text deriving (Eq, Read, Show, Generic, Typeable, FromJSON)
1346−data RegexpFlags = AllRegexpFlags
1348− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Read, Show, Generic, Typeable)
1350−data RegexpFlag = AnyString
1355− | Interval deriving (Eq, Read, Show, Generic, Typeable)
1357−newtype LessThan = LessThan Double deriving (Eq, Read, Show, Generic, Typeable)
1358−newtype LessThanEq = LessThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1359−newtype GreaterThan = GreaterThan Double deriving (Eq, Read, Show, Generic, Typeable)
1360−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Read, Show, Generic, Typeable)
1362−newtype LessThanD = LessThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1363−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1364−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1365−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Read, Show, Generic, Typeable)
1367−data RangeValue = RangeDateLte LessThanEqD
1368− | RangeDateLt LessThanD
1369− | RangeDateGte GreaterThanEqD
1370− | RangeDateGt GreaterThanD
1371− | RangeDateGtLt GreaterThanD LessThanD
1372− | RangeDateGteLte GreaterThanEqD LessThanEqD
1373− | RangeDateGteLt GreaterThanEqD LessThanD
1374− | RangeDateGtLte GreaterThanD LessThanEqD
1375− | RangeDoubleLte LessThanEq
1376− | RangeDoubleLt LessThan
1377− | RangeDoubleGte GreaterThanEq
1378− | RangeDoubleGt GreaterThan
1379− | RangeDoubleGtLt GreaterThan LessThan
1380− | RangeDoubleGteLte GreaterThanEq LessThanEq
1381− | RangeDoubleGteLt GreaterThanEq LessThan
1382− | RangeDoubleGtLte GreaterThan LessThanEq
1383− deriving (Eq, Read, Show, Generic, Typeable)
1385−rangeValueToPair :: RangeValue -> [Pair]
1386−rangeValueToPair rv = case rv of
1387− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1388− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1389− RangeDateLt (LessThanD t) -> ["lt" .= t]
1390− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1391− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1392− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1393− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1394− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1395− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1396− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1397− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1398− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1399− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1400− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1401− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1402− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1404−data Term = Term { termField :: Text
1405− , termValue :: Text } deriving (Eq, Read, Show, Generic, Typeable)
1407−data BoolMatch = MustMatch Term Cache
1408− | MustNotMatch Term Cache
1409− | ShouldMatch [Term] Cache deriving (Eq, Read, Show, Generic, Typeable)
1411−-- "memory" or "indexed"
1412−data GeoFilterType = GeoFilterMemory
1413− | GeoFilterIndexed deriving (Eq, Read, Show, Generic, Typeable)
1415−data LatLon = LatLon { lat :: Double
1416− , lon :: Double } deriving (Eq, Read, Show, Generic, Typeable)
1418−data GeoBoundingBox =
1419− GeoBoundingBox { topLeft :: LatLon
1420− , bottomRight :: LatLon } deriving (Eq, Read, Show, Generic, Typeable)
1422−data GeoBoundingBoxConstraint =
1423− GeoBoundingBoxConstraint { geoBBField :: FieldName
1424− , constraintBox :: GeoBoundingBox
1425− , bbConstraintcache :: Cache
1426− , geoType :: GeoFilterType
1427− } deriving (Eq, Read, Show, Generic, Typeable)
1430− GeoPoint { geoField :: FieldName
1431− , latLon :: LatLon} deriving (Eq, Read, Show, Generic, Typeable)
1433−data DistanceUnit = Miles
1441− | NauticalMiles deriving (Eq, Read, Show, Generic, Typeable)
1443−data DistanceType = Arc
1444− | SloppyArc -- doesn't exist <1.0
1445− | Plane deriving (Eq, Read, Show, Generic, Typeable)
1447−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1448− | NoOptimizeBbox deriving (Eq, Read, Show, Generic, Typeable)
1451− Distance { coefficient :: Double
1452− , unit :: DistanceUnit } deriving (Eq, Read, Show, Generic, Typeable)
1454−data DistanceRange =
1455− DistanceRange { distanceFrom :: Distance
1456− , distanceTo :: Distance } deriving (Eq, Read, Show, Generic, Typeable)
1458−type TemplateQueryKey = Text
1459−type TemplateQueryValue = Text
1461−newtype TemplateQueryKeyValuePairs = TemplateQueryKeyValuePairs (HM.HashMap TemplateQueryKey TemplateQueryValue)
1462− deriving (Eq, Read, Show, Generic, Typeable)
1464−instance ToJSON TemplateQueryKeyValuePairs where
1465− toJSON (TemplateQueryKeyValuePairs x) = Object $ HM.map toJSON x
1467−instance FromJSON TemplateQueryKeyValuePairs where
1468− parseJSON (Object o) = pure . TemplateQueryKeyValuePairs $ HM.mapMaybe getValue o
1469− where getValue (String x) = Just x
1470− getValue _ = Nothing
1471− parseJSON _ = fail "error parsing TemplateQueryKeyValuePairs"
1473−data TemplateQueryInline =
1474− TemplateQueryInline { inline :: Query
1475− , params :: TemplateQueryKeyValuePairs
1477− deriving (Eq, Read, Show, Generic, Typeable)
1479−instance ToJSON TemplateQueryInline where
1480− toJSON TemplateQueryInline{..} = object [ "query" .= inline
1481− , "params" .= params
1484−instance FromJSON TemplateQueryInline where
1485− parseJSON = withObject "TemplateQueryInline" parse
1486− where parse o = TemplateQueryInline
1490−data SearchResult a =
1491− SearchResult { took :: Int
1493− , shards :: ShardResult
1494− , searchHits :: SearchHits a
1495− , aggregations :: Maybe AggregationResults
1496− , scrollId :: Maybe ScrollId
1497− , suggest :: Maybe NamedSuggestionResponse -- ^ Only one Suggestion request / response per Search is supported.
1499− deriving (Eq, Read, Show, Generic, Typeable)
1501−newtype ScrollId = ScrollId Text deriving (Eq, Read, Show, Generic, Ord, ToJSON, FromJSON)
1503−type Score = Maybe Double
1506− SearchHits { hitsTotal :: Int
1507− , maxScore :: Score
1508− , hits :: [Hit a] } deriving (Eq, Read, Show, Generic, Typeable)
1510−instance Semigroup (SearchHits a) where
1511− (SearchHits ta ma ha) <> (SearchHits tb mb hb) = SearchHits (ta + tb) (max ma mb) (ha <> hb)
1513−instance Monoid (SearchHits a) where
1514− mempty = SearchHits 0 Nothing mempty
1518− Hit { hitIndex :: IndexName
1519− , hitType :: MappingName
1520− , hitDocId :: DocId
1521− , hitScore :: Score
1522− , hitSource :: Maybe a
1523− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Read, Show, Generic, Typeable)
1526− ShardResult { shardTotal :: Int
1527− , shardsSuccessful :: Int
1528− , shardsFailed :: Int } deriving (Eq, Read, Show, Generic, Typeable)
1530−type HitHighlight = M.Map Text [Text]
1532−showText :: Show a => a -> Text
1533−showText = T.pack . show
1535−readMay :: Read a => String -> Maybe a
1536−readMay s = case reads s of
1537− (a, ""):_ -> Just a
1540−parseReadText :: Read a => Text -> Parser a
1541−parseReadText = maybe mzero return . readMay . T.unpack
1544−data TermOrder = TermOrder{ termSortField :: Text
1545− , termSortOrder :: SortOrder } deriving (Eq, Read, Show, Generic, Typeable)
1547−data TermInclusion = TermInclusion Text
1548− | TermPattern Text Text deriving (Eq, Read, Show, Generic, Typeable)
1550−data CollectionMode = BreadthFirst
1551− | DepthFirst deriving (Eq, Read, Show, Generic, Typeable)
1553−data ExecutionHint = Ordinals
1555− | GlobalOrdinalsHash
1556− | GlobalOrdinalsLowCardinality
1557− | Map deriving (Eq, Read, Show, Generic, Typeable)
1559−data TimeInterval = Weeks
1563− | Seconds deriving Eq
1565−data Interval = Year
1573− | FractionalInterval Float TimeInterval deriving (Eq, Read, Show, Generic, Typeable)
1576−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1577−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Read, Show, Generic, Typeable)
1580−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1581−data DateMathAnchor = DMNow
1582− | DMDate Day deriving (Eq, Read, Show, Generic, Typeable)
1584−data DateMathModifier = AddTime Int DateMathUnit
1585− | SubtractTime Int DateMathUnit
1586− | RoundDownTo DateMathUnit deriving (Eq, Read, Show, Generic, Typeable)
1588−data DateMathUnit = DMYear
1594− | DMSecond deriving (Eq, Read, Show, Generic, Typeable)
1596−instance ToJSON Version where
1597− toJSON Version {..} = object ["number" .= number
1598− ,"build_hash" .= build_hash
1599− ,"build_timestamp" .= build_timestamp
1600− ,"build_snapshot" .= build_snapshot
1601− ,"lucene_version" .= lucene_version]
1603−instance FromJSON Version where
1604− parseJSON = withObject "Version" parse
1605− where parse o = Version
1607− <*> o .: "build_hash"
1608− <*> o .: "build_timestamp"
1609− <*> o .: "build_snapshot"
1610− <*> o .: "lucene_version"
1612−instance ToJSON VersionNumber where
1613− toJSON = toJSON . Vers.showVersion . versionNumber
1615−instance FromJSON VersionNumber where
1616− parseJSON = withText "VersionNumber" (parse . T.unpack)
1618− parse s = case filter (null . snd)(RP.readP_to_S Vers.parseVersion s) of
1619− [(v, _)] -> pure (VersionNumber v)
1620− [] -> fail ("Invalid version string " ++ s)
1621− xs -> fail ("Ambiguous version string " ++ s ++ " (" ++ intercalate ", " (Vers.showVersion . fst <$> xs) ++ ")")
1623−instance ToJSON TermOrder where
1624− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1626−instance ToJSON TermInclusion where
1627− toJSON (TermInclusion x) = toJSON x
1628− toJSON (TermPattern pattern flags) =
1629− omitNulls [ "pattern" .= pattern
1630− , "flags" .= flags]
1632−instance ToJSON CollectionMode where
1633− toJSON BreadthFirst = "breadth_first"
1634− toJSON DepthFirst = "depth_first"
1636−instance ToJSON ExecutionHint where
1637− toJSON Ordinals = "ordinals"
1638− toJSON GlobalOrdinals = "global_ordinals"
1639− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1640− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1643−instance ToJSON Interval where
1644− toJSON Year = "year"
1645− toJSON Quarter = "quarter"
1646− toJSON Month = "month"
1647− toJSON Week = "week"
1649− toJSON Hour = "hour"
1650− toJSON Minute = "minute"
1651− toJSON Second = "second"
1652− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1654−instance Show TimeInterval where
1661−instance Read TimeInterval where
1662− readPrec = f =<< TR.get
1664− f 'w' = return Weeks
1665− f 'd' = return Days
1666− f 'h' = return Hours
1667− f 'm' = return Minutes
1668− f 's' = return Seconds
1669− f _ = fail "TimeInterval expected one of w, d, h, m, s"
1672−instance ToJSON DateRangeAggregation where
1673− toJSON DateRangeAggregation {..} =
1674− omitNulls [ "field" .= draField
1675− , "format" .= draFormat
1676− , "ranges" .= toList draRanges
1679−instance ToJSON DateRangeAggRange where
1680− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1681− toJSON (DateRangeTo e) = object [ "to" .= e ]
1682− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1684−instance ToJSON DateMathExpr where
1685− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1686− where fmtA DMNow = "now"
1687− fmtA (DMDate date) = (T.pack $ showGregorian date) <> "||"
1688− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1689− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1690− fmtMod (RoundDownTo u) = "/" <> fmtU u
1696− fmtU DMMinute = "m"
1697− fmtU DMSecond = "s"
1700−type AggregationResults = M.Map Text Value
1702−class BucketAggregation a where
1703− key :: a -> BucketValue
1704− docCount :: a -> Int
1705− aggs :: a -> Maybe AggregationResults
1708−data Bucket a = Bucket { buckets :: [a]} deriving (Read, Show)
1710−data BucketValue = TextValue Text
1711− | ScientificValue Scientific
1712− | BoolValue Bool deriving (Read, Show)
1714−data MissingResult = MissingResult { missingDocCount :: Int } deriving (Show)
1716−data TopHitResult a = TopHitResult { tarHits :: (SearchHits a)
1719−data TermsResult = TermsResult { termKey :: BucketValue
1720− , termsDocCount :: Int
1721− , termsAggs :: Maybe AggregationResults } deriving (Read, Show)
1723−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1724− , dateKeyStr :: Maybe Text
1725− , dateDocCount :: Int
1726− , dateHistogramAggs :: Maybe AggregationResults } deriving (Read, Show)
1728−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1729− , dateRangeFrom :: Maybe UTCTime
1730− , dateRangeFromAsString :: Maybe Text
1731− , dateRangeTo :: Maybe UTCTime
1732− , dateRangeToAsString :: Maybe Text
1733− , dateRangeDocCount :: Int
1734− , dateRangeAggs :: Maybe AggregationResults } deriving (Read, Show, Eq, Generic, Typeable)
1736−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1737−toTerms = toAggResult
1739−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1740−toDateHistogram = toAggResult
1742−toMissing :: Text -> AggregationResults -> Maybe MissingResult
1743−toMissing = toAggResult
1745−toTopHits :: (FromJSON a) => Text -> AggregationResults -> Maybe (TopHitResult a)
1746−toTopHits = toAggResult
1748−toAggResult :: (FromJSON a) => Text -> AggregationResults -> Maybe a
1749−toAggResult t a = M.lookup t a >>= deserialize
1750− where deserialize = parseMaybe parseJSON
1752−instance BucketAggregation TermsResult where
1754− docCount = termsDocCount
1757−instance BucketAggregation DateHistogramResult where
1758− key = TextValue . showText . dateKey
1759− docCount = dateDocCount
1760− aggs = dateHistogramAggs
1762−instance BucketAggregation DateRangeResult where
1763− key = TextValue . dateRangeKey
1764− docCount = dateRangeDocCount
1765− aggs = dateRangeAggs
1767−instance (FromJSON a) => FromJSON (Bucket a) where
1768− parseJSON (Object v) = Bucket <$>
1770− parseJSON _ = mempty
1772−instance FromJSON BucketValue where
1773− parseJSON (String t) = return $ TextValue t
1774− parseJSON (Number s) = return $ ScientificValue s
1775− parseJSON (Bool b) = return $ BoolValue b
1776− parseJSON _ = mempty
1778−instance FromJSON MissingResult where
1779− parseJSON = withObject "MissingResult" parse
1780− where parse v = MissingResult <$> v .: "doc_count"
1782−instance FromJSON TermsResult where
1783− parseJSON (Object v) = TermsResult <$>
1785− v .: "doc_count" <*>
1786− (pure $ getNamedSubAgg v ["key", "doc_count"])
1787− parseJSON _ = mempty
1789−instance FromJSON DateHistogramResult where
1790− parseJSON (Object v) = DateHistogramResult <$>
1792− v .:? "key_as_string" <*>
1793− v .: "doc_count" <*>
1794− (pure $ getNamedSubAgg v [ "key"
1799− parseJSON _ = mempty
1801−instance FromJSON DateRangeResult where
1802− parseJSON = withObject "DateRangeResult" parse
1803− where parse v = DateRangeResult <$>
1805− (fmap posixMS <$> v .:? "from") <*>
1806− v .:? "from_as_string" <*>
1807− (fmap posixMS <$> v .:? "to") <*>
1808− v .:? "to_as_string" <*>
1809− v .: "doc_count" <*>
1810− (pure $ getNamedSubAgg v [ "key"
1819−instance FromJSON POSIXMS where
1820− parseJSON = withScientific "POSIXMS" (return . parse)
1821− where parse n = let n' = truncate n :: Integer
1822− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1824−instance (FromJSON a) => FromJSON (TopHitResult a) where
1825− parseJSON (Object v) = TopHitResult <$>
1827− parseJSON _ = fail "Failure in FromJSON (TopHitResult a)"
1829−instance Semigroup Filter where
1830− a <> b = AndFilter [a, b] defaultCache
1832−instance Monoid Filter where
1833− mempty = IdentityFilter
1836−instance Seminearring Filter where
1837− a <||> b = OrFilter [a, b] defaultCache
1839−instance ToJSON Filter where
1840− toJSON (AndFilter filters cache) =
1842− object [ "filters" .= fmap toJSON filters
1843− , "_cache" .= cache]]
1845− toJSON (OrFilter filters cache) =
1847− object [ "filters" .= fmap toJSON filters
1848− , "_cache" .= cache]]
1850− toJSON (NotFilter notFilter cache) =
1852− object ["filter" .= notFilter
1853− , "_cache" .= cache]]
1855− toJSON (IdentityFilter) =
1856− object ["match_all" .= object []]
1858− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1859− object ["term" .= object base]
1860− where base = [termFilterField .= termFilterValue,
1863− toJSON (ExistsFilter (FieldName fieldName)) =
1864− object ["exists" .= object
1865− ["field" .= fieldName]]
1867− toJSON (BoolFilter boolMatch) =
1868− object ["bool" .= boolMatch]
1870− toJSON (GeoBoundingBoxFilter bbConstraint) =
1871− object ["geo_bounding_box" .= bbConstraint]
1873− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1874− distance distanceType optimizeBbox cache) =
1875− object ["geo_distance" .=
1876− object ["distance" .= distance
1877− , "distance_type" .= distanceType
1878− , "optimize_bbox" .= optimizeBbox
1879− , distanceGeoField .= geoDistLatLon
1880− , "_cache" .= cache]]
1882− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1883− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1884− object ["geo_distance_range" .=
1885− object ["from" .= geoDistRangeDistFrom
1886− , "to" .= drDistanceTo
1887− , gddrField .= drLatLon]]
1889− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1890− object ["geo_polygon" .=
1891− object [geoPolygonFilterField .=
1892− object ["points" .= fmap toJSON latLons]]]
1894− toJSON (IdsFilter (MappingName mappingName) values) =
1896− object ["type" .= mappingName
1897− , "values" .= fmap unpackId values]]
1899− toJSON (LimitFilter limit) =
1900− object ["limit" .= object ["value" .= limit]]
1902− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1903− object ["missing" .=
1904− object [ "field" .= fieldName
1905− , "existence" .= existence
1906− , "null_value" .= nullValue]]
1908− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1909− object ["prefix" .=
1910− object [fieldName .= fieldValue
1911− , "_cache" .= cache]]
1913− toJSON (QueryFilter query False) =
1914− object ["query" .= toJSON query ]
1915− toJSON (QueryFilter query True) =
1916− object ["fquery" .=
1917− object [ "query" .= toJSON query
1918− , "_cache" .= True ]]
1920− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1922− object [ fieldName .= object (rangeValueToPair rangeValue)
1923− , "execution" .= rangeExecution
1924− , "_cache" .= cache]]
1926− toJSON (RegexpFilter (FieldName fieldName)
1927− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1928− object ["regexp" .=
1929− object [fieldName .=
1930− object ["value" .= regexText
1931− , "flags" .= flags]
1932− , "_name" .= cacheName
1933− , "_cache" .= cache
1934− , "_cache_key" .= cacheKey]]
1936−instance FromJSON Filter where
1937− parseJSON = withObject "Filter" parse
1938− where parse o = andFilter `taggedWith` "and"
1939− <|> orFilter `taggedWith` "or"
1940− <|> notFilter `taggedWith` "not"
1941− <|> identityFilter `taggedWith` "match_all"
1942− <|> boolFilter `taggedWith` "bool"
1943− <|> existsFilter `taggedWith` "exists"
1944− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
1945− <|> geoDistanceFilter `taggedWith` "geo_distance"
1946− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
1947− <|> geoPolygonFilter `taggedWith` "geo_polygon"
1948− <|> idsFilter `taggedWith` "ids"
1949− <|> limitFilter `taggedWith` "limit"
1950− <|> missingFilter `taggedWith` "missing"
1951− <|> prefixFilter `taggedWith` "prefix"
1952− <|> queryFilter `taggedWith` "query"
1953− <|> fqueryFilter `taggedWith` "fquery"
1954− <|> rangeFilter `taggedWith` "range"
1955− <|> regexpFilter `taggedWith` "regexp"
1956− <|> termFilter `taggedWith` "term"
1957− where taggedWith parser k = parser =<< o .: k
1958− andFilter o = AndFilter <$> o .: "filters"
1959− <*> o .:? "_cache" .!= defaultCache
1960− orFilter o = OrFilter <$> o .: "filters"
1961− <*> o .:? "_cache" .!= defaultCache
1962− notFilter o = NotFilter <$> o .: "filter"
1963− <*> o .: "_cache" .!= defaultCache
1964− identityFilter :: Object -> Parser Filter
1966− | HM.null m = pure IdentityFilter
1967− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
1968− boolFilter = pure . BoolFilter
1969− existsFilter o = ExistsFilter <$> o .: "field"
1970− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1971− geoDistanceFilter o = do
1972− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
1974− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1975− GeoDistanceFilter gp <$> o .: "distance"
1976− <*> o .: "distance_type"
1977− <*> o .: "optimize_bbox"
1978− <*> o .:? "_cache" .!= defaultCache
1979− _ -> fail "Could not find GeoDistanceFilter field name"
1980− geoDistanceRangeFilter o = do
1981− case HM.toList (deleteSeveral ["from", "to"] o) of
1983− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1984− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1985− return (GeoDistanceRangeFilter gp rng)
1986− _ -> fail "Could not find GeoDistanceRangeFilter field name"
1987− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
1988− idsFilter o = IdsFilter <$> o .: "type"
1990− limitFilter o = LimitFilter <$> o .: "value"
1991− missingFilter o = MissingFilter <$> o .: "field"
1992− <*> o .: "existence"
1993− <*> o .: "null_value"
1994− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
1995− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
1996− _ -> fail "Could not parse PrefixFilter"
1998− queryFilter q = pure (QueryFilter q False)
1999− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2000− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2001− [(fn, v)] -> RangeFilter (FieldName fn)
2003− <*> o .: "execution"
2004− <*> o .:? "_cache" .!= defaultCache
2005− _ -> fail "Could not find field name for RangeFilter"
2006− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2007− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2011− <*> o .:? "_cache" .!= defaultCache
2012− <*> o .: "_cache_key"
2013− _ -> fail "Could not find field name for RegexpFilter"
2014− termFilter o = case HM.toList (HM.delete "_cache" o) of
2015− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2016− <$> o .:? "_cache" .!= defaultCache
2017− _ -> fail "Could not find term field for TermFilter"
2019−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2020−fieldTagged f o = case HM.toList o of
2021− [(k, Object o')] -> f (FieldName k) o'
2022− _ -> fail "Expected object with 1 field-named key"
2024−-- Try to get an AggregationResults when we don't know the
2025−-- field name. We filter out the known keys to try to minimize the noise.
2026−getNamedSubAgg :: Object -> [Text] -> Maybe AggregationResults
2027−getNamedSubAgg o knownKeys = maggRes
2028− where unknownKeys = HM.filterWithKey (\k _ -> k `notElem` knownKeys) o
2030− | HM.null unknownKeys = Nothing
2031− | otherwise = Just . M.fromList $ HM.toList unknownKeys
2033−instance ToJSON GeoPoint where
2034− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2035− object [ geoPointField .= geoPointLatLon ]
2038−instance ToJSON Query where
2039− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2041− object [termQueryField .= object merged]]
2043− base = [ "value" .= termQueryValue ]
2044− boosted = maybe [] (return . ("boost" .=)) boost
2045− merged = mappend base boosted
2047− toJSON (TermsQuery fieldName terms) =
2048− object [ "terms" .= object conjoined ]
2049− where conjoined = [fieldName .= terms]
2051− toJSON (IdsQuery idsQueryMappingName docIds) =
2052− object [ "ids" .= object conjoined ]
2053− where conjoined = [ "type" .= idsQueryMappingName
2054− , "values" .= fmap toJSON docIds ]
2056− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2057− object [ "query_string" .= qQueryStringQuery ]
2059− toJSON (QueryMatchQuery matchQuery) =
2060− object [ "match" .= matchQuery ]
2062− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2063− toJSON multiMatchQuery
2065− toJSON (QueryBoolQuery boolQuery) =
2066− object [ "bool" .= boolQuery ]
2068− toJSON (QueryBoostingQuery boostingQuery) =
2069− object [ "boosting" .= boostingQuery ]
2071− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2072− object [ "common" .= commonTermsQuery ]
2074− toJSON (ConstantScoreFilter csFilter boost) =
2075− object ["constant_score" .= object ["filter" .= csFilter
2076− , "boost" .= boost]]
2078− toJSON (ConstantScoreQuery query boost) =
2079− object ["constant_score" .= object ["query" .= query
2080− , "boost" .= boost]]
2082− toJSON (QueryDisMaxQuery disMaxQuery) =
2083− object [ "dis_max" .= disMaxQuery ]
2085− toJSON (QueryFilteredQuery qFilteredQuery) =
2086− object [ "filtered" .= qFilteredQuery ]
2088− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2089− object [ "fuzzy_like_this" .= fuzzyQuery ]
2091− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2092− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2094− toJSON (QueryFuzzyQuery fuzzyQuery) =
2095− object [ "fuzzy" .= fuzzyQuery ]
2097− toJSON (QueryHasChildQuery childQuery) =
2098− object [ "has_child" .= childQuery ]
2100− toJSON (QueryHasParentQuery parentQuery) =
2101− object [ "has_parent" .= parentQuery ]
2103− toJSON (QueryIndicesQuery qIndicesQuery) =
2104− object [ "indices" .= qIndicesQuery ]
2106− toJSON (MatchAllQuery boost) =
2107− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2109− toJSON (QueryMoreLikeThisQuery query) =
2110− object [ "more_like_this" .= query ]
2112− toJSON (QueryMoreLikeThisFieldQuery query) =
2113− object [ "more_like_this_field" .= query ]
2115− toJSON (QueryNestedQuery query) =
2116− object [ "nested" .= query ]
2118− toJSON (QueryPrefixQuery query) =
2119− object [ "prefix" .= query ]
2121− toJSON (QueryRangeQuery query) =
2122− object [ "range" .= query ]
2124− toJSON (QueryRegexpQuery query) =
2125− object [ "regexp" .= query ]
2127− toJSON (QuerySimpleQueryStringQuery query) =
2128− object [ "simple_query_string" .= query ]
2130− toJSON (QueryTemplateQueryInline templateQuery) =
2131− object [ "template" .= templateQuery ]
2133−instance FromJSON Query where
2134− parseJSON v = withObject "Query" parse v
2135− where parse o = termQuery `taggedWith` "term"
2136− <|> termsQuery `taggedWith` "terms"
2137− <|> idsQuery `taggedWith` "ids"
2138− <|> queryQueryStringQuery `taggedWith` "query_string"
2139− <|> queryMatchQuery `taggedWith` "match"
2140− <|> queryMultiMatchQuery
2141− <|> queryBoolQuery `taggedWith` "bool"
2142− <|> queryBoostingQuery `taggedWith` "boosting"
2143− <|> queryCommonTermsQuery `taggedWith` "common"
2144− <|> constantScoreFilter `taggedWith` "constant_score"
2145− <|> constantScoreQuery `taggedWith` "constant_score"
2146− <|> queryDisMaxQuery `taggedWith` "dis_max"
2147− <|> queryFilteredQuery `taggedWith` "filtered"
2148− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2149− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2150− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2151− <|> queryHasChildQuery `taggedWith` "has_child"
2152− <|> queryHasParentQuery `taggedWith` "has_parent"
2153− <|> queryIndicesQuery `taggedWith` "indices"
2154− <|> matchAllQuery `taggedWith` "match_all"
2155− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2156− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2157− <|> queryNestedQuery `taggedWith` "nested"
2158− <|> queryPrefixQuery `taggedWith` "prefix"
2159− <|> queryRangeQuery `taggedWith` "range"
2160− <|> queryRegexpQuery `taggedWith` "regexp"
2161− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2162− <|> queryTemplateQueryInline `taggedWith` "template"
2163− where taggedWith parser k = parser =<< o .: k
2164− termQuery = fieldTagged $ \(FieldName fn) o ->
2165− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2166− termsQuery o = case HM.toList o of
2167− [(fn, vs)] -> do vals <- parseJSON vs
2169− x:xs -> return (TermsQuery fn (x :| xs))
2170− _ -> fail "Expected non empty list of values"
2171− _ -> fail "Expected object with 1 field-named key"
2172− idsQuery o = IdsQuery <$> o .: "type"
2174− queryQueryStringQuery = pure . QueryQueryStringQuery
2175− queryMatchQuery = pure . QueryMatchQuery
2176− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2177− queryBoolQuery = pure . QueryBoolQuery
2178− queryBoostingQuery = pure . QueryBoostingQuery
2179− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2180− constantScoreFilter o = case HM.lookup "filter" o of
2181− Just x -> ConstantScoreFilter <$> parseJSON x
2183− _ -> fail "Does not appear to be a ConstantScoreFilter"
2184− constantScoreQuery o = case HM.lookup "query" o of
2185− Just x -> ConstantScoreQuery <$> parseJSON x
2187− _ -> fail "Does not appear to be a ConstantScoreQuery"
2188− queryDisMaxQuery = pure . QueryDisMaxQuery
2189− queryFilteredQuery = pure . QueryFilteredQuery
2190− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2191− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2192− queryFuzzyQuery = pure . QueryFuzzyQuery
2193− queryHasChildQuery = pure . QueryHasChildQuery
2194− queryHasParentQuery = pure . QueryHasParentQuery
2195− queryIndicesQuery = pure . QueryIndicesQuery
2196− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2197− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2198− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2199− queryNestedQuery = pure . QueryNestedQuery
2200− queryPrefixQuery = pure . QueryPrefixQuery
2201− queryRangeQuery = pure . QueryRangeQuery
2202− queryRegexpQuery = pure . QueryRegexpQuery
2203− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2204− queryTemplateQueryInline = pure . QueryTemplateQueryInline
2207−omitNulls :: [(Text, Value)] -> Value
2208−omitNulls = object . filter notNull where
2209− notNull (_, Null) = False
2210− notNull (_, Array a) = (not . V.null) a
2214−instance ToJSON SimpleQueryStringQuery where
2215− toJSON SimpleQueryStringQuery {..} =
2216− omitNulls (base ++ maybeAdd)
2217− where base = [ "query" .= simpleQueryStringQuery ]
2218− maybeAdd = [ "fields" .= simpleQueryStringField
2219− , "default_operator" .= simpleQueryStringOperator
2220− , "analyzer" .= simpleQueryStringAnalyzer
2221− , "flags" .= simpleQueryStringFlags
2222− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2223− , "locale" .= simpleQueryStringLocale ]
2225−instance FromJSON SimpleQueryStringQuery where
2226− parseJSON = withObject "SimpleQueryStringQuery" parse
2227− where parse o = SimpleQueryStringQuery <$> o .: "query"
2229− <*> o .:? "default_operator"
2230− <*> o .:? "analyzer"
2231− <*> (parseFlags <$> o .:? "flags")
2232− <*> o .:? "lowercase_expanded_terms"
2234− parseFlags (Just (x:xs)) = Just (x :| xs)
2235− parseFlags _ = Nothing
2237−instance ToJSON FieldOrFields where
2238− toJSON (FofField fieldName) =
2240− toJSON (FofFields fieldNames) =
2243−instance FromJSON FieldOrFields where
2244− parseJSON v = FofField <$> parseJSON v
2245− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2247−instance ToJSON SimpleQueryFlag where
2248− toJSON SimpleQueryAll = "ALL"
2249− toJSON SimpleQueryNone = "NONE"
2250− toJSON SimpleQueryAnd = "AND"
2251− toJSON SimpleQueryOr = "OR"
2252− toJSON SimpleQueryPrefix = "PREFIX"
2253− toJSON SimpleQueryPhrase = "PHRASE"
2254− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2255− toJSON SimpleQueryEscape = "ESCAPE"
2256− toJSON SimpleQueryWhitespace = "WHITESPACE"
2257− toJSON SimpleQueryFuzzy = "FUZZY"
2258− toJSON SimpleQueryNear = "NEAR"
2259− toJSON SimpleQuerySlop = "SLOP"
2261−instance FromJSON SimpleQueryFlag where
2262− parseJSON = withText "SimpleQueryFlag" parse
2263− where parse "ALL" = pure SimpleQueryAll
2264− parse "NONE" = pure SimpleQueryNone
2265− parse "AND" = pure SimpleQueryAnd
2266− parse "OR" = pure SimpleQueryOr
2267− parse "PREFIX" = pure SimpleQueryPrefix
2268− parse "PHRASE" = pure SimpleQueryPhrase
2269− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2270− parse "ESCAPE" = pure SimpleQueryEscape
2271− parse "WHITESPACE" = pure SimpleQueryWhitespace
2272− parse "FUZZY" = pure SimpleQueryFuzzy
2273− parse "NEAR" = pure SimpleQueryNear
2274− parse "SLOP" = pure SimpleQuerySlop
2275− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2277−instance ToJSON RegexpQuery where
2278− toJSON (RegexpQuery (FieldName rqQueryField)
2279− (Regexp regexpQueryQuery) rqQueryFlags
2281− object [ rqQueryField .= omitNulls base ]
2282− where base = [ "value" .= regexpQueryQuery
2283− , "flags" .= rqQueryFlags
2284− , "boost" .= rqQueryBoost ]
2286−instance FromJSON RegexpQuery where
2287− parseJSON = withObject "RegexpQuery" parse
2288− where parse = fieldTagged $ \fn o ->
2294−instance ToJSON QueryStringQuery where
2295− toJSON (QueryStringQuery qsQueryString
2296− qsDefaultField qsOperator
2297− qsAnalyzer qsAllowWildcard
2298− qsLowercaseExpanded qsEnablePositionIncrements
2299− qsFuzzyMaxExpansions qsFuzziness
2300− qsFuzzyPrefixLength qsPhraseSlop
2301− qsBoost qsAnalyzeWildcard
2302− qsGeneratePhraseQueries qsMinimumShouldMatch
2303− qsLenient qsLocale) =
2306− base = [ "query" .= qsQueryString
2307− , "default_field" .= qsDefaultField
2308− , "default_operator" .= qsOperator
2309− , "analyzer" .= qsAnalyzer
2310− , "allow_leading_wildcard" .= qsAllowWildcard
2311− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2312− , "enable_position_increments" .= qsEnablePositionIncrements
2313− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2314− , "fuzziness" .= qsFuzziness
2315− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2316− , "phrase_slop" .= qsPhraseSlop
2317− , "boost" .= qsBoost
2318− , "analyze_wildcard" .= qsAnalyzeWildcard
2319− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2320− , "minimum_should_match" .= qsMinimumShouldMatch
2321− , "lenient" .= qsLenient
2322− , "locale" .= qsLocale ]
2324−instance FromJSON QueryStringQuery where
2325− parseJSON = withObject "QueryStringQuery" parse
2326− where parse o = QueryStringQuery
2328− <*> o .:? "default_field"
2329− <*> o .:? "default_operator"
2330− <*> o .:? "analyzer"
2331− <*> o .:? "allow_leading_wildcard"
2332− <*> o .:? "lowercase_expanded_terms"
2333− <*> o .:? "enable_position_increments"
2334− <*> o .:? "fuzzy_max_expansions"
2335− <*> o .:? "fuzziness"
2336− <*> o .:? "fuzzy_prefix_length"
2337− <*> o .:? "phrase_slop"
2339− <*> o .:? "analyze_wildcard"
2340− <*> o .:? "auto_generate_phrase_queries"
2341− <*> o .:? "minimum_should_match"
2342− <*> o .:? "lenient"
2345−instance ToJSON RangeQuery where
2346− toJSON (RangeQuery (FieldName fieldName) range boost) =
2347− object [ fieldName .= object conjoined ]
2348− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2350−instance FromJSON RangeQuery where
2351− parseJSON = withObject "RangeQuery" parse
2352− where parse = fieldTagged $ \fn o ->
2354− <$> parseJSON (Object o)
2357−instance FromJSON RangeValue where
2358− parseJSON = withObject "RangeValue" parse
2359− where parse o = parseDate o
2361− parseDate o = do lt <- o .:? "lt"
2365− case (lt, lte, gt, gte) of
2366− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2367− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2368− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2369− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2370− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2371− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2372− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2373− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2374− (Nothing, Nothing, Nothing, Nothing) -> mzero
2375− parseDouble o = do lt <- o .:? "lt"
2379− case (lt, lte, gt, gte) of
2380− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2381− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2382− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2383− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2384− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2385− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2386− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2387− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2388− (Nothing, Nothing, Nothing, Nothing) -> mzero
2390−instance ToJSON PrefixQuery where
2391− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2392− object [ fieldName .= omitNulls base ]
2393− where base = [ "value" .= queryValue
2394− , "boost" .= boost ]
2396−instance FromJSON PrefixQuery where
2397− parseJSON = withObject "PrefixQuery" parse
2398− where parse = fieldTagged $ \fn o ->
2403−instance ToJSON NestedQuery where
2404− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2405− object [ "path" .= nqPath
2406− , "score_mode" .= nqScoreType
2407− , "query" .= nqQuery ]
2409−instance FromJSON NestedQuery where
2410− parseJSON = withObject "NestedQuery" parse
2411− where parse o = NestedQuery
2413− <*> o .: "score_mode"
2416−instance ToJSON MoreLikeThisFieldQuery where
2417− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2418− percent mtf mqt stopwords mindf maxdf
2419− minwl maxwl boostTerms boost analyzer) =
2420− object [ fieldName .= omitNulls base ]
2421− where base = [ "like_text" .= text
2422− , "percent_terms_to_match" .= percent
2423− , "min_term_freq" .= mtf
2424− , "max_query_terms" .= mqt
2425− , "stop_words" .= stopwords
2426− , "min_doc_freq" .= mindf
2427− , "max_doc_freq" .= maxdf
2428− , "min_word_length" .= minwl
2429− , "max_word_length" .= maxwl
2430− , "boost_terms" .= boostTerms
2432− , "analyzer" .= analyzer ]
2434−instance FromJSON MoreLikeThisFieldQuery where
2435− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2436− where parse = fieldTagged $ \fn o ->
2437− MoreLikeThisFieldQuery
2438− <$> o .: "like_text"
2440− <*> o .:? "percent_terms_to_match"
2441− <*> o .:? "min_term_freq"
2442− <*> o .:? "max_query_terms"
2443− -- <*> (optionalNE =<< o .:? "stop_words")
2444− <*> o .:? "stop_words"
2445− <*> o .:? "min_doc_freq"
2446− <*> o .:? "max_doc_freq"
2447− <*> o .:? "min_word_length"
2448− <*> o .:? "max_word_length"
2449− <*> o .:? "boost_terms"
2451− <*> o .:? "analyzer"
2452− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2454−instance ToJSON MoreLikeThisQuery where
2455− toJSON (MoreLikeThisQuery text fields percent
2456− mtf mqt stopwords mindf maxdf
2457− minwl maxwl boostTerms boost analyzer) =
2459− where base = [ "like_text" .= text
2460− , "fields" .= fields
2461− , "percent_terms_to_match" .= percent
2462− , "min_term_freq" .= mtf
2463− , "max_query_terms" .= mqt
2464− , "stop_words" .= stopwords
2465− , "min_doc_freq" .= mindf
2466− , "max_doc_freq" .= maxdf
2467− , "min_word_length" .= minwl
2468− , "max_word_length" .= maxwl
2469− , "boost_terms" .= boostTerms
2471− , "analyzer" .= analyzer ]
2473−instance FromJSON MoreLikeThisQuery where
2474− parseJSON = withObject "MoreLikeThisQuery" parse
2475− where parse o = MoreLikeThisQuery
2476− <$> o .: "like_text"
2477− -- <*> (optionalNE =<< o .:? "fields")
2479− <*> o .:? "percent_terms_to_match"
2480− <*> o .:? "min_term_freq"
2481− <*> o .:? "max_query_terms"
2482− -- <*> (optionalNE =<< o .:? "stop_words")
2483− <*> o .:? "stop_words"
2484− <*> o .:? "min_doc_freq"
2485− <*> o .:? "max_doc_freq"
2486− <*> o .:? "min_word_length"
2487− <*> o .:? "max_word_length"
2488− <*> o .:? "boost_terms"
2490− <*> o .:? "analyzer"
2491− -- optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2493−instance ToJSON IndicesQuery where
2494− toJSON (IndicesQuery indices query noMatch) =
2495− omitNulls [ "indices" .= indices
2496− , "no_match_query" .= noMatch
2497− , "query" .= query ]
2499−instance FromJSON IndicesQuery where
2500− parseJSON = withObject "IndicesQuery" parse
2501− where parse o = IndicesQuery
2502− <$> o .:? "indices" .!= []
2504− <*> o .:? "no_match_query"
2506−instance ToJSON HasParentQuery where
2507− toJSON (HasParentQuery queryType query scoreType) =
2508− omitNulls [ "parent_type" .= queryType
2509− , "score_type" .= scoreType
2510− , "query" .= query ]
2512−instance FromJSON HasParentQuery where
2513− parseJSON = withObject "HasParentQuery" parse
2514− where parse o = HasParentQuery
2515− <$> o .: "parent_type"
2517− <*> o .:? "score_type"
2519−instance ToJSON HasChildQuery where
2520− toJSON (HasChildQuery queryType query scoreType) =
2521− omitNulls [ "query" .= query
2522− , "score_type" .= scoreType
2523− , "type" .= queryType ]
2525−instance FromJSON HasChildQuery where
2526− parseJSON = withObject "HasChildQuery" parse
2527− where parse o = HasChildQuery
2530− <*> o .:? "score_type"
2532−instance ToJSON FuzzyQuery where
2533− toJSON (FuzzyQuery (FieldName fieldName) queryText
2534− prefixLength maxEx fuzziness boost) =
2535− object [ fieldName .= omitNulls base ]
2536− where base = [ "value" .= queryText
2537− , "fuzziness" .= fuzziness
2538− , "prefix_length" .= prefixLength
2540− , "max_expansions" .= maxEx ]
2542−instance FromJSON FuzzyQuery where
2543− parseJSON = withObject "FuzzyQuery" parse
2544− where parse = fieldTagged $ \fn o ->
2547− <*> o .: "prefix_length"
2548− <*> o .: "max_expansions"
2549− <*> o .: "fuzziness"
2552−instance ToJSON FuzzyLikeFieldQuery where
2553− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2554− fieldText maxTerms ignoreFreq fuzziness prefixLength
2556− object [ fieldName .=
2557− omitNulls [ "like_text" .= fieldText
2558− , "max_query_terms" .= maxTerms
2559− , "ignore_tf" .= ignoreFreq
2560− , "fuzziness" .= fuzziness
2561− , "prefix_length" .= prefixLength
2562− , "analyzer" .= analyzer
2563− , "boost" .= boost ]]
2565−instance FromJSON FuzzyLikeFieldQuery where
2566− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2567− where parse = fieldTagged $ \fn o ->
2568− FuzzyLikeFieldQuery fn
2569− <$> o .: "like_text"
2570− <*> o .: "max_query_terms"
2571− <*> o .: "ignore_tf"
2572− <*> o .: "fuzziness"
2573− <*> o .: "prefix_length"
2575− <*> o .:? "analyzer"
2577−instance ToJSON FuzzyLikeThisQuery where
2578− toJSON (FuzzyLikeThisQuery fields text maxTerms
2579− ignoreFreq fuzziness prefixLength boost analyzer) =
2581− where base = [ "fields" .= fields
2582− , "like_text" .= text
2583− , "max_query_terms" .= maxTerms
2584− , "ignore_tf" .= ignoreFreq
2585− , "fuzziness" .= fuzziness
2586− , "prefix_length" .= prefixLength
2587− , "analyzer" .= analyzer
2588− , "boost" .= boost ]
2590−instance FromJSON FuzzyLikeThisQuery where
2591− parseJSON = withObject "FuzzyLikeThisQuery" parse
2592− where parse o = FuzzyLikeThisQuery
2593− <$> o .:? "fields" .!= []
2594− <*> o .: "like_text"
2595− <*> o .: "max_query_terms"
2596− <*> o .: "ignore_tf"
2597− <*> o .: "fuzziness"
2598− <*> o .: "prefix_length"
2600− <*> o .:? "analyzer"
2602−instance ToJSON FilteredQuery where
2603− toJSON (FilteredQuery query fFilter) =
2604− object [ "query" .= query
2605− , "filter" .= fFilter ]
2607−instance FromJSON FilteredQuery where
2608− parseJSON = withObject "FilteredQuery" parse
2609− where parse o = FilteredQuery
2613−instance ToJSON DisMaxQuery where
2614− toJSON (DisMaxQuery queries tiebreaker boost) =
2616− where base = [ "queries" .= queries
2618− , "tie_breaker" .= tiebreaker ]
2620−instance FromJSON DisMaxQuery where
2621− parseJSON = withObject "DisMaxQuery" parse
2622− where parse o = DisMaxQuery
2623− <$> o .:? "queries" .!= []
2624− <*> o .: "tie_breaker"
2627−instance ToJSON CommonTermsQuery where
2628− toJSON (CommonTermsQuery (FieldName fieldName)
2629− (QueryString query) cf lfo hfo msm
2630− boost analyzer disableCoord) =
2631− object [fieldName .= omitNulls base ]
2632− where base = [ "query" .= query
2633− , "cutoff_frequency" .= cf
2634− , "low_freq_operator" .= lfo
2635− , "minimum_should_match" .= msm
2637− , "analyzer" .= analyzer
2638− , "disable_coord" .= disableCoord
2639− , "high_freq_operator" .= hfo ]
2641−instance FromJSON CommonTermsQuery where
2642− parseJSON = withObject "CommonTermsQuery" parse
2643− where parse = fieldTagged $ \fn o ->
2644− CommonTermsQuery fn
2646− <*> o .: "cutoff_frequency"
2647− <*> o .: "low_freq_operator"
2648− <*> o .: "high_freq_operator"
2649− <*> o .:? "minimum_should_match"
2651− <*> o .:? "analyzer"
2652− <*> o .:? "disable_coord"
2654−instance ToJSON CommonMinimumMatch where
2655− toJSON (CommonMinimumMatch mm) = toJSON mm
2656− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2657− object [ "low_freq" .= lowF
2658− , "high_freq" .= highF ]
2660−instance FromJSON CommonMinimumMatch where
2661− parseJSON v = parseMinimum v
2662− <|> parseMinimumHighLow v
2663− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2664− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2665− MinimumMatchHighLow
2666− <$> o .: "low_freq"
2667− <*> o .: "high_freq")
2670−instance ToJSON BoostingQuery where
2671− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2672− object [ "positive" .= bqPositiveQuery
2673− , "negative" .= bqNegativeQuery
2674− , "negative_boost" .= bqNegativeBoost ]
2676−instance FromJSON BoostingQuery where
2677− parseJSON = withObject "BoostingQuery" parse
2678− where parse o = BoostingQuery
2679− <$> o .: "positive"
2680− <*> o .: "negative"
2681− <*> o .: "negative_boost"
2683−instance ToJSON BoolQuery where
2684− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2686− where base = [ "must" .= mustM
2687− , "must_not" .= notM
2688− , "should" .= shouldM
2689− , "minimum_should_match" .= bqMin
2691− , "disable_coord" .= disableCoord ]
2693−instance FromJSON BoolQuery where
2694− parseJSON = withObject "BoolQuery" parse
2695− where parse o = BoolQuery
2696− <$> o .:? "must" .!= []
2697− <*> o .:? "must_not" .!= []
2698− <*> o .:? "should" .!= []
2699− <*> o .:? "minimum_should_match"
2701− <*> o .:? "disable_coord"
2703−instance ToJSON MatchQuery where
2704− toJSON (MatchQuery (FieldName fieldName)
2705− (QueryString mqQueryString) booleanOperator
2706− zeroTermsQuery cutoffFrequency matchQueryType
2707− analyzer maxExpansions lenient boost) =
2708− object [ fieldName .= omitNulls base ]
2709− where base = [ "query" .= mqQueryString
2710− , "operator" .= booleanOperator
2711− , "zero_terms_query" .= zeroTermsQuery
2712− , "cutoff_frequency" .= cutoffFrequency
2713− , "type" .= matchQueryType
2714− , "analyzer" .= analyzer
2715− , "max_expansions" .= maxExpansions
2716− , "lenient" .= lenient
2717− , "boost" .= boost ]
2719−instance FromJSON MatchQuery where
2720− parseJSON = withObject "MatchQuery" parse
2721− where parse = fieldTagged $ \fn o ->
2724− <*> o .: "operator"
2725− <*> o .: "zero_terms_query"
2726− <*> o .:? "cutoff_frequency"
2728− <*> o .:? "analyzer"
2729− <*> o .:? "max_expansions"
2730− <*> o .:? "lenient"
2733−instance ToJSON MultiMatchQuery where
2734− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2735− ztQ tb mmqt cf analyzer maxEx lenient) =
2736− object ["multi_match" .= omitNulls base]
2737− where base = [ "fields" .= fmap toJSON fields
2739− , "operator" .= boolOp
2740− , "zero_terms_query" .= ztQ
2741− , "tie_breaker" .= tb
2743− , "cutoff_frequency" .= cf
2744− , "analyzer" .= analyzer
2745− , "max_expansions" .= maxEx
2746− , "lenient" .= lenient ]
2748−instance FromJSON MultiMatchQuery where
2749− parseJSON = withObject "MultiMatchQuery" parse
2750− where parse raw = do o <- raw .: "multi_match"
2752− <$> o .:? "fields" .!= []
2754− <*> o .: "operator"
2755− <*> o .: "zero_terms_query"
2756− <*> o .:? "tie_breaker"
2758− <*> o .:? "cutoff_frequency"
2759− <*> o .:? "analyzer"
2760− <*> o .:? "max_expansions"
2761− <*> o .:? "lenient"
2763−instance ToJSON MultiMatchQueryType where
2764− toJSON MultiMatchBestFields = "best_fields"
2765− toJSON MultiMatchMostFields = "most_fields"
2766− toJSON MultiMatchCrossFields = "cross_fields"
2767− toJSON MultiMatchPhrase = "phrase"
2768− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2770−instance FromJSON MultiMatchQueryType where
2771− parseJSON = withText "MultiMatchPhrasePrefix" parse
2772− where parse "best_fields" = pure MultiMatchBestFields
2773− parse "most_fields" = pure MultiMatchMostFields
2774− parse "cross_fields" = pure MultiMatchCrossFields
2775− parse "phrase" = pure MultiMatchPhrase
2776− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2777− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2779−instance ToJSON BooleanOperator where
2780− toJSON And = String "and"
2781− toJSON Or = String "or"
2783−instance FromJSON BooleanOperator where
2784− parseJSON = withText "BooleanOperator" parse
2785− where parse "and" = pure And
2786− parse "or" = pure Or
2787− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2789−instance ToJSON ZeroTermsQuery where
2790− toJSON ZeroTermsNone = String "none"
2791− toJSON ZeroTermsAll = String "all"
2793−instance FromJSON ZeroTermsQuery where
2794− parseJSON = withText "ZeroTermsQuery" parse
2795− where parse "none" = pure ZeroTermsNone
2796− parse "all" = pure ZeroTermsAll
2797− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2799−instance ToJSON MatchQueryType where
2800− toJSON MatchPhrase = "phrase"
2801− toJSON MatchPhrasePrefix = "phrase_prefix"
2803−instance FromJSON MatchQueryType where
2804− parseJSON = withText "MatchQueryType" parse
2805− where parse "phrase" = pure MatchPhrase
2806− parse "phrase_prefix" = pure MatchPhrasePrefix
2807− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2809−instance FromJSON Status where
2810− parseJSON (Object v) = Status <$>
2812− (v .:? "status" .!= 200) <*>
2816− parseJSON _ = empty
2819−instance ToJSON IndexSettings where
2820− toJSON (IndexSettings s r) = object ["settings" .=
2822− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2826−instance FromJSON IndexSettings where
2827− parseJSON = withObject "IndexSettings" parse
2828− where parse o = do s <- o .: "settings"
2830− IndexSettings <$> i .: "number_of_shards"
2831− <*> i .: "number_of_replicas"
2833−instance ToJSON UpdatableIndexSetting where
2834− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2835− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2836− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2837− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2838− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2839− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2840− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2841− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2842− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2843− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2844− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2845− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2846− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2847− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2848− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2849− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2850− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2851− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2852− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2853− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2854− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2855− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2856− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2857− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2858− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2859− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2860− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2861− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2863−instance FromJSON UpdatableIndexSetting where
2864− parseJSON = withObject "UpdatableIndexSetting" parse
2865− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2866− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2867− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2868− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2869− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2870− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2871− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2872− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2873− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2874− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2875− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2876− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2877− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2878− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2879− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2880− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2881− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2882− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2883− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2884− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2885− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2886− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2887− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2888− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2889− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2890− <|> blocksRead `taggedAt` ["blocks", "read"]
2891− <|> blocksWrite `taggedAt` ["blocks", "write"]
2892− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2893− where taggedAt f ks = taggedAt' f (Object o) ks
2894− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON (unStringlyTypeJSON v)))
2895− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
2896− taggedAt' f v' ks) v
2897− numberOfReplicas = pure . NumberOfReplicas
2898− autoExpandReplicas = pure . AutoExpandReplicas
2899− refreshInterval = pure . RefreshInterval . ndtJSON
2900− indexConcurrency = pure . IndexConcurrency
2901− failOnMergeFailure = pure . FailOnMergeFailure
2902− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
2903− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
2904− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
2905− translogDisableFlush = pure . TranslogDisableFlush
2906− cacheFilterMaxSize = pure . CacheFilterMaxSize
2907− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
2908− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
2909− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
2910− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
2911− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
2912− routingAllocationEnable = pure . RoutingAllocationEnable
2913− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
2914− recoveryInitialShards = pure . RecoveryInitialShards
2915− gcDeletes = pure . GCDeletes . ndtJSON
2916− ttlDisablePurge = pure . TTLDisablePurge
2917− translogFSType = pure . TranslogFSType
2918− compoundFormat = pure . IndexCompoundFormat
2919− compoundOnFlush = pure . IndexCompoundOnFlush
2920− warmerEnabled = pure . WarmerEnabled
2921− blocksReadOnly = pure . BlocksReadOnly
2922− blocksRead = pure . BlocksRead
2923− blocksWrite = pure . BlocksWrite
2924− blocksMetaData = pure . BlocksMetaData
2926−instance FromJSON IndexSettingsSummary where
2927− parseJSON = withObject "IndexSettingsSummary" parse
2928− where parse o = case HM.toList o of
2929− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
2931− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
2932− _ -> fail "Expected single-key object with index name"
2933− redundant (NumberOfReplicas _) = True
2934− redundant _ = False
2936−-- | For some reason in several settings APIs, all leaf values get returned
2937−-- as strings. This function attepmts to recover from this for all
2938−-- non-recursive JSON types. If nothing can be done, the value is left alone.
2939−unStringlyTypeJSON :: Value -> Value
2940−unStringlyTypeJSON (String "true") = Bool True
2941−unStringlyTypeJSON (String "false") = Bool False
2942−unStringlyTypeJSON (String "null") = Null
2943−unStringlyTypeJSON v@(String t) = case readMay (T.unpack t) of
2946−unStringlyTypeJSON v = v
2949−parseSettings :: Object -> Parser [UpdatableIndexSetting]
2950−parseSettings o = do
2952− -- slice the index object into singleton hashmaps and try to parse each
2953− parses <- forM (HM.toList o') $ \(k, v) -> do
2954− -- blocks are now nested into the "index" key, which is not how they're serialized
2955− let atRoot = Object (HM.singleton k v)
2956− let atIndex = Object (HM.singleton "index" atRoot)
2957− optional (parseJSON atRoot <|> parseJSON atIndex)
2958− return (catMaybes parses)
2960−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2961−oPath (k :| []) v = object [k .= v]
2962−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2964−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2965−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2966− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2968−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
2969−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
2970− where parse o = case HM.toList o of
2971− [] -> fail "Expected non-empty list of NodeAttrFilters"
2972− x:xs -> DT.mapM (uncurry parse') (x :| xs)
2973− parse' n = withText "Text" $ \t ->
2974− case T.splitOn "," t of
2975− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
2976− [] -> fail "Expected non-empty list of filter values"
2978−instance ToJSON ReplicaBounds where
2979− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2980− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2981− toJSON ReplicasUnbounded = Bool False
2983−instance FromJSON ReplicaBounds where
2984− parseJSON v = withText "ReplicaBounds" parseText v
2985− <|> withBool "ReplicaBounds" parseBool v
2986− where parseText t = case T.splitOn "-" t of
2987− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
2988− [a, b] -> ReplicasBounded <$> parseReadText a
2989− <*> parseReadText b
2990− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
2991− parseBool False = pure ReplicasUnbounded
2992− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
2994−instance ToJSON AllocationPolicy where
2995− toJSON AllocAll = String "all"
2996− toJSON AllocPrimaries = String "primaries"
2997− toJSON AllocNewPrimaries = String "new_primaries"
2998− toJSON AllocNone = String "none"
3000−instance FromJSON AllocationPolicy where
3001− parseJSON = withText "AllocationPolicy" parse
3002− where parse "all" = pure AllocAll
3003− parse "primaries" = pure AllocPrimaries
3004− parse "new_primaries" = pure AllocNewPrimaries
3005− parse "none" = pure AllocNone
3006− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
3008−instance ToJSON InitialShardCount where
3009− toJSON QuorumShards = String "quorum"
3010− toJSON QuorumMinus1Shards = String "quorum-1"
3011− toJSON FullShards = String "full"
3012− toJSON FullMinus1Shards = String "full-1"
3013− toJSON (ExplicitShards x) = toJSON x
3015−instance FromJSON InitialShardCount where
3016− parseJSON v = withText "InitialShardCount" parseText v
3017− <|> ExplicitShards <$> parseJSON v
3018− where parseText "quorum" = pure QuorumShards
3019− parseText "quorum-1" = pure QuorumMinus1Shards
3020− parseText "full" = pure FullShards
3021− parseText "full-1" = pure FullMinus1Shards
3022− parseText _ = mzero
3024−instance ToJSON FSType where
3025− toJSON FSSimple = "simple"
3026− toJSON FSBuffered = "buffered"
3028−instance FromJSON FSType where
3029− parseJSON = withText "FSType" parse
3030− where parse "simple" = pure FSSimple
3031− parse "buffered" = pure FSBuffered
3032− parse t = fail ("Invalid FSType: " <> show t)
3034−instance ToJSON CompoundFormat where
3035− toJSON (CompoundFileFormat x) = Bool x
3036− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3038−instance FromJSON CompoundFormat where
3039− parseJSON v = CompoundFileFormat <$> parseJSON v
3040− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3042−instance ToJSON NominalDiffTimeJSON where
3043− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3045−instance FromJSON NominalDiffTimeJSON where
3046− parseJSON = withText "NominalDiffTime" parse
3047− where parse t = case T.takeEnd 1 t of
3048− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3049− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3051−instance ToJSON IndexTemplate where
3052− toJSON (IndexTemplate p s m) = merge
3053− (object [ "template" .= p
3054− , "mappings" .= foldl' merge (object []) m
3058− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3060− merge _ _ = undefined
3062−instance (FromJSON a) => FromJSON (EsResult a) where
3063− parseJSON jsonVal@(Object v) = do
3064− found <- v .:? "found" .!= False
3066− then parseJSON jsonVal
3067− else return Nothing
3068− EsResult <$> v .: "_index" <*>
3072− parseJSON _ = empty
3074−instance (FromJSON a) => FromJSON (EsResultFound a) where
3075− parseJSON (Object v) = EsResultFound <$>
3076− v .: "_version" <*>
3078− parseJSON _ = empty
3080−instance FromJSON EsError where
3081− parseJSON (Object v) = EsError <$>
3083− (v .: "error" <|> (v .: "error" >>= (.: "reason")))
3084− parseJSON _ = empty
3086−instance FromJSON IndexAliasesSummary where
3087− parseJSON = withObject "IndexAliasesSummary" parse
3088− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3089− go ixn = withObject "index aliases" $ \ia -> do
3090− aliases <- ia .:? "aliases" .!= mempty
3091− forM (HM.toList aliases) $ \(aName, v) -> do
3092− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3093− IndexAliasSummary indexAlias <$> parseJSON v
3096−instance ToJSON IndexAliasAction where
3097− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3098− where Object iaObj = toJSON ia
3099− Object optsObj = toJSON opts
3100− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3101− where Object iaObj = toJSON ia
3103−instance ToJSON IndexAlias where
3104− toJSON IndexAlias {..} = object ["index" .= srcIndex
3105− , "alias" .= indexAlias
3108−instance ToJSON IndexAliasCreate where
3109− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3110− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3111− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3113−instance ToJSON AliasRouting where
3114− toJSON (AllAliasRouting v) = object ["routing" .= v]
3115− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3116− where prs = [("search_routing" .=) <$> srch
3117− ,("index_routing" .=) <$> idx]
3119−instance FromJSON AliasRouting where
3120− parseJSON = withObject "AliasRouting" parse
3121− where parse o = parseAll o <|> parseGranular o
3122− parseAll o = AllAliasRouting <$> o .: "routing"
3123− parseGranular o = do
3124− sr <- o .:? "search_routing"
3125− ir <- o .:? "index_routing"
3126− if isNothing sr && isNothing ir
3127− then fail "Both search_routing and index_routing can't be blank"
3128− else return (GranularAliasRouting sr ir)
3130−instance FromJSON IndexAliasCreate where
3131− parseJSON v = withObject "IndexAliasCreate" parse v
3132− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3135−instance ToJSON SearchAliasRouting where
3136− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3138−instance FromJSON SearchAliasRouting where
3139− parseJSON = withText "SearchAliasRouting" parse
3140− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3142−instance ToJSON Search where
3143− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource sSuggest) =
3144− omitNulls [ "query" .= query
3145− , "filter" .= sFilter
3147− , "aggregations" .= searchAggs
3148− , "highlight" .= highlight
3151− , "track_scores" .= sTrackSortScores
3152− , "fields" .= sFields
3153− , "_source" .= sSource
3154− , "suggest" .= sSuggest]
3157−instance ToJSON Source where
3158− toJSON NoSource = toJSON False
3159− toJSON (SourcePatterns patterns) = toJSON patterns
3160− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3162−instance ToJSON PatternOrPatterns where
3163− toJSON (PopPattern pattern) = toJSON pattern
3164− toJSON (PopPatterns patterns) = toJSON patterns
3166−instance ToJSON Include where
3167− toJSON (Include patterns) = toJSON patterns
3169−instance ToJSON Exclude where
3170− toJSON (Exclude patterns) = toJSON patterns
3172−instance ToJSON Pattern where
3173− toJSON (Pattern pattern) = toJSON pattern
3176−instance ToJSON FieldHighlight where
3177− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3178− object [ fName .= fSettings ]
3179− toJSON (FieldHighlight (FieldName fName) Nothing) =
3180− object [ fName .= emptyObject ]
3182−instance ToJSON Highlights where
3183− toJSON (Highlights global fields) =
3184− omitNulls (("fields" .= fields)
3185− : highlightSettingsPairs global)
3187−instance ToJSON HighlightSettings where
3188− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3190−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3191−highlightSettingsPairs Nothing = []
3192−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3193−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3194−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3197−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3198−plainHighPairs Nothing = []
3199−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3200− [ "type" .= String "plain"]
3201− ++ commonHighlightPairs plCom
3202− ++ nonPostingsToPairs plNonPost
3204−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3205−postHighPairs Nothing = []
3206−postHighPairs (Just (PostingsHighlight pCom)) =
3207− ("type" .= String "postings")
3208− : commonHighlightPairs pCom
3210−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3211−fastVectorHighPairs Nothing = []
3212−fastVectorHighPairs (Just
3213− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3214− fvBoundMaxScan fvFragOff fvMatchedFields
3216− [ "type" .= String "fvh"
3217− , "boundary_chars" .= fvBoundChars
3218− , "boundary_max_scan" .= fvBoundMaxScan
3219− , "fragment_offset" .= fvFragOff
3220− , "matched_fields" .= fvMatchedFields
3221− , "phraseLimit" .= fvPhraseLim]
3222− ++ commonHighlightPairs fvCom
3223− ++ nonPostingsToPairs fvNonPostSettings
3225−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3226−deleteSeveral ks hm = foldr HM.delete hm ks
3228−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3229−commonHighlightPairs Nothing = []
3230−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3231− chNoMatchSize chHighlightQuery
3232− chRequireFieldMatch)) =
3233− [ "order" .= chScore
3234− , "force_source" .= chForceSource
3235− , "encoder" .= chEncoder
3236− , "no_match_size" .= chNoMatchSize
3237− , "highlight_query" .= chHighlightQuery
3238− , "require_fieldMatch" .= chRequireFieldMatch]
3239− ++ highlightTagToPairs chTag
3242−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3243−nonPostingsToPairs Nothing = []
3244−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3245− [ "fragment_size" .= npFragSize
3246− , "number_of_fragments" .= npNumOfFrags]
3248−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3249−parseNEJSON [] = fail "Expected non-empty list"
3250−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3253−instance ToJSON HighlightEncoder where
3254− toJSON DefaultEncoder = String "default"
3255− toJSON HTMLEncoder = String "html"
3257−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3258−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3259−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3260− , "post_tags" .= post]
3261−highlightTagToPairs Nothing = []
3263−instance ToJSON SortSpec where
3264− toJSON (DefaultSortSpec
3265− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3266− dsSortMode dsMissingSort dsNestedFilter)) =
3267− object [dsSortFieldName .= omitNulls base] where
3268− base = [ "order" .= dsSortOrder
3269− , "ignore_unmapped" .= dsIgnoreUnmapped
3270− , "mode" .= dsSortMode
3271− , "missing" .= dsMissingSort
3272− , "nested_filter" .= dsNestedFilter ]
3274− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3275− object [ "unit" .= units
3276− , field .= gdsLatLon
3277− , "order" .= gdsSortOrder ]
3280−instance ToJSON SortOrder where
3281− toJSON Ascending = String "asc"
3282− toJSON Descending = String "desc"
3285−instance ToJSON SortMode where
3286− toJSON SortMin = String "min"
3287− toJSON SortMax = String "max"
3288− toJSON SortSum = String "sum"
3289− toJSON SortAvg = String "avg"
3292−instance ToJSON Missing where
3293− toJSON LastMissing = String "_last"
3294− toJSON FirstMissing = String "_first"
3295− toJSON (CustomMissing txt) = String txt
3298−instance ToJSON ScoreType where
3299− toJSON ScoreTypeMax = "max"
3300− toJSON ScoreTypeAvg = "avg"
3301− toJSON ScoreTypeSum = "sum"
3302− toJSON ScoreTypeNone = "none"
3304−instance FromJSON ScoreType where
3305− parseJSON = withText "ScoreType" parse
3306− where parse "max" = pure ScoreTypeMax
3307− parse "avg" = pure ScoreTypeAvg
3308− parse "sum" = pure ScoreTypeSum
3309− parse "none" = pure ScoreTypeNone
3310− parse t = fail ("Unexpected ScoreType: " <> show t)
3312−instance ToJSON Distance where
3313− toJSON (Distance dCoefficient dUnit) =
3314− String boltedTogether where
3315− coefText = showText dCoefficient
3316− (String unitText) = toJSON dUnit
3317− boltedTogether = mappend coefText unitText
3319−instance FromJSON Distance where
3320− parseJSON = withText "Distance" parse
3321− where parse t = Distance <$> parseCoeff nT
3322− <*> parseJSON (String unitT)
3323− where (nT, unitT) = T.span validForNumber t
3324− -- may be a better way to do this
3325− validForNumber '-' = True
3326− validForNumber '.' = True
3327− validForNumber 'e' = True
3328− validForNumber c = isNumber c
3329− parseCoeff "" = fail "Empty string cannot be parsed as number"
3330− parseCoeff s = return (read (T.unpack s))
3332−instance ToJSON DistanceUnit where
3333− toJSON Miles = String "mi"
3334− toJSON Yards = String "yd"
3335− toJSON Feet = String "ft"
3336− toJSON Inches = String "in"
3337− toJSON Kilometers = String "km"
3338− toJSON Meters = String "m"
3339− toJSON Centimeters = String "cm"
3340− toJSON Millimeters = String "mm"
3341− toJSON NauticalMiles = String "nmi"
3344−instance FromJSON DistanceUnit where
3345− parseJSON = withText "DistanceUnit" parse
3346− where parse "mi" = pure Miles
3347− parse "yd" = pure Yards
3348− parse "ft" = pure Feet
3349− parse "in" = pure Inches
3350− parse "km" = pure Kilometers
3351− parse "m" = pure Meters
3352− parse "cm" = pure Centimeters
3353− parse "mm" = pure Millimeters
3354− parse "nmi" = pure NauticalMiles
3355− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3357−instance ToJSON DistanceType where
3358− toJSON Arc = String "arc"
3359− toJSON SloppyArc = String "sloppy_arc"
3360− toJSON Plane = String "plane"
3362−instance FromJSON DistanceType where
3363− parseJSON = withText "DistanceType" parse
3364− where parse "arc" = pure Arc
3365− parse "sloppy_arc" = pure SloppyArc
3366− parse "plane" = pure Plane
3367− parse t = fail ("Unrecognized DistanceType: " <> show t)
3370−instance ToJSON OptimizeBbox where
3371− toJSON NoOptimizeBbox = String "none"
3372− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3374−instance FromJSON OptimizeBbox where
3375− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3376− <|> parseOptimize v
3377− where parseNoOptimize "none" = pure NoOptimizeBbox
3378− parseNoOptimize _ = mzero
3379− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3381−instance ToJSON GeoBoundingBoxConstraint where
3382− toJSON (GeoBoundingBoxConstraint
3383− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3384− object [gbbcGeoBBField .= gbbcConstraintBox
3385− , "_cache" .= cache
3388−instance FromJSON GeoBoundingBoxConstraint where
3389− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3390− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3391− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3393− <*> o .:? "_cache" .!= defaultCache
3395− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3397−instance ToJSON GeoFilterType where
3398− toJSON GeoFilterMemory = String "memory"
3399− toJSON GeoFilterIndexed = String "indexed"
3401−instance FromJSON GeoFilterType where
3402− parseJSON = withText "GeoFilterType" parse
3403− where parse "memory" = pure GeoFilterMemory
3404− parse "indexed" = pure GeoFilterIndexed
3405− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3407−instance ToJSON GeoBoundingBox where
3408− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3409− object ["top_left" .= gbbTopLeft
3410− , "bottom_right" .= gbbBottomRight]
3412−instance FromJSON GeoBoundingBox where
3413− parseJSON = withObject "GeoBoundingBox" parse
3414− where parse o = GeoBoundingBox
3415− <$> o .: "top_left"
3416− <*> o .: "bottom_right"
3418−instance ToJSON LatLon where
3419− toJSON (LatLon lLat lLon) =
3420− object ["lat" .= lLat
3423−instance FromJSON LatLon where
3424− parseJSON = withObject "LatLon" parse
3425− where parse o = LatLon <$> o .: "lat"
3428−-- index for smaller ranges, fielddata for longer ranges
3429−instance ToJSON RangeExecution where
3430− toJSON RangeExecutionIndex = "index"
3431− toJSON RangeExecutionFielddata = "fielddata"
3434−instance FromJSON RangeExecution where
3435− parseJSON = withText "RangeExecution" parse
3436− where parse "index" = pure RangeExecutionIndex
3437− parse "fielddata" = pure RangeExecutionFielddata
3438− parse t = error ("Unrecognized RangeExecution " <> show t)
3440−instance ToJSON RegexpFlags where
3441− toJSON AllRegexpFlags = String "ALL"
3442− toJSON NoRegexpFlags = String "NONE"
3443− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3444− where flagStrs = map flagStr . nub $ h:fs
3445− flagStr AnyString = "ANYSTRING"
3446− flagStr Automaton = "AUTOMATON"
3447− flagStr Complement = "COMPLEMENT"
3448− flagStr Empty = "EMPTY"
3449− flagStr Intersection = "INTERSECTION"
3450− flagStr Interval = "INTERVAL"
3452−instance FromJSON RegexpFlags where
3453− parseJSON = withText "RegexpFlags" parse
3454− where parse "ALL" = pure AllRegexpFlags
3455− parse "NONE" = pure NoRegexpFlags
3456− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3458−instance FromJSON RegexpFlag where
3459− parseJSON = withText "RegexpFlag" parse
3460− where parse "ANYSTRING" = pure AnyString
3461− parse "AUTOMATON" = pure Automaton
3462− parse "COMPLEMENT" = pure Complement
3463− parse "EMPTY" = pure Empty
3464− parse "INTERSECTION" = pure Intersection
3465− parse "INTERVAL" = pure Interval
3466− parse f = fail ("Unknown RegexpFlag: " <> show f)
3468−instance ToJSON Term where
3469− toJSON (Term field value) = object ["term" .= object
3472−instance FromJSON Term where
3473− parseJSON = withObject "Term" parse
3474− where parse o = do termObj <- o .: "term"
3475− case HM.toList termObj of
3476− [(fn, v)] -> Term fn <$> parseJSON v
3477− _ -> fail "Expected object with 1 field-named key"
3479−instance ToJSON BoolMatch where
3480− toJSON (MustMatch term cache) = object ["must" .= term,
3482− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3484− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3487−instance FromJSON BoolMatch where
3488− parseJSON = withObject "BoolMatch" parse
3489− where parse o = mustMatch `taggedWith` "must"
3490− <|> mustNotMatch `taggedWith` "must_not"
3491− <|> shouldMatch `taggedWith` "should"
3492− where taggedWith parser k = parser =<< o .: k
3493− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3494− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3495− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
3497instance (FromJSON a) => FromJSON (SearchResult a) where
444instance (FromJSON a) => FromJSON (SearchResult a) where
3498 parseJSON (Object v) = SearchResult <$>
445 parseJSON (Object v) = SearchResult <$>
@@ -3504,1747 +451,3 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3504 v .:? "_scroll_id" <*>
451 v .:? "_scroll_id" <*>
3505 v .:? "suggest"
452 v .:? "suggest"
3506 parseJSON _ = empty
453 parseJSON _ = empty
3508−instance (FromJSON a) => FromJSON (SearchHits a) where
3509− parseJSON (Object v) = SearchHits <$>
3511− v .: "max_score" <*>
3513− parseJSON _ = empty
3515−instance (FromJSON a) => FromJSON (Hit a) where
3516− parseJSON (Object v) = Hit <$>
3521− v .:? "_source" <*>
3523− parseJSON _ = empty
3525−instance FromJSON ShardResult where
3526− parseJSON (Object v) = ShardResult <$>
3528− v .: "successful" <*>
3530− parseJSON _ = empty
3533−instance FromJSON DocVersion where
3536− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3538−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3539−instance FromJSON ReplicaCount where
3540− parseJSON v = parseAsInt v
3541− <|> parseAsString v
3542− where parseAsInt = fmap ReplicaCount . parseJSON
3543− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3545−instance FromJSON ShardCount where
3546− parseJSON v = parseAsInt v
3547− <|> parseAsString v
3548− where parseAsInt = fmap ShardCount . parseJSON
3549− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3551−instance Bounded DocVersion where
3552− minBound = DocVersion 1
3553− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3555−instance Enum DocVersion where
3557− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3558− | otherwise = succError "DocVersion"
3560− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3561− | otherwise = predError "DocVersion"
3563− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3564− fromEnum = docVersionNumber
3565− enumFrom = boundedEnumFrom
3566− enumFromThen = boundedEnumFromThen
3568−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3569−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Read, Show, Eq)
3571−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3572−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Read, Show, Eq)
3575−data SnapshotRepoSelection = SnapshotRepoList (NonEmpty SnapshotRepoPattern)
3576− | AllSnapshotRepos deriving (Eq, Generic, Show, Typeable)
3579−-- | Either specifies an exact repo name or one with globs in it,
3580−-- e.g. @RepoPattern "foo*"@ __NOTE__: Patterns are not supported on ES < 1.7
3581−data SnapshotRepoPattern = ExactRepo SnapshotRepoName
3583− deriving (Eq, Generic, Show, Typeable)
3585−-- | The unique name of a snapshot repository.
3586−newtype SnapshotRepoName = SnapshotRepoName { snapshotRepoName :: Text }
3587− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3590−-- | A generic representation of a snapshot repo. This is what gets
3591−-- sent to and parsed from the server. For repo types enabled by
3592−-- plugins that aren't exported by this library, consider making a
3593−-- custom type which implements 'SnapshotRepo'. If it is a common repo
3594−-- type, consider submitting a pull request to have it included in the
3596−data GenericSnapshotRepo = GenericSnapshotRepo {
3597− gSnapshotRepoName :: SnapshotRepoName
3598− , gSnapshotRepoType :: SnapshotRepoType
3599− , gSnapshotRepoSettings :: GenericSnapshotRepoSettings
3600− } deriving (Eq, Generic, Show, Typeable)
3603−instance SnapshotRepo GenericSnapshotRepo where
3604− toGSnapshotRepo = id
3605− fromGSnapshotRepo = Right
3608−newtype SnapshotRepoType = SnapshotRepoType { snapshotRepoType :: Text }
3609− deriving (Eq, Ord, Generic, Show, Typeable, ToJSON, FromJSON)
3612−-- | Opaque representation of snapshot repo settings. Instances of
3613−-- 'SnapshotRepo' will produce this.
3614−newtype GenericSnapshotRepoSettings = GenericSnapshotRepoSettings { gSnapshotRepoSettingsObject :: Object }
3615− deriving (Eq, Generic, Show, Typeable, ToJSON)
3618− -- Regardless of whether you send strongly typed json, my version of
3619− -- ES sends back stringly typed json in the settings, e.g. booleans
3620− -- as strings, so we'll try to convert them.
3621−instance FromJSON GenericSnapshotRepoSettings where
3622− parseJSON = fmap (GenericSnapshotRepoSettings . fmap unStringlyTypeJSON). parseJSON
3624−-- | The result of running 'verifySnapshotRepo'.
3625−newtype SnapshotVerification = SnapshotVerification { snapshotNodeVerifications :: [SnapshotNodeVerification] }
3626− deriving (Eq, Generic, Show, Typeable)
3629−instance FromJSON SnapshotVerification where
3630− parseJSON = withObject "SnapshotVerification" parse
3634− SnapshotVerification <$> mapM (uncurry parse') (HM.toList o2)
3635− parse' rawFullId = withObject "SnapshotNodeVerification" $ \o ->
3636− SnapshotNodeVerification (FullNodeId rawFullId) <$> o .: "name"
3639−-- | A node that has verified a snapshot
3640−data SnapshotNodeVerification = SnapshotNodeVerification {
3641− snvFullId :: FullNodeId
3642− , snvNodeName :: NodeName
3643− } deriving (Eq, Generic, Show, Typeable)
3646−-- | Unique, automatically-generated name assigned to nodes that are
3647−-- usually returned in node-oriented APIs.
3648−newtype FullNodeId = FullNodeId { fullNodeId :: Text }
3649− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3652−-- | A human-readable node name that is supplied by the user in the
3653−-- node config or automatically generated by ElasticSearch.
3654−newtype NodeName = NodeName { nodeName :: Text }
3655− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3657−newtype ClusterName = ClusterName { clusterName :: Text }
3658− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3660−data NodesInfo = NodesInfo {
3661− nodesInfo :: [NodeInfo]
3662− , nodesClusterName :: ClusterName
3663− } deriving (Eq, Show, Generic, Typeable)
3665−data NodesStats = NodesStats {
3666− nodesStats :: [NodeStats]
3667− , nodesStatsClusterName :: ClusterName
3668− } deriving (Eq, Show, Generic, Typeable)
3670−data NodeStats = NodeStats {
3671− nodeStatsName :: NodeName
3672− , nodeStatsFullId :: FullNodeId
3673− , nodeStatsBreakersStats :: Maybe NodeBreakersStats
3674− , nodeStatsHTTP :: NodeHTTPStats
3675− , nodeStatsTransport :: NodeTransportStats
3676− , nodeStatsFS :: NodeFSStats
3677− , nodeStatsNetwork :: NodeNetworkStats
3678− , nodeStatsThreadPool :: NodeThreadPoolsStats
3679− , nodeStatsJVM :: NodeJVMStats
3680− , nodeStatsProcess :: NodeProcessStats
3681− , nodeStatsOS :: NodeOSStats
3682− , nodeStatsIndices :: NodeIndicesStats
3683− } deriving (Eq, Show, Generic, Typeable)
3685−data NodeBreakersStats = NodeBreakersStats {
3686− nodeStatsParentBreaker :: NodeBreakerStats
3687− , nodeStatsRequestBreaker :: NodeBreakerStats
3688− , nodeStatsFieldDataBreaker :: NodeBreakerStats
3689− } deriving (Eq, Show, Generic, Typeable)
3691−data NodeBreakerStats = NodeBreakerStats {
3692− nodeBreakersTripped :: Int
3693− , nodeBreakersOverhead :: Double
3694− , nodeBreakersEstSize :: Bytes
3695− , nodeBreakersLimitSize :: Bytes
3696− } deriving (Eq, Show, Generic, Typeable)
3698−data NodeHTTPStats = NodeHTTPStats {
3699− nodeHTTPTotalOpened :: Int
3700− , nodeHTTPCurrentOpen :: Int
3701− } deriving (Eq, Show, Generic, Typeable)
3703−data NodeTransportStats = NodeTransportStats {
3704− nodeTransportTXSize :: Bytes
3705− , nodeTransportCount :: Int
3706− , nodeTransportRXSize :: Bytes
3707− , nodeTransportRXCount :: Int
3708− , nodeTransportServerOpen :: Int
3709− } deriving (Eq, Show, Generic, Typeable)
3711−data NodeFSStats = NodeFSStats {
3712− nodeFSDataPaths :: [NodeDataPathStats]
3713− , nodeFSTotal :: NodeFSTotalStats
3714− , nodeFSTimestamp :: UTCTime
3715− } deriving (Eq, Show, Generic, Typeable)
3717−data NodeDataPathStats = NodeDataPathStats {
3718− nodeDataPathDiskServiceTime :: Maybe Double
3719− , nodeDataPathDiskQueue :: Maybe Double
3720− , nodeDataPathIOSize :: Maybe Bytes
3721− , nodeDataPathWriteSize :: Maybe Bytes
3722− , nodeDataPathReadSize :: Maybe Bytes
3723− , nodeDataPathIOOps :: Maybe Int
3724− , nodeDataPathWrites :: Maybe Int
3725− , nodeDataPathReads :: Maybe Int
3726− , nodeDataPathAvailable :: Bytes
3727− , nodeDataPathFree :: Bytes
3728− , nodeDataPathTotal :: Bytes
3729− , nodeDataPathType :: Maybe Text
3730− , nodeDataPathDevice :: Text
3731− , nodeDataPathMount :: Text
3732− , nodeDataPathPath :: Text
3733− } deriving (Eq, Show, Generic, Typeable)
3735−data NodeFSTotalStats = NodeFSTotalStats {
3736− nodeFSTotalDiskServiceTime :: Maybe Double
3737− , nodeFSTotalDiskQueue :: Maybe Double
3738− , nodeFSTotalIOSize :: Maybe Bytes
3739− , nodeFSTotalWriteSize :: Maybe Bytes
3740− , nodeFSTotalReadSize :: Maybe Bytes
3741− , nodeFSTotalIOOps :: Maybe Int
3742− , nodeFSTotalWrites :: Maybe Int
3743− , nodeFSTotalReads :: Maybe Int
3744− , nodeFSTotalAvailable :: Bytes
3745− , nodeFSTotalFree :: Bytes
3746− , nodeFSTotalTotal :: Bytes
3747− } deriving (Eq, Show, Generic, Typeable)
3749−data NodeNetworkStats = NodeNetworkStats {
3750− nodeNetTCPOutRSTs :: Int
3751− , nodeNetTCPInErrs :: Int
3752− , nodeNetTCPAttemptFails :: Int
3753− , nodeNetTCPEstabResets :: Int
3754− , nodeNetTCPRetransSegs :: Int
3755− , nodeNetTCPOutSegs :: Int
3756− , nodeNetTCPInSegs :: Int
3757− , nodeNetTCPCurrEstab :: Int
3758− , nodeNetTCPPassiveOpens :: Int
3759− , nodeNetTCPActiveOpens :: Int
3760− } deriving (Eq, Show, Generic, Typeable)
3762−data NodeThreadPoolsStats = NodeThreadPoolsStats {
3763− nodeThreadPoolsStatsSnapshot :: NodeThreadPoolStats
3764− , nodeThreadPoolsStatsBulk :: NodeThreadPoolStats
3765− , nodeThreadPoolsStatsMerge :: NodeThreadPoolStats
3766− , nodeThreadPoolsStatsGet :: NodeThreadPoolStats
3767− , nodeThreadPoolsStatsManagement :: NodeThreadPoolStats
3768− , nodeThreadPoolsStatsFetchShardStore :: Maybe NodeThreadPoolStats
3769− , nodeThreadPoolsStatsOptimize :: NodeThreadPoolStats
3770− , nodeThreadPoolsStatsFlush :: NodeThreadPoolStats
3771− , nodeThreadPoolsStatsSearch :: NodeThreadPoolStats
3772− , nodeThreadPoolsStatsWarmer :: NodeThreadPoolStats
3773− , nodeThreadPoolsStatsGeneric :: NodeThreadPoolStats
3774− , nodeThreadPoolsStatsSuggest :: NodeThreadPoolStats
3775− , nodeThreadPoolsStatsRefresh :: NodeThreadPoolStats
3776− , nodeThreadPoolsStatsIndex :: NodeThreadPoolStats
3777− , nodeThreadPoolsStatsListener :: Maybe NodeThreadPoolStats
3778− , nodeThreadPoolsStatsFetchShardStarted :: Maybe NodeThreadPoolStats
3779− , nodeThreadPoolsStatsPercolate :: NodeThreadPoolStats
3780− } deriving (Eq, Show, Generic, Typeable)
3782−data NodeThreadPoolStats = NodeThreadPoolStats {
3783− nodeThreadPoolCompleted :: Int
3784− , nodeThreadPoolLargest :: Int
3785− , nodeThreadPoolRejected :: Int
3786− , nodeThreadPoolActive :: Int
3787− , nodeThreadPoolQueue :: Int
3788− , nodeThreadPoolThreads :: Int
3789− } deriving (Eq, Show, Generic, Typeable)
3791−data NodeJVMStats = NodeJVMStats {
3792− nodeJVMStatsMappedBufferPool :: JVMBufferPoolStats
3793− , nodeJVMStatsDirectBufferPool :: JVMBufferPoolStats
3794− , nodeJVMStatsGCOldCollector :: JVMGCStats
3795− , nodeJVMStatsGCYoungCollector :: JVMGCStats
3796− , nodeJVMStatsPeakThreadsCount :: Int
3797− , nodeJVMStatsThreadsCount :: Int
3798− , nodeJVMStatsOldPool :: JVMPoolStats
3799− , nodeJVMStatsSurvivorPool :: JVMPoolStats
3800− , nodeJVMStatsYoungPool :: JVMPoolStats
3801− , nodeJVMStatsNonHeapCommitted :: Bytes
3802− , nodeJVMStatsNonHeapUsed :: Bytes
3803− , nodeJVMStatsHeapMax :: Bytes
3804− , nodeJVMStatsHeapCommitted :: Bytes
3805− , nodeJVMStatsHeapUsedPercent :: Int
3806− , nodeJVMStatsHeapUsed :: Bytes
3807− , nodeJVMStatsUptime :: NominalDiffTime
3808− , nodeJVMStatsTimestamp :: UTCTime
3809− } deriving (Eq, Show, Generic, Typeable)
3811−data JVMBufferPoolStats = JVMBufferPoolStats {
3812− jvmBufferPoolStatsTotalCapacity :: Bytes
3813− , jvmBufferPoolStatsUsed :: Bytes
3814− , jvmBufferPoolStatsCount :: Int
3815− } deriving (Eq, Show, Generic, Typeable)
3817−data JVMGCStats = JVMGCStats {
3818− jvmGCStatsCollectionTime :: NominalDiffTime
3819− , jvmGCStatsCollectionCount :: Int
3820− } deriving (Eq, Show, Generic, Typeable)
3822−data JVMPoolStats = JVMPoolStats {
3823− jvmPoolStatsPeakMax :: Bytes
3824− , jvmPoolStatsPeakUsed :: Bytes
3825− , jvmPoolStatsMax :: Bytes
3826− , jvmPoolStatsUsed :: Bytes
3827− } deriving (Eq, Show, Generic, Typeable)
3829−data NodeProcessStats = NodeProcessStats {
3830− nodeProcessMemTotalVirtual :: Bytes
3831− , nodeProcessMemShare :: Bytes
3832− , nodeProcessMemResident :: Bytes
3833− , nodeProcessCPUTotal :: NominalDiffTime
3834− , nodeProcessCPUUser :: NominalDiffTime
3835− , nodeProcessCPUSys :: NominalDiffTime
3836− , nodeProcessCPUPercent :: Int
3837− , nodeProcessOpenFDs :: Int
3838− , nodeProcessTimestamp :: UTCTime
3839− } deriving (Eq, Show, Generic, Typeable)
3841−data NodeOSStats = NodeOSStats {
3842− nodeOSSwapFree :: Bytes
3843− , nodeOSSwapUsed :: Bytes
3844− , nodeOSMemActualUsed :: Bytes
3845− , nodeOSMemActualFree :: Bytes
3846− , nodeOSMemUsedPercent :: Int
3847− , nodeOSMemFreePercent :: Int
3848− , nodeOSMemUsed :: Bytes
3849− , nodeOSMemFree :: Bytes
3850− , nodeOSCPUStolen :: Int
3851− , nodeOSCPUUsage :: Int
3852− , nodeOSCPUIdle :: Int
3853− , nodeOSCPUUser :: Int
3854− , nodeOSCPUSys :: Int
3855− , nodeOSLoad :: Maybe LoadAvgs
3856− , nodeOSUptime :: NominalDiffTime
3857− , nodeOSTimestamp :: UTCTime
3858− } deriving (Eq, Show, Generic, Typeable)
3860−data LoadAvgs = LoadAvgs {
3861− loadAvg1Min :: Double
3862− , loadAvg5Min :: Double
3863− , loadAvg15Min :: Double
3864− } deriving (Eq, Show, Generic, Typeable)
3866−data NodeIndicesStats = NodeIndicesStats {
3867− nodeIndicesStatsRecoveryThrottleTime :: Maybe NominalDiffTime
3868− , nodeIndicesStatsRecoveryCurrentAsTarget :: Maybe Int
3869− , nodeIndicesStatsRecoveryCurrentAsSource :: Maybe Int
3870− , nodeIndicesStatsQueryCacheMisses :: Maybe Int
3871− , nodeIndicesStatsQueryCacheHits :: Maybe Int
3872− , nodeIndicesStatsQueryCacheEvictions :: Maybe Int
3873− , nodeIndicesStatsQueryCacheSize :: Maybe Bytes
3874− , nodeIndicesStatsSuggestCurrent :: Int
3875− , nodeIndicesStatsSuggestTime :: NominalDiffTime
3876− , nodeIndicesStatsSuggestTotal :: Int
3877− , nodeIndicesStatsTranslogSize :: Bytes
3878− , nodeIndicesStatsTranslogOps :: Int
3879− , nodeIndicesStatsSegFixedBitSetMemory :: Maybe Bytes
3880− , nodeIndicesStatsSegVersionMapMemory :: Bytes
3881− , nodeIndicesStatsSegIndexWriterMaxMemory :: Maybe Bytes
3882− , nodeIndicesStatsSegIndexWriterMemory :: Bytes
3883− , nodeIndicesStatsSegMemory :: Bytes
3884− , nodeIndicesStatsSegCount :: Int
3885− , nodeIndicesStatsCompletionSize :: Bytes
3886− , nodeIndicesStatsPercolateQueries :: Int
3887− , nodeIndicesStatsPercolateMemory :: Bytes
3888− , nodeIndicesStatsPercolateCurrent :: Int
3889− , nodeIndicesStatsPercolateTime :: NominalDiffTime
3890− , nodeIndicesStatsPercolateTotal :: Int
3891− , nodeIndicesStatsFieldDataEvictions :: Int
3892− , nodeIndicesStatsFieldDataMemory :: Bytes
3893− , nodeIndicesStatsIDCacheMemory :: Bytes
3894− , nodeIndicesStatsFilterCacheEvictions :: Int
3895− , nodeIndicesStatsFilterCacheMemory :: Bytes
3896− , nodeIndicesStatsWarmerTotalTime :: NominalDiffTime
3897− , nodeIndicesStatsWarmerTotal :: Int
3898− , nodeIndicesStatsWarmerCurrent :: Int
3899− , nodeIndicesStatsFlushTotalTime :: NominalDiffTime
3900− , nodeIndicesStatsFlushTotal :: Int
3901− , nodeIndicesStatsRefreshTotalTime :: NominalDiffTime
3902− , nodeIndicesStatsRefreshTotal :: Int
3903− , nodeIndicesStatsMergesTotalSize :: Bytes
3904− , nodeIndicesStatsMergesTotalDocs :: Int
3905− , nodeIndicesStatsMergesTotalTime :: NominalDiffTime
3906− , nodeIndicesStatsMergesTotal :: Int
3907− , nodeIndicesStatsMergesCurrentSize :: Bytes
3908− , nodeIndicesStatsMergesCurrentDocs :: Int
3909− , nodeIndicesStatsMergesCurrent :: Int
3910− , nodeIndicesStatsSearchFetchCurrent :: Int
3911− , nodeIndicesStatsSearchFetchTime :: NominalDiffTime
3912− , nodeIndicesStatsSearchFetchTotal :: Int
3913− , nodeIndicesStatsSearchQueryCurrent :: Int
3914− , nodeIndicesStatsSearchQueryTime :: NominalDiffTime
3915− , nodeIndicesStatsSearchQueryTotal :: Int
3916− , nodeIndicesStatsSearchOpenContexts :: Int
3917− , nodeIndicesStatsGetCurrent :: Int
3918− , nodeIndicesStatsGetMissingTime :: NominalDiffTime
3919− , nodeIndicesStatsGetMissingTotal :: Int
3920− , nodeIndicesStatsGetExistsTime :: NominalDiffTime
3921− , nodeIndicesStatsGetExistsTotal :: Int
3922− , nodeIndicesStatsGetTime :: NominalDiffTime
3923− , nodeIndicesStatsGetTotal :: Int
3924− , nodeIndicesStatsIndexingThrottleTime :: Maybe NominalDiffTime
3925− , nodeIndicesStatsIndexingIsThrottled :: Maybe Bool
3926− , nodeIndicesStatsIndexingNoopUpdateTotal :: Maybe Int
3927− , nodeIndicesStatsIndexingDeleteCurrent :: Int
3928− , nodeIndicesStatsIndexingDeleteTime :: NominalDiffTime
3929− , nodeIndicesStatsIndexingDeleteTotal :: Int
3930− , nodeIndicesStatsIndexingIndexCurrent :: Int
3931− , nodeIndicesStatsIndexingIndexTime :: NominalDiffTime
3932− , nodeIndicesStatsIndexingTotal :: Int
3933− , nodeIndicesStatsStoreThrottleTime :: NominalDiffTime
3934− , nodeIndicesStatsStoreSize :: Bytes
3935− , nodeIndicesStatsDocsDeleted :: Int
3936− , nodeIndicesStatsDocsCount :: Int
3937− } deriving (Eq, Show, Generic, Typeable)
3939−-- | A quirky address format used throughout ElasticSearch. An example
3940−-- would be inet[/1.1.1.1:9200]. inet may be a placeholder for a
3941−-- <https://en.wikipedia.org/wiki/Fully_qualified_domain_name FQDN>.
3942−newtype EsAddress = EsAddress { esAddress :: Text }
3943− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3945−-- | Typically a 7 character hex string.
3946−newtype BuildHash = BuildHash { buildHash :: Text }
3947− deriving (Eq, Ord, Generic, Read, Show, Typeable, FromJSON, ToJSON)
3949−newtype PluginName = PluginName { pluginName :: Text }
3950− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
3952−data NodeInfo = NodeInfo {
3953− nodeInfoHTTPAddress :: EsAddress
3954− , nodeInfoBuild :: BuildHash
3955− , nodeInfoESVersion :: VersionNumber
3956− , nodeInfoIP :: Server
3957− , nodeInfoHost :: Server
3958− , nodeInfoTransportAddress :: EsAddress
3959− , nodeInfoName :: NodeName
3960− , nodeInfoFullId :: FullNodeId
3961− , nodeInfoPlugins :: [NodePluginInfo]
3962− , nodeInfoHTTP :: NodeHTTPInfo
3963− , nodeInfoTransport :: NodeTransportInfo
3964− , nodeInfoNetwork :: NodeNetworkInfo
3965− , nodeInfoThreadPool :: NodeThreadPoolsInfo
3966− , nodeInfoJVM :: NodeJVMInfo
3967− , nodeInfoProcess :: NodeProcessInfo
3968− , nodeInfoOS :: NodeOSInfo
3969− , nodeInfoSettings :: Object
3970− -- ^ The members of the settings objects are not consistent,
3971− -- dependent on plugins, etc.
3972− } deriving (Eq, Show, Generic, Typeable)
3974−data NodePluginInfo = NodePluginInfo {
3975− nodePluginSite :: Bool
3976− -- ^ Is this a site plugin?
3977− , nodePluginJVM :: Bool
3978− -- ^ Is this plugin running on the JVM
3979− , nodePluginDescription :: Text
3980− , nodePluginVersion :: MaybeNA VersionNumber
3981− , nodePluginName :: PluginName
3982− } deriving (Eq, Show, Generic, Typeable)
3984−data NodeHTTPInfo = NodeHTTPInfo {
3985− nodeHTTPMaxContentLength :: Bytes
3986− , nodeHTTPTransportAddress :: BoundTransportAddress
3987− } deriving (Eq, Show, Generic, Typeable)
3989−data NodeTransportInfo = NodeTransportInfo {
3990− nodeTransportProfiles :: [BoundTransportAddress]
3991− , nodeTransportAddress :: BoundTransportAddress
3992− } deriving (Eq, Show, Generic, Typeable)
3994−data BoundTransportAddress = BoundTransportAddress {
3995− publishAddress :: EsAddress
3996− , boundAddress :: EsAddress
3997− } deriving (Eq, Show, Generic, Typeable)
3999−data NodeNetworkInfo = NodeNetworkInfo {
4000− nodeNetworkPrimaryInterface :: NodeNetworkInterface
4001− , nodeNetworkRefreshInterval :: NominalDiffTime
4002− } deriving (Eq, Show, Generic, Typeable)
4004−newtype MacAddress = MacAddress { macAddress :: Text }
4005− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4007−newtype NetworkInterfaceName = NetworkInterfaceName { networkInterfaceName :: Text }
4008− deriving (Eq, Ord, Generic, Show, Typeable, FromJSON)
4010−data NodeNetworkInterface = NodeNetworkInterface {
4011− nodeNetIfaceMacAddress :: MacAddress
4012− , nodeNetIfaceName :: NetworkInterfaceName
4013− , nodeNetIfaceAddress :: Server
4014− } deriving (Eq, Show, Generic, Typeable)
4016−data NodeThreadPoolsInfo = NodeThreadPoolsInfo {
4017− nodeThreadPoolsRefresh :: NodeThreadPoolInfo
4018− , nodeThreadPoolsManagement :: NodeThreadPoolInfo
4019− , nodeThreadPoolsPercolate :: NodeThreadPoolInfo
4020− , nodeThreadPoolsListener :: Maybe NodeThreadPoolInfo
4021− , nodeThreadPoolsFetchShardStarted :: Maybe NodeThreadPoolInfo
4022− , nodeThreadPoolsSearch :: NodeThreadPoolInfo
4023− , nodeThreadPoolsFlush :: NodeThreadPoolInfo
4024− , nodeThreadPoolsWarmer :: NodeThreadPoolInfo
4025− , nodeThreadPoolsOptimize :: NodeThreadPoolInfo
4026− , nodeThreadPoolsBulk :: NodeThreadPoolInfo
4027− , nodeThreadPoolsSuggest :: NodeThreadPoolInfo
4028− , nodeThreadPoolsMerge :: NodeThreadPoolInfo
4029− , nodeThreadPoolsSnapshot :: NodeThreadPoolInfo
4030− , nodeThreadPoolsGet :: NodeThreadPoolInfo
4031− , nodeThreadPoolsFetchShardStore :: Maybe NodeThreadPoolInfo
4032− , nodeThreadPoolsIndex :: NodeThreadPoolInfo
4033− , nodeThreadPoolsGeneric :: NodeThreadPoolInfo
4034− } deriving (Eq, Show, Generic, Typeable)
4036−data NodeThreadPoolInfo = NodeThreadPoolInfo {
4037− nodeThreadPoolQueueSize :: ThreadPoolSize
4038− , nodeThreadPoolKeepalive :: Maybe NominalDiffTime
4039− , nodeThreadPoolMin :: Maybe Int
4040− , nodeThreadPoolMax :: Maybe Int
4041− , nodeThreadPoolType :: ThreadPoolType
4042− } deriving (Eq, Show, Generic, Typeable)
4044−data ThreadPoolSize = ThreadPoolBounded Int
4045− | ThreadPoolUnbounded
4046− deriving (Eq, Show, Generic, Typeable)
4048−data ThreadPoolType = ThreadPoolScaling
4051− deriving (Eq, Show, Generic, Typeable)
4053−data NodeJVMInfo = NodeJVMInfo {
4054− nodeJVMInfoMemoryPools :: [JVMMemoryPool]
4055− , nodeJVMInfoMemoryPoolsGCCollectors :: [JVMGCCollector]
4056− , nodeJVMInfoMemoryInfo :: JVMMemoryInfo
4057− , nodeJVMInfoStartTime :: UTCTime
4058− , nodeJVMInfoVMVendor :: Text
4059− , nodeJVMVMVersion :: VersionNumber
4060− -- ^ JVM doesn't seme to follow normal version conventions
4061− , nodeJVMVMName :: Text
4062− , nodeJVMVersion :: VersionNumber
4063− , nodeJVMPID :: PID
4064− } deriving (Eq, Show, Generic, Typeable)
4066−-- | Handles quirks in the way JVM versions are rendered (1.7.0_101 -> 1.7.0.101)
4067−newtype JVMVersion = JVMVersion { unJVMVersion :: VersionNumber }
4069−data JVMMemoryInfo = JVMMemoryInfo {
4070− jvmMemoryInfoDirectMax :: Bytes
4071− , jvmMemoryInfoNonHeapMax :: Bytes
4072− , jvmMemoryInfoNonHeapInit :: Bytes
4073− , jvmMemoryInfoHeapMax :: Bytes
4074− , jvmMemoryInfoHeapInit :: Bytes
4075− } deriving (Eq, Show, Generic, Typeable)
4077−newtype JVMMemoryPool = JVMMemoryPool {
4078− jvmMemoryPool :: Text
4079− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4081−newtype JVMGCCollector = JVMGCCollector {
4082− jvmGCCollector :: Text
4083− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4087− } deriving (Eq, Show, Generic, Typeable, FromJSON)
4089−data NodeOSInfo = NodeOSInfo {
4090− nodeOSSwap :: Bytes
4091− , nodeOSMem :: Bytes
4092− , nodeOSCPUInfo :: CPUInfo
4093− , nodeOSAvailableProcessors :: Int
4094− , nodeOSRefreshInterval :: NominalDiffTime
4095− } deriving (Eq, Show, Generic, Typeable)
4097−data CPUInfo = CPUInfo {
4098− cpuCacheSize :: Bytes
4099− , cpuCoresPerSocket :: Int
4100− , cpuTotalSockets :: Int
4101− , cpuTotalCores :: Int
4104− , cpuVendor :: Text
4105− } deriving (Eq, Show, Generic, Typeable)
4107−data NodeProcessInfo = NodeProcessInfo {
4108− nodeProcessMLockAll :: Bool
4109− -- ^ See <https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration.html>
4110− , nodeProcessMaxFileDescriptors :: Int
4111− , nodeProcessId :: PID
4112− , nodeProcessRefreshInterval :: NominalDiffTime
4113− } deriving (Eq, Show, Generic, Typeable)
4115−data SnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings {
4116− repoUpdateVerify :: Bool
4117− -- ^ After creation/update, synchronously check that nodes can
4118− -- write to this repo. Defaults to True. You may use False if you
4119− -- need a faster response and plan on verifying manually later
4120− -- with 'verifySnapshotRepo'.
4121− } deriving (Eq, Show, Generic, Typeable)
4124−-- | Reasonable defaults for repo creation/update
4126−-- * repoUpdateVerify True
4127−defaultSnapshotRepoUpdateSettings :: SnapshotRepoUpdateSettings
4128−defaultSnapshotRepoUpdateSettings = SnapshotRepoUpdateSettings True
4131−-- | A filesystem-based snapshot repo that ships with
4132−-- ElasticSearch. This is an instance of 'SnapshotRepo' so it can be
4133−-- used with 'updateSnapshotRepo'
4134−data FsSnapshotRepo = FsSnapshotRepo {
4135− fsrName :: SnapshotRepoName
4136− , fsrLocation :: FilePath
4137− , fsrCompressMetadata :: Bool
4138− , fsrChunkSize :: Maybe Bytes
4139− -- ^ Size by which to split large files during snapshotting.
4140− , fsrMaxRestoreBytesPerSec :: Maybe Bytes
4141− -- ^ Throttle node restore rate. If not supplied, defaults to 40mb/sec
4142− , fsrMaxSnapshotBytesPerSec :: Maybe Bytes
4143− -- ^ Throttle node snapshot rate. If not supplied, defaults to 40mb/sec
4144− } deriving (Eq, Generic, Show, Typeable)
4147−instance SnapshotRepo FsSnapshotRepo where
4148− toGSnapshotRepo FsSnapshotRepo {..} =
4149− GenericSnapshotRepo fsrName fsRepoType (GenericSnapshotRepoSettings settings)
4151− Object settings = object $ [ "location" .= fsrLocation
4152− , "compress" .= fsrCompressMetadata
4154− optionalPairs = catMaybes [ ("chunk_size" .=) <$> fsrChunkSize
4155− , ("max_restore_bytes_per_sec" .=) <$> fsrMaxRestoreBytesPerSec
4156− , ("max_snapshot_bytes_per_sec" .=) <$> fsrMaxSnapshotBytesPerSec
4158− fromGSnapshotRepo GenericSnapshotRepo {..}
4159− | gSnapshotRepoType == fsRepoType = do
4160− let o = gSnapshotRepoSettingsObject gSnapshotRepoSettings
4162− FsSnapshotRepo gSnapshotRepoName <$> o .: "location"
4163− <*> o .:? "compress" .!= False
4164− <*> o .:? "chunk_size"
4165− <*> o .:? "max_restore_bytes_per_sec"
4166− <*> o .:? "max_snapshot_bytes_per_sec"
4167− | otherwise = Left (RepoTypeMismatch fsRepoType gSnapshotRepoType)
4170−parseRepo :: Parser a -> Either SnapshotRepoConversionError a
4171−parseRepo parser = case parseEither (const parser) () of
4172− Left e -> Left (OtherRepoConversionError (T.pack e))
4176−fsRepoType :: SnapshotRepoType
4177−fsRepoType = SnapshotRepoType "fs"
4179−-- | Law: fromGSnapshotRepo (toGSnapshotRepo r) == Right r
4180−class SnapshotRepo r where
4181− toGSnapshotRepo :: r -> GenericSnapshotRepo
4182− fromGSnapshotRepo :: GenericSnapshotRepo -> Either SnapshotRepoConversionError r
4185−data SnapshotRepoConversionError = RepoTypeMismatch SnapshotRepoType SnapshotRepoType
4186− -- ^ Expected type and actual type
4187− | OtherRepoConversionError Text
4188− deriving (Show, Eq, Generic, Typeable)
4191−instance Exception SnapshotRepoConversionError
4194−data SnapshotCreateSettings = SnapshotCreateSettings {
4195− snapWaitForCompletion :: Bool
4196− -- ^ Should the API call return immediately after initializing
4197− -- the snapshot or wait until completed? Note that if this is
4198− -- enabled it could wait a long time, so you should adjust your
4199− -- 'ManagerSettings' accordingly to set long timeouts or
4200− -- explicitly handle timeouts.
4201− , snapIndices :: Maybe IndexSelection
4202− -- ^ Nothing will snapshot all indices. Just [] is permissable and
4203− -- will essentially be a no-op snapshot.
4204− , snapIgnoreUnavailable :: Bool
4205− -- ^ If set to True, any matched indices that don't exist will be
4206− -- ignored. Otherwise it will be an error and fail.
4207− , snapIncludeGlobalState :: Bool
4208− , snapPartial :: Bool
4209− -- ^ If some indices failed to snapshot (e.g. if not all primary
4210− -- shards are available), should the process proceed?
4211− } deriving (Eq, Generic, Show, Typeable)
4214−-- | Reasonable defaults for snapshot creation
4216−-- * snapWaitForCompletion False
4217−-- * snapIndices Nothing
4218−-- * snapIgnoreUnavailable False
4219−-- * snapIncludeGlobalState True
4220−-- * snapPartial False
4221−defaultSnapshotCreateSettings :: SnapshotCreateSettings
4222−defaultSnapshotCreateSettings = SnapshotCreateSettings {
4223− snapWaitForCompletion = False
4224− , snapIndices = Nothing
4225− , snapIgnoreUnavailable = False
4226− , snapIncludeGlobalState = True
4227− , snapPartial = False
4231−data SnapshotSelection = SnapshotList (NonEmpty SnapshotPattern)
4232− | AllSnapshots deriving (Eq, Generic, Show, Typeable)
4235−-- | Either specifies an exact snapshot name or one with globs in it,
4236−-- e.g. @SnapPattern "foo*"@ __NOTE__: Patterns are not supported on
4238−data SnapshotPattern = ExactSnap SnapshotName
4240− deriving (Eq, Generic, Show, Typeable)
4243−-- | General information about the state of a snapshot. Has some
4244−-- redundancies with 'SnapshotStatus'
4245−data SnapshotInfo = SnapshotInfo {
4246− snapInfoShards :: ShardResult
4247− , snapInfoFailures :: [SnapshotShardFailure]
4248− , snapInfoDuration :: NominalDiffTime
4249− , snapInfoEndTime :: UTCTime
4250− , snapInfoStartTime :: UTCTime
4251− , snapInfoState :: SnapshotState
4252− , snapInfoIndices :: [IndexName]
4253− , snapInfoName :: SnapshotName
4254− } deriving (Eq, Generic, Show, Typeable)
4257−instance FromJSON SnapshotInfo where
4258− parseJSON = withObject "SnapshotInfo" parse
4260− parse o = SnapshotInfo <$> o .: "shards"
4261− <*> o .: "failures"
4262− <*> (unMS <$> o .: "duration_in_millis")
4263− <*> (posixMS <$> o .: "end_time_in_millis")
4264− <*> (posixMS <$> o .: "start_time_in_millis")
4267− <*> o .: "snapshot"
4269−data SnapshotShardFailure = SnapshotShardFailure {
4270− snapShardFailureIndex :: IndexName
4271− , snapShardFailureNodeId :: Maybe NodeName -- I'm not 100% sure this isn't actually 'FullNodeId'
4272− , snapShardFailureReason :: Text
4273− , snapShardFailureShardId :: ShardId
4274− } deriving (Eq, Show, Generic, Typeable)
4277−instance FromJSON SnapshotShardFailure where
4278− parseJSON = withObject "SnapshotShardFailure" parse
4280− parse o = SnapshotShardFailure <$> o .: "index"
4281− <*> o .:? "node_id"
4283− <*> o .: "shard_id"
4286−newtype ShardId = ShardId { shardId :: Int }
4287− deriving (Eq, Show, Generic, Typeable, FromJSON)
4290−newtype MS = MS NominalDiffTime
4293−-- keeps the unexported constructor warnings at bay
4294−unMS :: MS -> NominalDiffTime
4298−instance FromJSON MS where
4299− parseJSON = withScientific "MS" (return . MS . parse)
4301− parse n = fromInteger ((truncate n) * 1000)
4304−data SnapshotState = SnapshotInit
4311− deriving (Show, Eq, Generic, Typeable)
4313−instance FromJSON SnapshotState where
4314− parseJSON = withText "SnapshotState" parse
4316− parse "INIT" = return SnapshotInit
4317− parse "STARTED" = return SnapshotStarted
4318− parse "SUCCESS" = return SnapshotSuccess
4319− parse "FAILED" = return SnapshotFailed
4320− parse "ABORTED" = return SnapshotAborted
4321− parse "MISSING" = return SnapshotMissing
4322− parse "WAITING" = return SnapshotWaiting
4323− parse t = fail ("Invalid snapshot state " <> T.unpack t)
4326−newtype SnapshotName = SnapshotName { snapshotName :: Text }
4327− deriving (Show, Eq, Ord, Generic, Typeable, ToJSON, FromJSON)
4330−data SnapshotRestoreSettings = SnapshotRestoreSettings {
4331− snapRestoreWaitForCompletion :: Bool
4332− -- ^ Should the API call return immediately after initializing
4333− -- the restore or wait until completed? Note that if this is
4334− -- enabled, it could wait a long time, so you should adjust your
4335− -- 'ManagerSettings' accordingly to set long timeouts or
4336− -- explicitly handle timeouts.
4337− , snapRestoreIndices :: Maybe IndexSelection
4338− -- ^ Nothing will restore all indices in the snapshot. Just [] is
4339− -- permissable and will essentially be a no-op restore.
4340− , snapRestoreIgnoreUnavailable :: Bool
4341− -- ^ If set to True, any indices that do not exist will be ignored
4342− -- during snapshot rather than failing the restore.
4343− , snapRestoreIncludeGlobalState :: Bool
4344− -- ^ If set to false, will ignore any global state in the snapshot
4345− -- and will not restore it.
4346− , snapRestoreRenamePattern :: Maybe RestoreRenamePattern
4347− -- ^ A regex pattern for matching indices. Used with
4348− -- 'snapRestoreRenameReplacement', the restore can reference the
4349− -- matched index and create a new index name upon restore.
4350− , snapRestoreRenameReplacement :: Maybe (NonEmpty RestoreRenameToken)
4351− -- ^ Expression of how index renames should be constructed.
4352− , snapRestorePartial :: Bool
4353− -- ^ If some indices fail to restore, should the process proceed?
4354− , snapRestoreIncludeAliases :: Bool
4355− -- ^ Should the restore also restore the aliases captured in the
4357− , snapRestoreIndexSettingsOverrides :: Maybe RestoreIndexSettings
4358− -- ^ Settings to apply during the restore process. __NOTE:__ This
4359− -- option is not supported in ES < 1.5 and should be set to
4360− -- Nothing in that case.
4361− , snapRestoreIgnoreIndexSettings :: Maybe (NonEmpty Text)
4362− -- ^ This type could be more rich but it isn't clear which
4363− -- settings are allowed to be ignored during restore, so we're
4364− -- going with including this feature in a basic form rather than
4365− -- omitting it. One example here would be
4366− -- "index.refresh_interval". Any setting specified here will
4367− -- revert back to the server default during the restore process.
4368− } deriving (Eq, Generic, Show, Typeable)
4370−-- | Regex-stype pattern, e.g. "index_(.+)" to match index names
4371−newtype RestoreRenamePattern = RestoreRenamePattern { rrPattern :: Text }
4372− deriving (Show, Eq, Generic, Typeable, Ord, ToJSON)
4375−-- | A single token in a index renaming scheme for a restore. These
4376−-- are concatenated into a string before being sent to
4377−-- ElasticSearch. Check out these Java
4378−-- <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.
4379−data RestoreRenameToken = RRTLit Text
4380− -- ^ Just a literal string of characters
4382− -- ^ Equivalent to $0. The entire matched pattern, not any subgroup
4383− | RRSubGroup RRGroupRefNum
4384− -- ^ A specific reference to a group number
4385− deriving (Show, Eq, Generic, Typeable)
4388−-- | A group number for regex matching. Only values from 1-9 are
4389−-- supported. Construct with 'mkRRGroupRefNum'
4390−newtype RRGroupRefNum = RRGroupRefNum { rrGroupRefNum :: Int }
4391− deriving (Show, Eq, Generic, Typeable, Ord)
4393−instance Bounded RRGroupRefNum where
4394− minBound = RRGroupRefNum 1
4395− maxBound = RRGroupRefNum 9
4398−-- | Only allows valid group number references (1-9).
4399−mkRRGroupRefNum :: Int -> Maybe RRGroupRefNum
4401− | i >= (rrGroupRefNum minBound) && i <= (rrGroupRefNum maxBound) =
4402− Just $ RRGroupRefNum i
4403− | otherwise = Nothing
4406−-- | Reasonable defaults for snapshot restores
4408−-- * snapRestoreWaitForCompletion False
4409−-- * snapRestoreIndices Nothing
4410−-- * snapRestoreIgnoreUnavailable False
4411−-- * snapRestoreIncludeGlobalState True
4412−-- * snapRestoreRenamePattern Nothing
4413−-- * snapRestoreRenameReplacement Nothing
4414−-- * snapRestorePartial False
4415−-- * snapRestoreIncludeAliases True
4416−-- * snapRestoreIndexSettingsOverrides Nothing
4417−-- * snapRestoreIgnoreIndexSettings Nothing
4418−defaultSnapshotRestoreSettings :: SnapshotRestoreSettings
4419−defaultSnapshotRestoreSettings = SnapshotRestoreSettings {
4420− snapRestoreWaitForCompletion = False
4421− , snapRestoreIndices = Nothing
4422− , snapRestoreIgnoreUnavailable = False
4423− , snapRestoreIncludeGlobalState = True
4424− , snapRestoreRenamePattern = Nothing
4425− , snapRestoreRenameReplacement = Nothing
4426− , snapRestorePartial = False
4427− , snapRestoreIncludeAliases = True
4428− , snapRestoreIndexSettingsOverrides = Nothing
4429− , snapRestoreIgnoreIndexSettings = Nothing
4433−-- | Index settings that can be overridden. The docs only mention you
4434−-- can update number of replicas, but there may be more. You
4435−-- definitely cannot override shard count.
4436−data RestoreIndexSettings = RestoreIndexSettings {
4437− restoreOverrideReplicas :: Maybe ReplicaCount
4438− } deriving (Show, Eq, Generic, Typeable)
4441−instance ToJSON RestoreIndexSettings where
4442− toJSON RestoreIndexSettings {..} = object prs
4444− prs = catMaybes [("index.number_of_replicas" .=) <$> restoreOverrideReplicas]
4447−instance FromJSON NodesInfo where
4448− parseJSON = withObject "NodesInfo" parse
4451− nodes <- o .: "nodes"
4452− infos <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4453− node <- parseJSON v
4454− parseNodeInfo (FullNodeId fullNID) node
4455− cn <- o .: "cluster_name"
4456− return (NodesInfo infos cn)
4458−instance FromJSON NodesStats where
4459− parseJSON = withObject "NodesStats" parse
4462− nodes <- o .: "nodes"
4463− stats <- forM (HM.toList nodes) $ \(fullNID, v) -> do
4464− node <- parseJSON v
4465− parseNodeStats (FullNodeId fullNID) node
4466− cn <- o .: "cluster_name"
4467− return (NodesStats stats cn)
4469−instance FromJSON NodeBreakerStats where
4470− parseJSON = withObject "NodeBreakerStats" parse
4472− parse o = NodeBreakerStats <$> o .: "tripped"
4473− <*> o .: "overhead"
4474− <*> o .: "estimated_size_in_bytes"
4475− <*> o .: "limit_size_in_bytes"
4477−instance FromJSON NodeHTTPStats where
4478− parseJSON = withObject "NodeHTTPStats" parse
4480− parse o = NodeHTTPStats <$> o .: "total_opened"
4481− <*> o .: "current_open"
4483−instance FromJSON NodeTransportStats where
4484− parseJSON = withObject "NodeTransportStats" parse
4486− parse o = NodeTransportStats <$> o .: "tx_size_in_bytes"
4487− <*> o .: "tx_count"
4488− <*> o .: "rx_size_in_bytes"
4489− <*> o .: "rx_count"
4490− <*> o .: "server_open"
4492−instance FromJSON NodeFSStats where
4493− parseJSON = withObject "NodeFSStats" parse
4495− parse o = NodeFSStats <$> o .: "data"
4497− <*> (posixMS <$> o .: "timestamp")
4499−instance FromJSON NodeDataPathStats where
4500− parseJSON = withObject "NodeDataPathStats" parse
4503− NodeDataPathStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4504− <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4505− <*> o .:? "disk_io_size_in_bytes"
4506− <*> o .:? "disk_write_size_in_bytes"
4507− <*> o .:? "disk_read_size_in_bytes"
4508− <*> o .:? "disk_io_op"
4509− <*> o .:? "disk_writes"
4510− <*> o .:? "disk_reads"
4511− <*> o .: "available_in_bytes"
4512− <*> o .: "free_in_bytes"
4513− <*> o .: "total_in_bytes"
4519−newtype StringlyTypedDouble = StringlyTypedDouble { unStringlyTypedDouble :: Double }
4522−instance FromJSON StringlyTypedDouble where
4523− parseJSON = fmap StringlyTypedDouble . parseJSON . unStringlyTypeJSON
4526−instance FromJSON NodeFSTotalStats where
4527− parseJSON = withObject "NodeFSTotalStats" parse
4529− parse o = NodeFSTotalStats <$> (fmap unStringlyTypedDouble <$> o .:? "disk_service_time")
4530− <*> (fmap unStringlyTypedDouble <$> o .:? "disk_queue")
4531− <*> o .:? "disk_io_size_in_bytes"
4532− <*> o .:? "disk_write_size_in_bytes"
4533− <*> o .:? "disk_read_size_in_bytes"
4534− <*> o .:? "disk_io_op"
4535− <*> o .:? "disk_writes"
4536− <*> o .:? "disk_reads"
4537− <*> o .: "available_in_bytes"
4538− <*> o .: "free_in_bytes"
4539− <*> o .: "total_in_bytes"
4541−instance FromJSON NodeNetworkStats where
4542− parseJSON = withObject "NodeNetworkStats" parse
4546− NodeNetworkStats <$> tcp .: "out_rsts"
4547− <*> tcp .: "in_errs"
4548− <*> tcp .: "attempt_fails"
4549− <*> tcp .: "estab_resets"
4550− <*> tcp .: "retrans_segs"
4551− <*> tcp .: "out_segs"
4552− <*> tcp .: "in_segs"
4553− <*> tcp .: "curr_estab"
4554− <*> tcp .: "passive_opens"
4555− <*> tcp .: "active_opens"
4557−instance FromJSON NodeThreadPoolsStats where
4558− parseJSON = withObject "NodeThreadPoolsStats" parse
4560− parse o = NodeThreadPoolsStats <$> o .: "snapshot"
4564− <*> o .: "management"
4565− <*> o .:? "fetch_shard_store"
4566− <*> o .: "optimize"
4574− <*> o .:? "listener"
4575− <*> o .:? "fetch_shard_started"
4576− <*> o .: "percolate"
4577−instance FromJSON NodeThreadPoolStats where
4578− parseJSON = withObject "NodeThreadPoolStats" parse
4580− parse o = NodeThreadPoolStats <$> o .: "completed"
4582− <*> o .: "rejected"
4587−instance FromJSON NodeJVMStats where
4588− parseJSON = withObject "NodeJVMStats" parse
4591− bufferPools <- o .: "buffer_pools"
4592− mapped <- bufferPools .: "mapped"
4593− direct <- bufferPools .: "direct"
4595− collectors <- gc .: "collectors"
4596− oldC <- collectors .: "old"
4597− youngC <- collectors .: "young"
4598− threads <- o .: "threads"
4600− pools <- mem .: "pools"
4601− oldM <- pools .: "old"
4602− survivorM <- pools .: "survivor"
4603− youngM <- pools .: "young"
4604− NodeJVMStats <$> pure mapped
4608− <*> threads .: "peak_count"
4609− <*> threads .: "count"
4613− <*> mem .: "non_heap_committed_in_bytes"
4614− <*> mem .: "non_heap_used_in_bytes"
4615− <*> mem .: "heap_max_in_bytes"
4616− <*> mem .: "heap_committed_in_bytes"
4617− <*> mem .: "heap_used_percent"
4618− <*> mem .: "heap_used_in_bytes"
4619− <*> (unMS <$> o .: "uptime_in_millis")
4620− <*> (posixMS <$> o .: "timestamp")
4622−instance FromJSON JVMBufferPoolStats where
4623− parseJSON = withObject "JVMBufferPoolStats" parse
4625− parse o = JVMBufferPoolStats <$> o .: "total_capacity_in_bytes"
4626− <*> o .: "used_in_bytes"
4629−instance FromJSON JVMGCStats where
4630− parseJSON = withObject "JVMGCStats" parse
4632− parse o = JVMGCStats <$> (unMS <$> o .: "collection_time_in_millis")
4633− <*> o .: "collection_count"
4635−instance FromJSON JVMPoolStats where
4636− parseJSON = withObject "JVMPoolStats" parse
4638− parse o = JVMPoolStats <$> o .: "peak_max_in_bytes"
4639− <*> o .: "peak_used_in_bytes"
4640− <*> o .: "max_in_bytes"
4641− <*> o .: "used_in_bytes"
4643−instance FromJSON NodeProcessStats where
4644− parseJSON = withObject "NodeProcessStats" parse
4649− NodeProcessStats <$> mem .: "total_virtual_in_bytes"
4650− <*> mem .: "share_in_bytes"
4651− <*> mem .: "resident_in_bytes"
4652− <*> (unMS <$> cpu .: "total_in_millis")
4653− <*> (unMS <$> cpu .: "user_in_millis")
4654− <*> (unMS <$> cpu .: "sys_in_millis")
4655− <*> cpu .: "percent"
4656− <*> o .: "open_file_descriptors"
4657− <*> (posixMS <$> o .: "timestamp")
4659−instance FromJSON NodeOSStats where
4660− parseJSON = withObject "NodeOSStats" parse
4663− swap <- o .: "swap"
4666− load <- o .:? "load_average"
4667− NodeOSStats <$> swap .: "free_in_bytes"
4668− <*> swap .: "used_in_bytes"
4669− <*> mem .: "actual_used_in_bytes"
4670− <*> mem .: "actual_free_in_bytes"
4671− <*> mem .: "used_percent"
4672− <*> mem .: "free_percent"
4673− <*> mem .: "used_in_bytes"
4674− <*> mem .: "free_in_bytes"
4675− <*> cpu .: "stolen"
4681− <*> (unMS <$> o .: "uptime_in_millis")
4682− <*> (posixMS <$> o .: "timestamp")
4684−instance FromJSON LoadAvgs where
4685− parseJSON = withArray "LoadAvgs" parse
4687− parse v = case V.toList v of
4688− [one, five, fifteen] -> LoadAvgs <$> parseJSON one
4690− <*> parseJSON fifteen
4691− _ -> fail "Expecting a triple of Doubles"
4693−instance FromJSON NodeIndicesStats where
4694− parseJSON = withObject "NodeIndicesStats" parse
4697− let (.::) mv k = case mv of
4698− Just v -> Just <$> v .: k
4699− Nothing -> pure Nothing
4700− mRecovery <- o .:? "recovery"
4701− mQueryCache <- o .:? "query_cache"
4702− suggest <- o .: "suggest"
4703− translog <- o .: "translog"
4704− segments <- o .: "segments"
4705− completion <- o .: "completion"
4706− percolate <- o .: "percolate"
4707− fielddata <- o .: "fielddata"
4708− idCache <- o .: "id_cache"
4709− filterCache <- o .: "filter_cache"
4710− warmer <- o .: "warmer"
4711− flush <- o .: "flush"
4712− refresh <- o .: "refresh"
4713− merges <- o .: "merges"
4714− search <- o .: "search"
4715− getStats <- o .: "get"
4716− indexing <- o .: "indexing"
4717− store <- o .: "store"
4718− docs <- o .: "docs"
4719− NodeIndicesStats <$> (fmap unMS <$> mRecovery .:: "throttle_time_in_millis")
4720− <*> mRecovery .:: "current_as_target"
4721− <*> mRecovery .:: "current_as_source"
4722− <*> mQueryCache .:: "miss_count"
4723− <*> mQueryCache .:: "hit_count"
4724− <*> mQueryCache .:: "evictions"
4725− <*> mQueryCache .:: "memory_size_in_bytes"
4726− <*> suggest .: "current"
4727− <*> (unMS <$> suggest .: "time_in_millis")
4728− <*> suggest .: "total"
4729− <*> translog .: "size_in_bytes"
4730− <*> translog .: "operations"
4731− <*> segments .:? "fixed_bit_set_memory_in_bytes"
4732− <*> segments .: "version_map_memory_in_bytes"
4733− <*> segments .:? "index_writer_max_memory_in_bytes"
4734− <*> segments .: "index_writer_memory_in_bytes"
4735− <*> segments .: "memory_in_bytes"
4736− <*> segments .: "count"
4737− <*> completion .: "size_in_bytes"
4738− <*> percolate .: "queries"
4739− <*> percolate .: "memory_size_in_bytes"
4740− <*> percolate .: "current"
4741− <*> (unMS <$> percolate .: "time_in_millis")
4742− <*> percolate .: "total"
4743− <*> fielddata .: "evictions"
4744− <*> fielddata .: "memory_size_in_bytes"
4745− <*> idCache .: "memory_size_in_bytes"
4746− <*> filterCache .: "evictions"
4747− <*> filterCache .: "memory_size_in_bytes"
4748− <*> (unMS <$> warmer .: "total_time_in_millis")
4749− <*> warmer .: "total"
4750− <*> warmer .: "current"
4751− <*> (unMS <$> flush .: "total_time_in_millis")
4752− <*> flush .: "total"
4753− <*> (unMS <$> refresh .: "total_time_in_millis")
4754− <*> refresh .: "total"
4755− <*> merges .: "total_size_in_bytes"
4756− <*> merges .: "total_docs"
4757− <*> (unMS <$> merges .: "total_time_in_millis")
4758− <*> merges .: "total"
4759− <*> merges .: "current_size_in_bytes"
4760− <*> merges .: "current_docs"
4761− <*> merges .: "current"
4762− <*> search .: "fetch_current"
4763− <*> (unMS <$> search .: "fetch_time_in_millis")
4764− <*> search .: "fetch_total"
4765− <*> search .: "query_current"
4766− <*> (unMS <$> search .: "query_time_in_millis")
4767− <*> search .: "query_total"
4768− <*> search .: "open_contexts"
4769− <*> getStats .: "current"
4770− <*> (unMS <$> getStats .: "missing_time_in_millis")
4771− <*> getStats .: "missing_total"
4772− <*> (unMS <$> getStats .: "exists_time_in_millis")
4773− <*> getStats .: "exists_total"
4774− <*> (unMS <$> getStats .: "time_in_millis")
4775− <*> getStats .: "total"
4776− <*> (fmap unMS <$> indexing .:? "throttle_time_in_millis")
4777− <*> indexing .:? "is_throttled"
4778− <*> indexing .:? "noop_update_total"
4779− <*> indexing .: "delete_current"
4780− <*> (unMS <$> indexing .: "delete_time_in_millis")
4781− <*> indexing .: "delete_total"
4782− <*> indexing .: "index_current"
4783− <*> (unMS <$> indexing .: "index_time_in_millis")
4784− <*> indexing .: "index_total"
4785− <*> (unMS <$> store .: "throttle_time_in_millis")
4786− <*> store .: "size_in_bytes"
4787− <*> docs .: "deleted"
4788− <*> docs .: "count"
4790−instance FromJSON NodeBreakersStats where
4791− parseJSON = withObject "NodeBreakersStats" parse
4793− parse o = NodeBreakersStats <$> o .: "parent"
4795− <*> o .: "fielddata"
4797−parseNodeStats :: FullNodeId -> Object -> Parser NodeStats
4798−parseNodeStats fnid o = do
4799− NodeStats <$> o .: "name"
4801− <*> o .:? "breakers"
4803− <*> o .: "transport"
4806− <*> o .: "thread_pool"
4812−parseNodeInfo :: FullNodeId -> Object -> Parser NodeInfo
4813−parseNodeInfo nid o =
4814− NodeInfo <$> o .: "http_address"
4819− <*> o .: "transport_address"
4824− <*> o .: "transport"
4826− <*> o .: "thread_pool"
4830− <*> o .: "settings"
4832−instance FromJSON NodePluginInfo where
4833− parseJSON = withObject "NodePluginInfo" parse
4835− parse o = NodePluginInfo <$> o .: "site"
4837− <*> o .: "description"
4841−instance FromJSON NodeHTTPInfo where
4842− parseJSON = withObject "NodeHTTPInfo" parse
4844− parse o = NodeHTTPInfo <$> o .: "max_content_length_in_bytes"
4845− <*> parseJSON (Object o)
4847−instance FromJSON BoundTransportAddress where
4848− parseJSON = withObject "BoundTransportAddress" parse
4850− parse o = BoundTransportAddress <$> o .: "publish_address"
4851− <*> o .: "bound_address"
4853−instance FromJSON NodeOSInfo where
4854− parseJSON = withObject "NodeOSInfo" parse
4857− swap <- o .: "swap"
4859− NodeOSInfo <$> swap .: "total_in_bytes"
4860− <*> mem .: "total_in_bytes"
4862− <*> o .: "available_processors"
4863− <*> (unMS <$> o .: "refresh_interval_in_millis")
4866−instance FromJSON CPUInfo where
4867− parseJSON = withObject "CPUInfo" parse
4869− parse o = CPUInfo <$> o .: "cache_size_in_bytes"
4870− <*> o .: "cores_per_socket"
4871− <*> o .: "total_sockets"
4872− <*> o .: "total_cores"
4877−instance FromJSON NodeProcessInfo where
4878− parseJSON = withObject "NodeProcessInfo" parse
4880− parse o = NodeProcessInfo <$> o .: "mlockall"
4881− <*> o .: "max_file_descriptors"
4883− <*> (unMS <$> o .: "refresh_interval_in_millis")
4885−instance FromJSON NodeJVMInfo where
4886− parseJSON = withObject "NodeJVMInfo" parse
4888− parse o = NodeJVMInfo <$> o .: "memory_pools"
4889− <*> o .: "gc_collectors"
4891− <*> (posixMS <$> o .: "start_time_in_millis")
4892− <*> o .: "vm_vendor"
4893− <*> o .: "vm_version"
4895− <*> (unJVMVersion <$> o .: "version")
4898−instance FromJSON JVMVersion where
4899− parseJSON (String t) =
4900− JVMVersion <$> parseJSON (String (T.replace "_" "." t))
4901− parseJSON v = JVMVersion <$> parseJSON v
4903−instance FromJSON JVMMemoryInfo where
4904− parseJSON = withObject "JVMMemoryInfo" parse
4906− parse o = JVMMemoryInfo <$> o .: "direct_max_in_bytes"
4907− <*> o .: "non_heap_max_in_bytes"
4908− <*> o .: "non_heap_init_in_bytes"
4909− <*> o .: "heap_max_in_bytes"
4910− <*> o .: "heap_init_in_bytes"
4912−instance FromJSON NodeThreadPoolsInfo where
4913− parseJSON = withObject "NodeThreadPoolsInfo" parse
4915− parse o = NodeThreadPoolsInfo <$> o .: "refresh"
4916− <*> o .: "management"
4917− <*> o .: "percolate"
4918− <*> o .:? "listener"
4919− <*> o .:? "fetch_shard_started"
4923− <*> o .: "optimize"
4927− <*> o .: "snapshot"
4929− <*> o .:? "fetch_shard_store"
4933−instance FromJSON NodeThreadPoolInfo where
4934− parseJSON = withObject "NodeThreadPoolInfo" parse
4937− ka <- maybe (return Nothing) (fmap Just . parseStringInterval) =<< o .:? "keep_alive"
4938− NodeThreadPoolInfo <$> (parseJSON . unStringlyTypeJSON =<< o .: "queue_size")
4944−parseStringInterval :: (Monad m) => String -> m NominalDiffTime
4945−parseStringInterval s = case span isNumber s of
4946− ("", _) -> fail "Invalid interval"
4947− (nS, unitS) -> case (readMay nS, readMay unitS) of
4948− (Just n, Just unit) -> return (fromInteger (n * unitNDT unit))
4949− (Nothing, _) -> fail "Invalid interval number"
4950− (_, Nothing) -> fail "Invalid interval unit"
4952− unitNDT Seconds = 1
4953− unitNDT Minutes = 60
4954− unitNDT Hours = 60 * 60
4955− unitNDT Days = 24 * 60 * 60
4956− unitNDT Weeks = 7 * 24 * 60 * 60
4958−instance FromJSON ThreadPoolSize where
4959− parseJSON v = parseAsNumber v <|> parseAsString v
4961− parseAsNumber = parseAsInt <=< parseJSON
4962− parseAsInt (-1) = return ThreadPoolUnbounded
4964− | n >= 0 = return (ThreadPoolBounded n)
4965− | otherwise = fail "Thread pool size must be >= -1."
4966− parseAsString = withText "ThreadPoolSize" $ \t ->
4967− case first (readMay . T.unpack) (T.span isNumber t) of
4968− (Just n, "k") -> return (ThreadPoolBounded (n * 1000))
4969− (Just n, "") -> return (ThreadPoolBounded n)
4970− _ -> fail ("Invalid thread pool size " <> T.unpack t)
4972−instance FromJSON ThreadPoolType where
4973− parseJSON = withText "ThreadPoolType" parse
4975− parse "scaling" = return ThreadPoolScaling
4976− parse "fixed" = return ThreadPoolFixed
4977− parse "cached" = return ThreadPoolCached
4978− parse e = fail ("Unexpected thread pool type" <> T.unpack e)
4980−instance FromJSON NodeTransportInfo where
4981− parseJSON = withObject "NodeTransportInfo" parse
4983− parse o = NodeTransportInfo <$> (maybe (return mempty) parseProfiles =<< o .:? "profiles")
4984− <*> parseJSON (Object o)
4985− parseProfiles (Object o) | HM.null o = return []
4986− parseProfiles v@(Array _) = parseJSON v
4987− parseProfiles Null = return []
4988− parseProfiles _ = fail "Could not parse profiles"
4990−instance FromJSON NodeNetworkInfo where
4991− parseJSON = withObject "NodeNetworkInfo" parse
4993− parse o = NodeNetworkInfo <$> o .: "primary_interface"
4994− <*> (unMS <$> o .: "refresh_interval_in_millis")
4997−instance FromJSON NodeNetworkInterface where
4998− parseJSON = withObject "NodeNetworkInterface" parse
5000− parse o = NodeNetworkInterface <$> o .: "mac_address"
5004−newtype MaybeNA a = MaybeNA { unMaybeNA :: Maybe a }
5005− deriving (Show, Eq)
5007−instance FromJSON a => FromJSON (MaybeNA a) where
5008− parseJSON (String "NA") = pure $ MaybeNA Nothing
5009− parseJSON o = MaybeNA . Just <$> parseJSON o
5012−data Suggest = Suggest { suggestText :: Text
5013− , suggestName :: Text
5014− , suggestType :: SuggestType
5016− deriving (Show, Generic, Eq, Read, Typeable)
5018−instance ToJSON Suggest where
5019− toJSON Suggest{..} = object [ "text" .= suggestText
5020− , suggestName .= suggestType
5023−instance FromJSON Suggest where
5024− parseJSON (Object o) = do
5025− suggestText' <- o .: "text"
5026− let dropTextList = HM.toList $ HM.filterWithKey (\x _ -> x /= "text") o
5027− suggestName' <- case dropTextList of
5028− [(x, _)] -> return x
5029− _ -> fail "error parsing Suggest field name"
5030− suggestType' <- o .: suggestName'
5031− return $ Suggest suggestText' suggestName' suggestType'
5032− parseJSON x = typeMismatch "Suggest" x
5034−data SuggestType = SuggestTypePhraseSuggester PhraseSuggester
5035− deriving (Show, Generic, Eq, Read, Typeable)
5037−instance ToJSON SuggestType where
5038− toJSON (SuggestTypePhraseSuggester x) = object ["phrase" .= x]
5040−instance FromJSON SuggestType where
5041− parseJSON = withObject "SuggestType" parse
5042− where parse o = phraseSuggester `taggedWith` "phrase"
5043− where taggedWith parser k = parser =<< o .: k
5044− phraseSuggester = pure . SuggestTypePhraseSuggester
5046−data PhraseSuggester =
5047− PhraseSuggester { phraseSuggesterField :: FieldName
5048− , phraseSuggesterGramSize :: Maybe Int
5049− , phraseSuggesterRealWordErrorLikelihood :: Maybe Int
5050− , phraseSuggesterConfidence :: Maybe Int
5051− , phraseSuggesterMaxErrors :: Maybe Int
5052− , phraseSuggesterSeparator :: Maybe Text
5053− , phraseSuggesterSize :: Maybe Size
5054− , phraseSuggesterAnalyzer :: Maybe Analyzer
5055− , phraseSuggesterShardSize :: Maybe Int
5056− , phraseSuggesterHighlight :: Maybe PhraseSuggesterHighlighter
5057− , phraseSuggesterCollate :: Maybe PhraseSuggesterCollate
5058− , phraseSuggesterCandidateGenerators :: [DirectGenerators]
5060− deriving (Show, Generic, Eq, Read, Typeable)
5062−instance ToJSON PhraseSuggester where
5063− toJSON PhraseSuggester{..} = omitNulls [ "field" .= phraseSuggesterField
5064− , "gram_size" .= phraseSuggesterGramSize
5065− , "real_word_error_likelihood" .= phraseSuggesterRealWordErrorLikelihood
5066− , "confidence" .= phraseSuggesterConfidence
5067− , "max_errors" .= phraseSuggesterMaxErrors
5068− , "separator" .= phraseSuggesterSeparator
5069− , "size" .= phraseSuggesterSize
5070− , "analyzer" .= phraseSuggesterAnalyzer
5071− , "shard_size" .= phraseSuggesterShardSize
5072− , "highlight" .= phraseSuggesterHighlight
5073− , "collate" .= phraseSuggesterCollate
5074− , "direct_generator" .= phraseSuggesterCandidateGenerators
5077−instance FromJSON PhraseSuggester where
5078− parseJSON = withObject "PhraseSuggester" parse
5079− where parse o = PhraseSuggester
5081− <*> o .:? "gram_size"
5082− <*> o .:? "real_word_error_likelihood"
5083− <*> o .:? "confidence"
5084− <*> o .:? "max_errors"
5085− <*> o .:? "separator"
5087− <*> o .:? "analyzer"
5088− <*> o .:? "shard_size"
5089− <*> o .:? "highlight"
5090− <*> o .:? "collate"
5091− <*> o .:? "direct_generator" .!= []
5093−mkPhraseSuggester :: FieldName -> PhraseSuggester
5094−mkPhraseSuggester fName =
5095− PhraseSuggester fName Nothing Nothing Nothing Nothing Nothing Nothing
5096− Nothing Nothing Nothing Nothing []
5098−data PhraseSuggesterHighlighter =
5099− PhraseSuggesterHighlighter { phraseSuggesterHighlighterPreTag :: Text
5100− , phraseSuggesterHighlighterPostTag :: Text
5102− deriving (Show, Generic, Eq, Read, Typeable)
5104−instance ToJSON PhraseSuggesterHighlighter where
5105− toJSON PhraseSuggesterHighlighter{..} =
5106− object [ "pre_tag" .= phraseSuggesterHighlighterPreTag
5107− , "post_tag" .= phraseSuggesterHighlighterPostTag
5110−instance FromJSON PhraseSuggesterHighlighter where
5111− parseJSON = withObject "PhraseSuggesterHighlighter" parse
5112− where parse o = PhraseSuggesterHighlighter
5114− <*> o .: "post_tag"
5116−data PhraseSuggesterCollate =
5117− PhraseSuggesterCollate { phraseSuggesterCollateTemplateQuery :: TemplateQueryInline
5118− , phraseSuggesterCollatePrune :: Bool
5120− deriving (Show, Generic, Eq, Read, Typeable)
5122−instance ToJSON PhraseSuggesterCollate where
5123− toJSON PhraseSuggesterCollate{..} = object [ "query" .= object
5124− [ "inline" .= (inline phraseSuggesterCollateTemplateQuery)
5126− , "params" .= (params phraseSuggesterCollateTemplateQuery)
5127− , "prune" .= phraseSuggesterCollatePrune
5130−instance FromJSON PhraseSuggesterCollate where
5131− parseJSON (Object o) = do
5132− query' <- o .: "query"
5133− inline' <- query' .: "inline"
5134− params' <- o .: "params"
5135− prune' <- o .:? "prune" .!= False
5136− return $ PhraseSuggesterCollate (TemplateQueryInline inline' params') prune'
5137− parseJSON x = typeMismatch "PhraseSuggesterCollate" x
5139−data SuggestOptions =
5140− SuggestOptions { suggestOptionsText :: Text
5141− , suggestOptionsScore :: Double
5142− , suggestOptionsFreq :: Maybe Int
5143− , suggestOptionsHighlighted :: Maybe Text
5145− deriving (Eq, Read, Show)
5147−instance FromJSON SuggestOptions where
5148− parseJSON = withObject "SuggestOptions" parse
5149− where parse o = SuggestOptions
5153− <*> o .:? "highlighted"
5155−data SuggestResponse =
5156− SuggestResponse { suggestResponseText :: Text
5157− , suggestResponseOffset :: Int
5158− , suggestResponseLength :: Int
5159− , suggestResponseOptions :: [SuggestOptions]
5161− deriving (Eq, Read, Show)
5163−instance FromJSON SuggestResponse where
5164− parseJSON = withObject "SuggestResponse" parse
5165− where parse o = SuggestResponse
5171−data NamedSuggestionResponse =
5172− NamedSuggestionResponse { nsrName :: Text
5173− , nsrResponses :: [SuggestResponse]
5175− deriving (Eq, Read, Show)
5177−instance FromJSON NamedSuggestionResponse where
5178− parseJSON (Object o) = do
5179− suggestionName' <- case HM.toList o of
5180− [(x, _)] -> return x
5181− _ -> fail "error parsing NamedSuggestionResponse name"
5182− suggestionResponses' <- o .: suggestionName'
5183− return $ NamedSuggestionResponse suggestionName' suggestionResponses'
5185− parseJSON x = typeMismatch "NamedSuggestionResponse" x
5187−data DirectGeneratorSuggestModeTypes = DirectGeneratorSuggestModeMissing
5188− | DirectGeneratorSuggestModePopular
5189− | DirectGeneratorSuggestModeAlways
5190− deriving (Show, Eq, Read, Generic, Typeable)
5192−instance ToJSON DirectGeneratorSuggestModeTypes where
5193− toJSON DirectGeneratorSuggestModeMissing = "missing"
5194− toJSON DirectGeneratorSuggestModePopular = "popular"
5195− toJSON DirectGeneratorSuggestModeAlways = "always"
5197−instance FromJSON DirectGeneratorSuggestModeTypes where
5198− parseJSON = withText "DirectGeneratorSuggestModeTypes" parse
5199− where parse "missing" = pure DirectGeneratorSuggestModeMissing
5200− parse "popular" = pure DirectGeneratorSuggestModePopular
5201− parse "always" = pure DirectGeneratorSuggestModeAlways
5202− parse f = fail ("Unexpected DirectGeneratorSuggestModeTypes: " <> show f)
5204−data DirectGenerators = DirectGenerators
5205− { directGeneratorsField :: FieldName
5206− , directGeneratorsSize :: Maybe Int
5207− , directGeneratorSuggestMode :: DirectGeneratorSuggestModeTypes
5208− , directGeneratorMaxEdits :: Maybe Double
5209− , directGeneratorPrefixLength :: Maybe Int
5210− , directGeneratorMinWordLength :: Maybe Int
5211− , directGeneratorMaxInspections :: Maybe Int
5212− , directGeneratorMinDocFreq :: Maybe Double
5213− , directGeneratorMaxTermFreq :: Maybe Double
5214− , directGeneratorPreFilter :: Maybe Text
5215− , directGeneratorPostFilter :: Maybe Text
5217− deriving (Show, Eq, Read, Generic, Typeable)
5220−instance ToJSON DirectGenerators where
5221− toJSON DirectGenerators{..} = omitNulls [ "field" .= directGeneratorsField
5222− , "size" .= directGeneratorsSize
5223− , "suggest_mode" .= directGeneratorSuggestMode
5224− , "max_edits" .= directGeneratorMaxEdits
5225− , "prefix_length" .= directGeneratorPrefixLength
5226− , "min_word_length" .= directGeneratorMinWordLength
5227− , "max_inspections" .= directGeneratorMaxInspections
5228− , "min_doc_freq" .= directGeneratorMinDocFreq
5229− , "max_term_freq" .= directGeneratorMaxTermFreq
5230− , "pre_filter" .= directGeneratorPreFilter
5231− , "post_filter" .= directGeneratorPostFilter
5234−instance FromJSON DirectGenerators where
5235− parseJSON = withObject "DirectGenerators" parse
5236− where parse o = DirectGenerators
5239− <*> o .: "suggest_mode"
5240− <*> o .:? "max_edits"
5241− <*> o .:? "prefix_length"
5242− <*> o .:? "min_word_length"
5243− <*> o .:? "max_inspections"
5244− <*> o .:? "min_doc_freq"
5245− <*> o .:? "max_term_freq"
5246− <*> o .:? "pre_filter"
5247− <*> o .:? "post_filter"
5249−mkDirectGenerators :: FieldName -> DirectGenerators
5250−mkDirectGenerators fn = DirectGenerators fn Nothing DirectGeneratorSuggestModeMissing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing