@@ -1,8 +1,8 @@
1−{-# LANGUAGE DeriveGeneric #-}
21{-# LANGUAGE FlexibleContexts #-}
32{-# LANGUAGE FlexibleInstances #-}
43{-# LANGUAGE GeneralizedNewtypeDeriving #-}
54{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE NamedFieldPuns #-}
66{-# LANGUAGE OverloadedStrings #-}
77{-# LANGUAGE RecordWildCards #-}
88{-# LANGUAGE UndecidableInstances #-}
@@ -10,11 +10,11 @@
1010-------------------------------------------------------------------------------
1111-- |
1212-- Module : Database.Bloodhound.Types
13−-- Copyright : (C) 2014 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
1414-- License : BSD-style (see the file LICENSE)
1515-- Maintainer : Chris Allen <cma@bitemyapp.com
1616-- Stability : provisional
17−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
1818--
1919-- Data types for describing actions and data structures performed to interact
2020-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -42,24 +42,41 @@ module Database.Bloodhound.Types
4242 , mkTermsAggregation
4343 , mkTermsScriptAggregation
4444 , mkDateHistogram
45+ , mkCardinalityAggregation
4546 , mkDocVersion
47+ , mkStatsAggregation
48+ , mkExtendedStatsAggregation
4649 , docVersionNumber
50+ , toMissing
4751 , toTerms
4852 , toDateHistogram
53+ , toTopHits
4954 , omitNulls
5055 , BH(..)
5156 , runBH
52− , BHEnv(..)
57+ , BHEnv
58+ , bhServer
59+ , bhManager
60+ , bhRequestHook
61+ , mkBHEnv
5362 , MonadBH(..)
5463 , Version(..)
64+ , VersionNumber(..)
65+ , MaybeNA(..)
66+ , BuildHash(..)
5567 , Status(..)
5668 , Existence(..)
5769 , NullValue(..)
5870 , IndexSettings(..)
59− , IndexSettingUpdate(..)
71+ , UpdatableIndexSetting(..)
72+ , IndexSettingsSummary(..)
6073 , AllocationPolicy(..)
74+ , Compression(..)
6175 , ReplicaBounds(..)
6276 , Bytes(..)
77+ , gigabytes
78+ , megabytes
79+ , kilobytes
6380 , FSType(..)
6481 , InitialShardCount(..)
6582 , NodeAttrFilter(..)
@@ -70,6 +87,18 @@ module Database.Bloodhound.Types
7087 , Reply
7188 , EsResult(..)
7289 , EsResultFound(..)
90+ , EsError(..)
91+ , EsProtocolException(..)
92+ , IndexAlias(..)
93+ , IndexAliasName(..)
94+ , IndexAliasAction(..)
95+ , IndexAliasCreate(..)
96+ , IndexAliasSummary(..)
97+ , IndexAliasesSummary(..)
98+ , AliasRouting(..)
99+ , SearchAliasRouting(..)
100+ , IndexAliasRouting(..)
101+ , RoutingValue(..)
73102 , DocVersion
74103 , ExternalDocVersion(..)
75104 , VersionControl(..)
@@ -79,7 +108,7 @@ module Database.Bloodhound.Types
79108 , Search(..)
80109 , SearchType(..)
81110 , SearchResult(..)
82− , ScrollId
111+ , ScrollId(..)
83112 , SearchHits(..)
84113 , TrackSortScores
85114 , From(..)
@@ -91,8 +120,8 @@ module Database.Bloodhound.Types
91120 , Pattern(..)
92121 , ShardResult(..)
93122 , Hit(..)
123+ , HitFields(..)
94124 , Filter(..)
95− , Seminearring(..)
96125 , BoolMatch(..)
97126 , Term(..)
98127 , GeoPoint(..)
@@ -119,8 +148,22 @@ module Database.Bloodhound.Types
119148 , RegexpFlags(..)
120149 , RegexpFlag(..)
121150 , FieldName(..)
151+ , ScriptFields(..)
152+ , ScriptFieldName
153+ , ScriptFieldValue
122154 , Script(..)
155+ , ScriptLanguage(..)
156+ , ScriptInline(..)
157+ , ScriptId(..)
158+ , ScriptParams(..)
159+ , ScriptParamName
160+ , ScriptParamValue
123161 , IndexName(..)
162+ , IndexSelection(..)
163+ , NodeSelection(..)
164+ , NodeSelector(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
124167 , TemplateName(..)
125168 , TemplatePattern(..)
126169 , MappingName(..)
@@ -144,8 +187,19 @@ module Database.Bloodhound.Types
144187 , BoolQuery(..)
145188 , BoostingQuery(..)
146189 , CommonTermsQuery(..)
190+ , FunctionScoreQuery(..)
191+ , BoostMode(..)
192+ , ScoreMode(..)
193+ , FunctionScoreFunctions(..)
194+ , ComponentFunctionScoreFunction(..)
195+ , FunctionScoreFunction(..)
196+ , Weight(..)
197+ , Seed(..)
198+ , FieldValueFactor(..)
199+ , Factor(..)
200+ , FactorModifier(..)
201+ , FactorMissingFieldValue(..)
147202 , DisMaxQuery(..)
148− , FilteredQuery(..)
149203 , FuzzyLikeThisQuery(..)
150204 , FuzzyLikeFieldQuery(..)
151205 , FuzzyQuery(..)
@@ -161,10 +215,16 @@ module Database.Bloodhound.Types
161215 , RangeQuery(..)
162216 , RegexpQuery(..)
163217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
220+ , WildcardQuery(..)
164221 , BooleanOperator(..)
165222 , ZeroTermsQuery(..)
166223 , CutoffFrequency(..)
167224 , Analyzer(..)
225+ , Tokenizer(..)
226+ , TokenFilter(..)
227+ , CharFilter(..)
168228 , MaxExpansions(..)
169229 , Lenient(..)
170230 , MatchQueryType(..)
@@ -211,16 +271,118 @@ module Database.Bloodhound.Types
211271 , CollectionMode(..)
212272 , TermOrder(..)
213273 , TermInclusion(..)
274+ , SnapshotRepoSelection(..)
275+ , GenericSnapshotRepo(..)
276+ , SnapshotRepo(..)
277+ , SnapshotRepoConversionError(..)
278+ , SnapshotRepoType(..)
279+ , GenericSnapshotRepoSettings(..)
280+ , SnapshotRepoUpdateSettings(..)
281+ , defaultSnapshotRepoUpdateSettings
282+ , SnapshotRepoName(..)
283+ , SnapshotRepoPattern(..)
284+ , SnapshotVerification(..)
285+ , SnapshotNodeVerification(..)
286+ , FullNodeId(..)
287+ , NodeName(..)
288+ , ClusterName(..)
289+ , NodesInfo(..)
290+ , NodesStats(..)
291+ , NodeStats(..)
292+ , NodeBreakersStats(..)
293+ , NodeBreakerStats(..)
294+ , NodeHTTPStats(..)
295+ , NodeTransportStats(..)
296+ , NodeFSStats(..)
297+ , NodeDataPathStats(..)
298+ , NodeFSTotalStats(..)
299+ , NodeNetworkStats(..)
300+ , NodeThreadPoolsStats(..)
301+ , NodeThreadPoolStats(..)
302+ , NodeJVMStats(..)
303+ , JVMBufferPoolStats(..)
304+ , JVMGCStats(..)
305+ , JVMPoolStats(..)
306+ , NodeProcessStats(..)
307+ , NodeOSStats(..)
308+ , LoadAvgs(..)
309+ , NodeIndicesStats(..)
310+ , EsAddress(..)
311+ , PluginName(..)
312+ , NodeInfo(..)
313+ , NodePluginInfo(..)
314+ , NodeHTTPInfo(..)
315+ , NodeTransportInfo(..)
316+ , BoundTransportAddress(..)
317+ , NodeNetworkInfo(..)
318+ , MacAddress(..)
319+ , NetworkInterfaceName(..)
320+ , NodeNetworkInterface(..)
321+ , NodeThreadPoolsInfo(..)
322+ , NodeThreadPoolInfo(..)
323+ , ThreadPoolSize(..)
324+ , ThreadPoolType(..)
325+ , NodeJVMInfo(..)
326+ , JVMMemoryPool(..)
327+ , JVMGCCollector(..)
328+ , JVMMemoryInfo(..)
329+ , PID(..)
330+ , NodeOSInfo(..)
331+ , CPUInfo(..)
332+ , NodeProcessInfo(..)
333+ , FsSnapshotRepo(..)
334+ , SnapshotCreateSettings(..)
335+ , defaultSnapshotCreateSettings
336+ , SnapshotSelection(..)
337+ , SnapshotPattern(..)
338+ , SnapshotInfo(..)
339+ , SnapshotShardFailure(..)
340+ , ShardId(..)
341+ , SnapshotName(..)
342+ , SnapshotState(..)
343+ , SnapshotRestoreSettings(..)
344+ , defaultSnapshotRestoreSettings
345+ , RestoreRenamePattern(..)
346+ , RestoreRenameToken(..)
347+ , RRGroupRefNum
348+ , rrGroupRefNum
349+ , mkRRGroupRefNum
350+ , RestoreIndexSettings(..)
351+ , Suggest(..)
352+ , SuggestType(..)
353+ , PhraseSuggester(..)
354+ , PhraseSuggesterHighlighter(..)
355+ , PhraseSuggesterCollate(..)
356+ , mkPhraseSuggester
357+ , SuggestOptions(..)
358+ , SuggestResponse(..)
359+ , NamedSuggestionResponse(..)
360+ , DirectGenerators(..)
361+ , mkDirectGenerators
362+ , DirectGeneratorSuggestModeTypes (..)
214363
215364 , Aggregation(..)
216365 , Aggregations
217366 , AggregationResults
367+ , BucketValue(..)
218368 , Bucket(..)
219369 , BucketAggregation(..)
220370 , TermsAggregation(..)
371+ , MissingAggregation(..)
221372 , ValueCountAggregation(..)
222373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
223376 , DateHistogramAggregation(..)
377+ , DateRangeAggregation(..)
378+ , DateRangeAggRange(..)
379+ , DateMathExpr(..)
380+ , DateMathAnchor(..)
381+ , DateMathModifier(..)
382+ , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
385+ , SearchAfterKey
224386
225387 , Highlights(..)
226388 , FieldHighlight(..)
@@ -234,573 +396,36 @@ module Database.Bloodhound.Types
234396 , HighlightTag(..)
235397 , HitHighlight
236398
399+ , MissingResult(..)
237400 , TermsResult(..)
238401 , DateHistogramResult(..)
239− ) where
240−
241−import Control.Applicative
242−import Control.Monad.Catch
243−import Control.Monad.Except
244−import Control.Monad.Reader
245−import Control.Monad.State
246−import Control.Monad.Writer
247−import Data.Aeson
248−import Data.Aeson.Types (Pair, emptyObject, parseMaybe)
249−import qualified Data.ByteString.Lazy.Char8 as L
250−import qualified Data.HashMap.Strict as HM (union)
251−import Data.List (foldl', nub)
252−import Data.List.NonEmpty (NonEmpty (..), toList)
253−import qualified Data.Map.Strict as M
254−import Data.Maybe
255−import Data.Text (Text)
256−import qualified Data.Text as T
257−import Data.Time.Clock (UTCTime, NominalDiffTime)
258−import qualified Data.Vector as V
259−import GHC.Enum
260−import GHC.Generics (Generic)
261−import Network.HTTP.Client
262−import qualified Network.HTTP.Types.Method as NHTM
263−
264−import Database.Bloodhound.Types.Class
265−
266−-- $setup
267−-- >>> :set -XOverloadedStrings
268−-- >>> import Database.Bloodhound
269−-- >>> let testServer = (Server "http://localhost:9200")
270−-- >>> let testIndex = IndexName "twitter"
271−-- >>> let testMapping = MappingName "tweet"
272−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
273−
274−-- defaultIndexSettings is exported by Database.Bloodhound as well
275−-- no trailing slashes in servers, library handles building the path.
276−
277−{-| Common environment for Elasticsearch calls. Connections will be
278− pipelined according to the provided HTTP connection manager.
279−-}
280−data BHEnv = BHEnv { bhServer :: Server
281− , bhManager :: Manager
282− }
283−
284−{-| All API calls to Elasticsearch operate within
285− MonadBH. The idea is that it can be easily embedded in your
286− own monad transformer stack. A default instance for a ReaderT and
287− alias 'BH' is provided for the simple case.
288−-}
289−class (Functor m, Applicative m, MonadIO m) => MonadBH m where
290− getBHEnv :: m BHEnv
291−
292−newtype BH m a = BH {
293− unBH :: ReaderT BHEnv m a
294− } deriving ( Functor
295− , Applicative
296− , Monad
297− , MonadIO
298− , MonadState s
299− , MonadWriter w
300− , MonadError e
301− , Alternative
302− , MonadPlus
303− , MonadFix
304− , MonadThrow
305− , MonadCatch
306− , MonadMask)
307−
308−instance MonadTrans BH where
309− lift = BH . lift
310−
311−instance (MonadReader r m) => MonadReader r (BH m) where
312− ask = lift ask
313− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
314− local f (m r)
315−
316−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
317− getBHEnv = BH getBHEnv
318−
319−
320−instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where
321− getBHEnv = ask
322−
323−runBH :: BHEnv -> BH m a -> m a
324−runBH e f = runReaderT (unBH f) e
325−
326−{-| 'Version' is embedded in 'Status' -}
327−data Version = Version { number :: Text
328− , build_hash :: Text
329− , build_timestamp :: UTCTime
330− , build_snapshot :: Bool
331− , lucene_version :: Text } deriving (Eq, Show, Generic)
332−
333−{-| 'Status' is a data type for describing the JSON body returned by
334− Elasticsearch when you query its status. This was deprecated in 1.2.0.
335−
336− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
337−-}
338−
339−data Status = Status { ok :: Maybe Bool
340− , status :: Int
341− , name :: Text
342− , version :: Version
343− , tagline :: Text } deriving (Eq, Show)
344−
345−{-| 'IndexSettings' is used to configure the shards and replicas when you create
346− an Elasticsearch Index.
347−
348− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
349−-}
350−
351−data IndexSettings =
352− IndexSettings { indexShards :: ShardCount
353− , indexReplicas :: ReplicaCount } deriving (Eq, Show)
354−
355−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
356−defaultIndexSettings :: IndexSettings
357−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
358−
359−{-| 'IndexSettingUpdate' is used to update an index' settings piecemeal.
360−
361− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
362−-}
363−data IndexSettingUpdate = NumberOfReplicas Int
364− | AutoExpandReplicas ReplicaBounds
365− | BlocksReadOnly Bool
366− | BlocksRead Bool
367− | BlocksWrite Bool
368− | BlocksMetaData Bool
369− | RefreshInterval NominalDiffTime
370− | IndexConcurrency Int
371− | FailOnMergeFailure Bool
372− | TranslogFlushThresholdOps Int
373− | TranslogFlushThresholdSize Bytes
374− | TranslogFlushThresholdPeriod NominalDiffTime
375− | TranslogDisableFlush Bool
376− | CacheFilterMaxSize (Maybe Bytes)
377− | CacheFilterExpire (Maybe NominalDiffTime)
378− | GatewaySnapshotInterval NominalDiffTime
379− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
380− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
381− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
382− | RoutingAllocationDisable Bool
383− | RoutingAllocationDisableNew Bool
384− | RoutingAllocationDisableReplica Bool
385− | RoutingAllocationEnable AllocationPolicy
386− | RoutingAllocationShardsPerNode ShardCount
387− | RecoveryInitialShards InitialShardCount
388− | GCDeletes NominalDiffTime
389− | TTLDisablePurge Bool
390− | TranslogFSType FSType
391− | IndexCompoundFormat CompoundFormat
392− | IndexCompoundOnFlush Bool
393− | WarmerEnabled Bool
394− --TODO: figure out allocation options
395−
396−data AllocationPolicy = AllocAll
397− | AllocPrimaries
398− | AllocNewPrimaries
399− | AllocNone
400−
401−data ReplicaBounds = ReplicasBounded Int Int
402− | ReplicasLowerBounded Int
403− | ReplicasUnbounded
404−
405−newtype Bytes = Bytes Int deriving (Eq, Show, Ord, ToJSON)
406−
407−data FSType = FSSimple
408− | FSBuffered deriving (Eq, Show, Ord)
409−
410−data InitialShardCount = QuorumShards
411− | QuorumMinus1Shards
412− | FullShards
413− | FullMinus1Shards
414− | ExplicitShards Int
415−
416−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
417− , nodeAttrFilterValues :: NonEmpty Text}
418−
419−newtype NodeAttrName = NodeAttrName Text
420−
421−data CompoundFormat = CompoundFileFormat Bool
422− | MergeSegmentVsTotalIndex Double
423− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
424−
425−newtype NominalDiffTimeJSON = NominalDiffTimeJSON NominalDiffTime
426−
427−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
428−type Reply = Network.HTTP.Client.Response L.ByteString
429−type Method = NHTM.Method
430−
431−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
432−
433− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
434−-}
435−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show)
436−
437−data FieldType = GeoPointType
438− | GeoShapeType
439− | FloatType
440− | IntegerType
441− | LongType
442− | ShortType
443− | ByteType deriving (Eq, Show)
444−
445−data FieldDefinition =
446− FieldDefinition { fieldType :: FieldType } deriving (Eq, Show)
447−
448−{-| An 'IndexTemplate' defines a template that will automatically be
449− applied to new indices created. The templates include both
450− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
451− controls if the template will be applied to the index created.
452− Specify mappings as follows: @[toJSON TweetMapping, ...]@
453−
454− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
455−-}
456−data IndexTemplate =
457− IndexTemplate { templatePattern :: TemplatePattern
458− , templateSettings :: Maybe IndexSettings
459− , templateMappings :: [Value]
460− }
461−
462−data MappingField =
463− MappingField { mappingFieldName :: FieldName
464− , fieldDefinition :: FieldDefinition } deriving (Eq, Show)
465−
466−{-| Support for type reification of 'Mapping's is currently incomplete, for
467− now the mapping API verbiage expects a 'ToJSON'able blob.
468−
469− Indexes have mappings, mappings are schemas for the documents contained in the
470− index. I'd recommend having only one mapping per index, always having a mapping,
471− and keeping different kinds of documents separated if possible.
472−-}
473−data Mapping = Mapping { typeName :: TypeName
474− , mappingFields :: [MappingField] } deriving (Eq, Show)
475−
476−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
477− operation index, create, delete, and update. 'BulkIndex' behaves like an
478− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
479−
480− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
481−-}
482−data BulkOperation =
483− BulkIndex IndexName MappingName DocId Value
484− | BulkCreate IndexName MappingName DocId Value
485− | BulkDelete IndexName MappingName DocId
486− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show)
487−
488−{-| 'EsResult' describes the standard wrapper JSON document that you see in
489− successful Elasticsearch lookups or lookups that couldn't find the document.
490−-}
491−data EsResult a = EsResult { _index :: Text
492− , _type :: Text
493− , _id :: Text
494− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show)
495−
496−
497−{-| 'EsResultFound' contains the document and its metadata inside of an
498− 'EsResult' when the document was successfully found.
499−-}
500−data EsResultFound a = EsResultFound { _version :: DocVersion
501− , _source :: a } deriving (Eq, Show)
502−
503−
504−
505−{-| 'DocVersion' is an integer version number for a document between 1
506−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
507−-}
508−newtype DocVersion = DocVersion {
509− docVersionNumber :: Int
510− } deriving (Eq, Show, Ord, ToJSON)
511−
512−-- | Smart constructor for in-range doc version
513−mkDocVersion :: Int -> Maybe DocVersion
514−mkDocVersion i
515− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
516− Just $ DocVersion i
517− | otherwise = Nothing
518−
519−
520−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
521−own version numbers instead of ones from ES.
522−-}
523−newtype ExternalDocVersion = ExternalDocVersion DocVersion
524− deriving (Eq, Show, Ord, Bounded, Enum, ToJSON)
525−
526−{-| 'VersionControl' is specified when indexing documents as a
527−optimistic concurrency control.
528−-}
529−data VersionControl = NoVersionControl
530− -- ^ Don't send a version. This is a pure overwrite.
531− | InternalVersion DocVersion
532− -- ^ Use the default ES versioning scheme. Only
533− -- index the document if the version is the same
534− -- as the one specified. Only applicable to
535− -- updates, as you should be getting Version from
536− -- a search result.
537− | ExternalGT ExternalDocVersion
538− -- ^ Use your own version numbering. Only index
539− -- the document if the version is strictly higher
540− -- OR the document doesn't exist. The given
541− -- version will be used as the new version number
542− -- for the stored document. N.B. All updates must
543− -- increment this number, meaning there is some
544− -- global, external ordering of updates.
545− | ExternalGTE ExternalDocVersion
546− -- ^ Use your own version numbering. Only index
547− -- the document if the version is equal or higher
548− -- than the stored version. Will succeed if there
549− -- is no existing document. The given version will
550− -- be used as the new version number for the
551− -- stored document. Use with care, as this could
552− -- result in data loss.
553− | ForceVersion ExternalDocVersion
554− -- ^ The document will always be indexed and the
555− -- given version will be the new version. This is
556− -- typically used for correcting errors. Use with
557− -- care, as this could result in data loss.
558− deriving (Show, Eq, Ord)
559−
560−{-| 'DocumentParent' is used to specify a parent document.
561−-}
562−newtype DocumentParent = DocumentParent DocId
563− deriving (Eq, Show)
564−
565−{-| 'IndexDocumentSettings' are special settings supplied when indexing
566−a document. For the best backwards compatiblity when new fields are
567−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
568−-}
569−data IndexDocumentSettings =
570− IndexDocumentSettings { idsVersionControl :: VersionControl
571− , idsParent :: Maybe DocumentParent
572− } deriving (Eq, Show)
573−
574−{-| Reasonable default settings. Chooses no version control and no parent.
575−-}
576−defaultIndexDocumentSettings :: IndexDocumentSettings
577−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
578−
579−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
580− dependent with later sorts acting as tie-breakers for earlier sorts.
581−-}
582−type Sort = [SortSpec]
583−
584−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
585− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
586− 'DistanceUnit' to express "nearness" to a single geographical point as a
587− sort specification.
588−
589−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
590−-}
591−data SortSpec = DefaultSortSpec DefaultSort
592− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show)
593−
594−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
595− 'mkSort' convenience function for when you want to specify only the most
596− common parameters.
597−
598−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
599−-}
600−data DefaultSort =
601− DefaultSort { sortFieldName :: FieldName
602− , sortOrder :: SortOrder
603− -- default False
604− , ignoreUnmapped :: Bool
605− , sortMode :: Maybe SortMode
606− , missingSort :: Maybe Missing
607− , nestedFilter :: Maybe Filter } deriving (Eq, Show)
608−
609−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
610− encoded into "asc" or "desc" when turned into JSON.
611−
612−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
613−-}
614−data SortOrder = Ascending
615− | Descending deriving (Eq, Show)
616−
617−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
618− sorted last, first, or using a custom value as a substitute.
619−
620−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
621−-}
622−data Missing = LastMissing
623− | FirstMissing
624− | CustomMissing Text deriving (Eq, Show)
625−
626−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
627−
628−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
629−-}
630−data SortMode = SortMin
631− | SortMax
632− | SortSum
633− | SortAvg deriving (Eq, Show)
634−
635−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
636− that you can concisely describe the usual kind of 'SortSpec's you want.
637−-}
638−mkSort :: FieldName -> SortOrder -> DefaultSort
639−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
640−
641−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
642− 'Query's cannot be cached.
643−-}
644−type Cache = Bool -- caching on/off
645−defaultCache :: Cache
646−defaultCache = False
647−
648−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
649−-}
650−type PrefixValue = Text
651−
652−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
653− JSON encoding baked in. Used all over the place.
654−-}
655−data BooleanOperator = And | Or deriving (Eq, Show)
656−
657−{-| 'ShardCount' is part of 'IndexSettings'
658−-}
659−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic)
660−
661−{-| 'ReplicaCount' is part of 'IndexSettings'
662−-}
663−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic)
664−
665−{-| 'Server' is used with the client functions to point at the ES instance
666−-}
667−newtype Server = Server Text deriving (Eq, Show)
668−
669−{-| 'IndexName' is used to describe which index to query/create/delete
670−-}
671−newtype IndexName = IndexName Text deriving (Eq, Generic, Show)
672−
673−{-| 'TemplateName' is used to describe which template to query/create/delete
674−-}
675−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic)
676−
677−{-| 'TemplatePattern' represents a pattern which is matched against index names
678−-}
679−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic)
680−
681−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
682− the data in the indices.
683−-}
684−newtype MappingName = MappingName Text deriving (Eq, Generic, Show)
685−
686−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
687− Can be set by the user or created by ES itself. Often used in client
688− functions for poking at specific documents.
689−-}
690−newtype DocId = DocId Text deriving (Eq, Generic, Show)
691−
692−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
693−-}
694−newtype QueryString = QueryString Text deriving (Eq, Generic, Show)
695−
696−{-| 'FieldName' is used all over the place wherever a specific field within
697− a document needs to be specified, usually in 'Query's or 'Filter's.
698−-}
699−newtype FieldName = FieldName Text deriving (Eq, Show)
700−
701−
702−{-| 'Script' is often used in place of 'FieldName' to specify more
703−complex ways of extracting a value from a document.
704−-}
705−newtype Script = Script { scriptText :: Text } deriving (Eq, Show)
706−
707−{-| 'CacheName' is used in 'RegexpFilter' for describing the
708− 'CacheKey' keyed caching behavior.
709−-}
710−newtype CacheName = CacheName Text deriving (Eq, Show)
711−
712−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
713−-}
714−newtype CacheKey =
715− CacheKey Text deriving (Eq, Show)
716−newtype Existence =
717− Existence Bool deriving (Eq, Show)
718−newtype NullValue =
719− NullValue Bool deriving (Eq, Show)
720−newtype CutoffFrequency =
721− CutoffFrequency Double deriving (Eq, Show, Generic)
722−newtype Analyzer =
723− Analyzer Text deriving (Eq, Show, Generic)
724−newtype MaxExpansions =
725− MaxExpansions Int deriving (Eq, Show, Generic)
726−
727−{-| 'Lenient', if set to true, will cause format based failures to be
728− ignored. I don't know what the bloody default is, Elasticsearch
729− documentation didn't say what it was. Let me know if you figure it out.
730−-}
731−newtype Lenient =
732− Lenient Bool deriving (Eq, Show, Generic)
733−newtype Tiebreaker =
734− Tiebreaker Double deriving (Eq, Show, Generic)
735−newtype Boost =
736− Boost Double deriving (Eq, Show, Generic)
737−newtype BoostTerms =
738− BoostTerms Double deriving (Eq, Show, Generic)
739−
740−{-| 'MinimumMatch' controls how many should clauses in the bool query should
741− match. Can be an absolute value (2) or a percentage (30%) or a
742− combination of both.
743−-}
744−newtype MinimumMatch =
745− MinimumMatch Int deriving (Eq, Show, Generic)
746−newtype MinimumMatchText =
747− MinimumMatchText Text deriving (Eq, Show)
748−newtype DisableCoord =
749− DisableCoord Bool deriving (Eq, Show, Generic)
750−newtype IgnoreTermFrequency =
751− IgnoreTermFrequency Bool deriving (Eq, Show, Generic)
752−newtype MinimumTermFrequency =
753− MinimumTermFrequency Int deriving (Eq, Show, Generic)
754−newtype MaxQueryTerms =
755− MaxQueryTerms Int deriving (Eq, Show, Generic)
756−newtype Fuzziness =
757− Fuzziness Double deriving (Eq, Show, Generic)
758−
759−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
760−newtype PrefixLength =
761− PrefixLength Int deriving (Eq, Show, Generic)
762−newtype TypeName =
763− TypeName Text deriving (Eq, Show, Generic)
764−newtype PercentMatch =
765− PercentMatch Double deriving (Eq, Show, Generic)
766−newtype StopWord =
767− StopWord Text deriving (Eq, Show, Generic)
768−newtype QueryPath =
769− QueryPath Text deriving (Eq, Show, Generic)
770−
771−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
772− heavy, because all terms in the index need to be examined, just in case
773− they match. Leading wildcards can be disabled by setting
774− 'AllowLeadingWildcard' to false. -}
775−newtype AllowLeadingWildcard =
776− AllowLeadingWildcard Bool deriving (Eq, Show, Generic)
777−newtype LowercaseExpanded =
778− LowercaseExpanded Bool deriving (Eq, Show, Generic)
779−newtype EnablePositionIncrements =
780− EnablePositionIncrements Bool deriving (Eq, Show, Generic)
781−
782−{-| By default, wildcard terms in a query are not analyzed.
783− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
784−-}
785−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic)
786−
787−{-| 'GeneratePhraseQueries' defaults to false.
788−-}
789−newtype GeneratePhraseQueries =
790− GeneratePhraseQueries Bool deriving (Eq, Show, Generic)
791−
792−{-| 'Locale' is used for string conversions - defaults to ROOT.
793−-}
794−newtype Locale = Locale Text deriving (Eq, Show, Generic)
795−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic)
796−newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic)
797−
798−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
799− phrase matches. Default is 0.
800−-}
801−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic)
802−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic)
803−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic)
402+ , DateRangeResult(..)
403+ , TopHitResult(..)
404+
405+ , EsUsername(..)
406+ , EsPassword(..)
407+
408+ , Analysis(..)
409+ , AnalyzerDefinition(..)
410+ , TokenizerDefinition(..)
411+ , TokenFilterDefinition(..)
412+ , CharFilterDefinition(..)
413+ , Ngram(..)
414+ , TokenChar(..)
415+ , Shingle(..)
416+ , Language(..)
417+ ) where
418+
419+import Bloodhound.Import
420+
421+import Database.Bloodhound.Internal.Aggregation
422+import Database.Bloodhound.Internal.Analysis
423+import Database.Bloodhound.Internal.Client
424+import Database.Bloodhound.Internal.Highlight
425+import Database.Bloodhound.Internal.Newtypes
426+import Database.Bloodhound.Internal.Query
427+import Database.Bloodhound.Internal.Sort
428+import Database.Bloodhound.Internal.Suggest
804429
805430{-| 'unpackId' is a silly convenience function that gets used once.
806431-}
@@ -808,8 +433,6 @@ unpackId :: DocId -> Text
808433unpackId (DocId docId) = docId
809434
810435type TrackSortScores = Bool
811−newtype From = From Int deriving (Eq, Show, ToJSON)
812−newtype Size = Size Int deriving (Eq, Show, ToJSON)
813436
814437data Search = Search { queryBody :: Maybe Query
815438 , filterBody :: Maybe Filter
@@ -821,1708 +444,87 @@ data Search = Search { queryBody :: Maybe Query
821444 , from :: From
822445 , size :: Size
823446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
824448 , fields :: Maybe [FieldName]
825− , source :: Maybe Source } deriving (Eq, Show)
449+ , scriptFields :: Maybe ScriptFields
450+ , source :: Maybe Source
451+ , suggestBody :: Maybe Suggest -- ^ Only one Suggestion request / response per Search is supported.
452+ } deriving (Eq, Show)
453+
454+
455+instance ToJSON Search where
456+ toJSON (Search mquery sFilter sort searchAggs
457+ highlight sTrackSortScores sFrom sSize _ sAfter sFields
458+ sScriptFields sSource sSuggest) =
459+ omitNulls [ "query" .= query'
460+ , "sort" .= sort
461+ , "aggregations" .= searchAggs
462+ , "highlight" .= highlight
463+ , "from" .= sFrom
464+ , "size" .= sSize
465+ , "track_scores" .= sTrackSortScores
466+ , "search_after" .= sAfter
467+ , "fields" .= sFields
468+ , "script_fields" .= sScriptFields
469+ , "_source" .= sSource
470+ , "suggest" .= sSuggest]
471+
472+ where query' = case sFilter of
473+ Nothing -> mquery
474+ Just x ->
475+ Just
476+ . QueryBoolQuery
477+ $ mkBoolQuery (maybeToList mquery)
478+ [x] [] []
826479
827480data SearchType = SearchTypeQueryThenFetch
828481 | SearchTypeDfsQueryThenFetch
829− | SearchTypeCount
830− | SearchTypeScan
831− | SearchTypeQueryAndFetch
832− | SearchTypeDfsQueryAndFetch
833482 deriving (Eq, Show)
834483
835484data Source =
836− NoSource
485+ NoSource
837486 | SourcePatterns PatternOrPatterns
838487 | SourceIncludeExclude Include Exclude
839− deriving (Show, Eq)
840−
841−data PatternOrPatterns = PopPattern Pattern
842− | PopPatterns [Pattern] deriving (Eq, Show)
843−
844−data Include = Include [Pattern] deriving (Eq, Show)
845−data Exclude = Exclude [Pattern] deriving (Eq, Show)
846−
847−newtype Pattern = Pattern Text deriving (Eq, Show)
848−
849−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
850− , highlightFields :: [FieldHighlight]
851− } deriving (Show, Eq)
852−
853−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
854− deriving (Show, Eq)
855−
856−
857−data HighlightSettings = Plain PlainHighlight
858− | Postings PostingsHighlight
859− | FastVector FastVectorHighlight
860− deriving (Show, Eq)
861−data PlainHighlight =
862− PlainHighlight { plainCommon :: Maybe CommonHighlight
863− , plainNonPost :: Maybe NonPostings } deriving (Show, Eq)
864−
865− -- This requires that index_options are set to 'offset' in the mapping.
866−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq)
867−
868−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
869−data FastVectorHighlight =
870− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
871− , fvNonPostSettings :: Maybe NonPostings
872− , boundaryChars :: Maybe Text
873− , boundaryMaxScan :: Maybe Int
874− , fragmentOffset :: Maybe Int
875− , matchedFields :: [Text]
876− , phraseLimit :: Maybe Int
877− } deriving (Show, Eq)
878−
879−data CommonHighlight =
880− CommonHighlight { order :: Maybe Text
881− , forceSource :: Maybe Bool
882− , tag :: Maybe HighlightTag
883− , encoder :: Maybe HighlightEncoder
884− , noMatchSize :: Maybe Int
885− , highlightQuery :: Maybe Query
886− , requireFieldMatch :: Maybe Bool
887− } deriving (Show, Eq)
888−
889−-- Settings that are only applicable to FastVector and Plain highlighters.
890−data NonPostings =
891− NonPostings { fragmentSize :: Maybe Int
892− , numberOfFragments :: Maybe Int} deriving (Show, Eq)
893−
894−data HighlightEncoder = DefaultEncoder
895− | HTMLEncoder
896− deriving (Show, Eq)
897−
898−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
899−data HighlightTag = TagSchema Text
900− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
901− deriving (Show, Eq)
902−
903−
904−data Query =
905− TermQuery Term (Maybe Boost)
906− | TermsQuery (NonEmpty Term)
907− | QueryMatchQuery MatchQuery
908− | QueryMultiMatchQuery MultiMatchQuery
909− | QueryBoolQuery BoolQuery
910− | QueryBoostingQuery BoostingQuery
911− | QueryCommonTermsQuery CommonTermsQuery
912− | ConstantScoreFilter Filter Boost
913− | ConstantScoreQuery Query Boost
914− | QueryDisMaxQuery DisMaxQuery
915− | QueryFilteredQuery FilteredQuery
916− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
917− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
918− | QueryFuzzyQuery FuzzyQuery
919− | QueryHasChildQuery HasChildQuery
920− | QueryHasParentQuery HasParentQuery
921− | IdsQuery MappingName [DocId]
922− | QueryIndicesQuery IndicesQuery
923− | MatchAllQuery (Maybe Boost)
924− | QueryMoreLikeThisQuery MoreLikeThisQuery
925− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
926− | QueryNestedQuery NestedQuery
927− | QueryPrefixQuery PrefixQuery
928− | QueryQueryStringQuery QueryStringQuery
929− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
930− | QueryRangeQuery RangeQuery
931− | QueryRegexpQuery RegexpQuery
932− deriving (Eq, Show)
933−
934−data RegexpQuery =
935− RegexpQuery { regexpQueryField :: FieldName
936− , regexpQuery :: Regexp
937− , regexpQueryFlags :: RegexpFlags
938− , regexpQueryBoost :: Maybe Boost
939− } deriving (Eq, Show)
940−
941−data RangeQuery =
942− RangeQuery { rangeQueryField :: FieldName
943− , rangeQueryRange :: RangeValue
944− , rangeQueryBoost :: Boost } deriving (Eq, Show)
945−
946−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
947−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
948−
949−data SimpleQueryStringQuery =
950− SimpleQueryStringQuery
951− { simpleQueryStringQuery :: QueryString
952− , simpleQueryStringField :: Maybe FieldOrFields
953− , simpleQueryStringOperator :: Maybe BooleanOperator
954− , simpleQueryStringAnalyzer :: Maybe Analyzer
955− , simpleQueryStringFlags :: Maybe [SimpleQueryFlag]
956− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
957− , simpleQueryStringLocale :: Maybe Locale
958− } deriving (Eq, Show)
959−
960−data SimpleQueryFlag =
961− SimpleQueryAll
962− | SimpleQueryNone
963− | SimpleQueryAnd
964− | SimpleQueryOr
965− | SimpleQueryPrefix
966− | SimpleQueryPhrase
967− | SimpleQueryPrecedence
968− | SimpleQueryEscape
969− | SimpleQueryWhitespace
970− | SimpleQueryFuzzy
971− | SimpleQueryNear
972− | SimpleQuerySlop deriving (Eq, Show)
973−
974−-- use_dis_max and tie_breaker when fields are plural?
975−data QueryStringQuery =
976− QueryStringQuery
977− { queryStringQuery :: QueryString
978− , queryStringDefaultField :: Maybe FieldName
979− , queryStringOperator :: Maybe BooleanOperator
980− , queryStringAnalyzer :: Maybe Analyzer
981− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
982− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
983− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
984− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
985− , queryStringFuzziness :: Maybe Fuzziness
986− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
987− , queryStringPhraseSlop :: Maybe PhraseSlop
988− , queryStringBoost :: Maybe Boost
989− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
990− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
991− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
992− , queryStringLenient :: Maybe Lenient
993− , queryStringLocale :: Maybe Locale
994− } deriving (Eq, Show)
995−
996−mkQueryStringQuery :: QueryString -> QueryStringQuery
997−mkQueryStringQuery qs =
998− QueryStringQuery qs Nothing Nothing
999− Nothing Nothing Nothing Nothing
1000− Nothing Nothing Nothing Nothing
1001− Nothing Nothing Nothing Nothing
1002− Nothing Nothing
1003−
1004−data FieldOrFields = FofField FieldName
1005− | FofFields [FieldName] deriving (Eq, Show)
1006−
1007−data PrefixQuery =
1008− PrefixQuery
1009− { prefixQueryField :: FieldName
1010− , prefixQueryPrefixValue :: Text
1011− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show)
1012−
1013−data NestedQuery =
1014− NestedQuery
1015− { nestedQueryPath :: QueryPath
1016− , nestedQueryScoreType :: ScoreType
1017− , nestedQuery :: Query } deriving (Eq, Show)
1018−
1019−data MoreLikeThisFieldQuery =
1020− MoreLikeThisFieldQuery
1021− { moreLikeThisFieldText :: Text
1022− , moreLikeThisFieldFields :: FieldName
1023− -- default 0.3 (30%)
1024− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1025− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1026− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1027− , moreLikeThisFieldStopWords :: Maybe [StopWord]
1028− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1029− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1030− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1031− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1032− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1033− , moreLikeThisFieldBoost :: Maybe Boost
1034− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1035− } deriving (Eq, Show)
1036−
1037−data MoreLikeThisQuery =
1038− MoreLikeThisQuery
1039− { moreLikeThisText :: Text
1040− , moreLikeThisFields :: Maybe [FieldName]
1041− -- default 0.3 (30%)
1042− , moreLikeThisPercentMatch :: Maybe PercentMatch
1043− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1044− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1045− , moreLikeThisStopWords :: Maybe [StopWord]
1046− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1047− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1048− , moreLikeThisMinWordLength :: Maybe MinWordLength
1049− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1050− , moreLikeThisBoostTerms :: Maybe BoostTerms
1051− , moreLikeThisBoost :: Maybe Boost
1052− , moreLikeThisAnalyzer :: Maybe Analyzer
1053− } deriving (Eq, Show)
1054−
1055−data IndicesQuery =
1056− IndicesQuery
1057− { indicesQueryIndices :: [IndexName]
1058− , indicesQuery :: Query
1059− -- default "all"
1060− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show)
1061−
1062−data HasParentQuery =
1063− HasParentQuery
1064− { hasParentQueryType :: TypeName
1065− , hasParentQuery :: Query
1066− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1067−
1068−data HasChildQuery =
1069− HasChildQuery
1070− { hasChildQueryType :: TypeName
1071− , hasChildQuery :: Query
1072− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1073−
1074−data ScoreType =
1075− ScoreTypeMax
1076− | ScoreTypeSum
1077− | ScoreTypeAvg
1078− | ScoreTypeNone deriving (Eq, Show)
1079−
1080−data FuzzyQuery =
1081− FuzzyQuery { fuzzyQueryField :: FieldName
1082− , fuzzyQueryValue :: Text
1083− , fuzzyQueryPrefixLength :: PrefixLength
1084− , fuzzyQueryMaxExpansions :: MaxExpansions
1085− , fuzzyQueryFuzziness :: Fuzziness
1086− , fuzzyQueryBoost :: Maybe Boost
1087− } deriving (Eq, Show)
1088−
1089−data FuzzyLikeFieldQuery =
1090− FuzzyLikeFieldQuery
1091− { fuzzyLikeField :: FieldName
1092− -- anaphora is good for the soul.
1093− , fuzzyLikeFieldText :: Text
1094− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1095− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1096− , fuzzyLikeFieldFuzziness :: Fuzziness
1097− , fuzzyLikeFieldPrefixLength :: PrefixLength
1098− , fuzzyLikeFieldBoost :: Boost
1099− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1100− } deriving (Eq, Show)
1101−
1102−data FuzzyLikeThisQuery =
1103− FuzzyLikeThisQuery
1104− { fuzzyLikeFields :: [FieldName]
1105− , fuzzyLikeText :: Text
1106− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1107− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1108− , fuzzyLikeFuzziness :: Fuzziness
1109− , fuzzyLikePrefixLength :: PrefixLength
1110− , fuzzyLikeBoost :: Boost
1111− , fuzzyLikeAnalyzer :: Maybe Analyzer
1112− } deriving (Eq, Show)
1113−
1114−data FilteredQuery =
1115− FilteredQuery
1116− { filteredQuery :: Query
1117− , filteredFilter :: Filter } deriving (Eq, Show)
1118−
1119−data DisMaxQuery =
1120− DisMaxQuery { disMaxQueries :: [Query]
1121− -- default 0.0
1122− , disMaxTiebreaker :: Tiebreaker
1123− , disMaxBoost :: Maybe Boost
1124− } deriving (Eq, Show)
1125−
1126−data MatchQuery =
1127− MatchQuery { matchQueryField :: FieldName
1128− , matchQueryQueryString :: QueryString
1129− , matchQueryOperator :: BooleanOperator
1130− , matchQueryZeroTerms :: ZeroTermsQuery
1131− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1132− , matchQueryMatchType :: Maybe MatchQueryType
1133− , matchQueryAnalyzer :: Maybe Analyzer
1134− , matchQueryMaxExpansions :: Maybe MaxExpansions
1135− , matchQueryLenient :: Maybe Lenient
1136− , matchQueryBoost :: Maybe Boost } deriving (Eq, Show)
1137−
1138−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1139− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1140−-}
1141−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1142−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1143−
1144−data MatchQueryType =
1145− MatchPhrase
1146− | MatchPhrasePrefix deriving (Eq, Show)
1147−
1148−data MultiMatchQuery =
1149− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1150− , multiMatchQueryString :: QueryString
1151− , multiMatchQueryOperator :: BooleanOperator
1152− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1153− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1154− , multiMatchQueryType :: Maybe MultiMatchQueryType
1155− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1156− , multiMatchQueryAnalyzer :: Maybe Analyzer
1157− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1158− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show)
1159−
1160−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1161− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1162− make a 'MultiMatchQuery'.
1163−-}
1164−
1165−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1166−mkMultiMatchQuery matchFields query =
1167− MultiMatchQuery matchFields query
1168− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1169−
1170−data MultiMatchQueryType =
1171− MultiMatchBestFields
1172− | MultiMatchMostFields
1173− | MultiMatchCrossFields
1174− | MultiMatchPhrase
1175− | MultiMatchPhrasePrefix deriving (Eq, Show)
1176−
1177−data BoolQuery =
1178− BoolQuery { boolQueryMustMatch :: [Query]
1179− , boolQueryMustNotMatch :: [Query]
1180− , boolQueryShouldMatch :: [Query]
1181− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1182− , boolQueryBoost :: Maybe Boost
1183− , boolQueryDisableCoord :: Maybe DisableCoord
1184− } deriving (Eq, Show)
1185−
1186−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1187−mkBoolQuery must mustNot should =
1188− BoolQuery must mustNot should Nothing Nothing Nothing
1189−
1190−data BoostingQuery =
1191− BoostingQuery { positiveQuery :: Query
1192− , negativeQuery :: Query
1193− , negativeBoost :: Boost } deriving (Eq, Show)
1194−
1195−data CommonTermsQuery =
1196− CommonTermsQuery { commonField :: FieldName
1197− , commonQuery :: QueryString
1198− , commonCutoffFrequency :: CutoffFrequency
1199− , commonLowFreqOperator :: BooleanOperator
1200− , commonHighFreqOperator :: BooleanOperator
1201− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1202− , commonBoost :: Maybe Boost
1203− , commonAnalyzer :: Maybe Analyzer
1204− , commonDisableCoord :: Maybe DisableCoord
1205− } deriving (Eq, Show)
1206−
1207−data CommonMinimumMatch =
1208− CommonMinimumMatchHighLow MinimumMatchHighLow
1209− | CommonMinimumMatch MinimumMatch
1210− deriving (Eq, Show)
1211−
1212−data MinimumMatchHighLow =
1213− MinimumMatchHighLow { lowFreq :: MinimumMatch
1214− , highFreq :: MinimumMatch } deriving (Eq, Show)
1215−
1216−data Filter = AndFilter [Filter] Cache
1217− | OrFilter [Filter] Cache
1218− | NotFilter Filter Cache
1219− | IdentityFilter
1220− | BoolFilter BoolMatch
1221− | ExistsFilter FieldName -- always cached
1222− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1223− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1224− | GeoDistanceRangeFilter GeoPoint DistanceRange
1225− | GeoPolygonFilter FieldName [LatLon]
1226− | IdsFilter MappingName [DocId]
1227− | LimitFilter Int
1228− | MissingFilter FieldName Existence NullValue
1229− | PrefixFilter FieldName PrefixValue Cache
1230− | QueryFilter Query Cache
1231− | RangeFilter FieldName RangeValue RangeExecution Cache
1232− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1233− | TermFilter Term Cache
1234− deriving (Eq, Show)
1235−
1236−data ZeroTermsQuery = ZeroTermsNone
1237− | ZeroTermsAll deriving (Eq, Show)
1238−
1239−data RangeExecution = RangeExecutionIndex
1240− | RangeExecutionFielddata deriving (Eq, Show)
1241−
1242−newtype Regexp = Regexp Text deriving (Eq, Show)
1243−
1244−data RegexpFlags = AllRegexpFlags
1245− | NoRegexpFlags
1246− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show)
1247−
1248−data RegexpFlag = AnyString
1249− | Automaton
1250− | Complement
1251− | Empty
1252− | Intersection
1253− | Interval deriving (Eq, Show)
1254−
1255−newtype LessThan = LessThan Double deriving (Eq, Show)
1256−newtype LessThanEq = LessThanEq Double deriving (Eq, Show)
1257−newtype GreaterThan = GreaterThan Double deriving (Eq, Show)
1258−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show)
1259−
1260−newtype LessThanD = LessThanD UTCTime deriving (Eq, Show)
1261−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show)
1262−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show)
1263−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show)
1264−
1265−data RangeValue = RangeDateLte LessThanEqD
1266− | RangeDateLt LessThanD
1267− | RangeDateGte GreaterThanEqD
1268− | RangeDateGt GreaterThanD
1269− | RangeDateGtLt GreaterThanD LessThanD
1270− | RangeDateGteLte GreaterThanEqD LessThanEqD
1271− | RangeDateGteLt GreaterThanEqD LessThanD
1272− | RangeDateGtLte GreaterThanD LessThanEqD
1273− | RangeDoubleLte LessThanEq
1274− | RangeDoubleLt LessThan
1275− | RangeDoubleGte GreaterThanEq
1276− | RangeDoubleGt GreaterThan
1277− | RangeDoubleGtLt GreaterThan LessThan
1278− | RangeDoubleGteLte GreaterThanEq LessThanEq
1279− | RangeDoubleGteLt GreaterThanEq LessThan
1280− | RangeDoubleGtLte GreaterThan LessThanEq
1281− deriving (Eq, Show)
1282−
1283−rangeValueToPair :: RangeValue -> [Pair]
1284−rangeValueToPair rv = case rv of
1285− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1286− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1287− RangeDateLt (LessThanD t) -> ["lt" .= t]
1288− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1289− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1290− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1291− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1292− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1293− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1294− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1295− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1296− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1297− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1298− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1299− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1300− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1301−
1302−data Term = Term { termField :: Text
1303− , termValue :: Text } deriving (Eq, Show)
1304−
1305−data BoolMatch = MustMatch Term Cache
1306− | MustNotMatch Term Cache
1307− | ShouldMatch [Term] Cache deriving (Eq, Show)
1308−
1309−-- "memory" or "indexed"
1310−data GeoFilterType = GeoFilterMemory
1311− | GeoFilterIndexed deriving (Eq, Show)
1312−
1313−data LatLon = LatLon { lat :: Double
1314− , lon :: Double } deriving (Eq, Show)
1315−
1316−data GeoBoundingBox =
1317− GeoBoundingBox { topLeft :: LatLon
1318− , bottomRight :: LatLon } deriving (Eq, Show)
1319−
1320−data GeoBoundingBoxConstraint =
1321− GeoBoundingBoxConstraint { geoBBField :: FieldName
1322− , constraintBox :: GeoBoundingBox
1323− , bbConstraintcache :: Cache
1324− , geoType :: GeoFilterType
1325− } deriving (Eq, Show)
1326−
1327−data GeoPoint =
1328− GeoPoint { geoField :: FieldName
1329− , latLon :: LatLon} deriving (Eq, Show)
1330−
1331−data DistanceUnit = Miles
1332− | Yards
1333− | Feet
1334− | Inches
1335− | Kilometers
1336− | Meters
1337− | Centimeters
1338− | Millimeters
1339− | NauticalMiles deriving (Eq, Show)
1340−
1341−data DistanceType = Arc
1342− | SloppyArc -- doesn't exist <1.0
1343− | Plane deriving (Eq, Show)
1344−
1345−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1346− | NoOptimizeBbox deriving (Eq, Show)
1347−
1348−data Distance =
1349− Distance { coefficient :: Double
1350− , unit :: DistanceUnit } deriving (Eq, Show)
1351−
1352−data DistanceRange =
1353− DistanceRange { distanceFrom :: Distance
1354− , distanceTo :: Distance } deriving (Eq, Show)
1355−
1356−data SearchResult a =
1357− SearchResult { took :: Int
1358− , timedOut :: Bool
1359− , shards :: ShardResult
1360− , searchHits :: SearchHits a
1361− , aggregations :: Maybe AggregationResults
1362− , scrollId :: Maybe ScrollId } deriving (Eq, Show)
1363−
1364−type ScrollId = Text -- Fixme: Newtype
1365−
1366−type Score = Maybe Double
1367−
1368−data SearchHits a =
1369− SearchHits { hitsTotal :: Int
1370− , maxScore :: Score
1371− , hits :: [Hit a] } deriving (Eq, Show)
1372−
1373−
1374−instance Monoid (SearchHits a) where
1375− mempty = SearchHits 0 Nothing mempty
1376− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1377− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1378−
1379−
1380−data Hit a =
1381− Hit { hitIndex :: IndexName
1382− , hitType :: MappingName
1383− , hitDocId :: DocId
1384− , hitScore :: Score
1385− , hitSource :: a
1386− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show)
1387−
1388−data ShardResult =
1389− ShardResult { shardTotal :: Int
1390− , shardsSuccessful :: Int
1391− , shardsFailed :: Int } deriving (Eq, Show, Generic)
1392−
1393−type HitHighlight = M.Map Text [Text]
1394−
1395−showText :: Show a => a -> Text
1396−showText = T.pack . show
1397−
1398−type Aggregations = M.Map Text Aggregation
1399−
1400−emptyAggregations :: Aggregations
1401−emptyAggregations = M.empty
1402−
1403−mkAggregations :: Text -> Aggregation -> Aggregations
1404−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1405−
1406−data TermOrder = TermOrder{ termSortField :: Text
1407− , termSortOrder :: SortOrder } deriving (Eq, Show)
1408−
1409−data TermInclusion = TermInclusion Text
1410− | TermPattern Text Text deriving (Eq, Show)
1411−
1412−data CollectionMode = BreadthFirst
1413− | DepthFirst deriving (Eq, Show)
1414−
1415−data ExecutionHint = Ordinals
1416− | GlobalOrdinals
1417− | GlobalOrdinalsHash
1418− | GlobalOrdinalsLowCardinality
1419− | Map deriving (Eq, Show)
1420−
1421−data TimeInterval = Weeks
1422− | Days
1423− | Hours
1424− | Minutes
1425− | Seconds deriving (Eq)
1426−
1427−data Interval = Year
1428− | Quarter
1429− | Month
1430− | Week
1431− | Day
1432− | Hour
1433− | Minute
1434− | Second
1435− | FractionalInterval Float TimeInterval deriving (Eq, Show)
1436−
1437−data Aggregation = TermsAgg TermsAggregation
1438− | DateHistogramAgg DateHistogramAggregation
1439− | ValueCountAgg ValueCountAggregation
1440− | FilterAgg FilterAggregation deriving (Eq, Show)
1441−
1442−
1443−data TermsAggregation = TermsAggregation { term :: Either Text Text
1444− , termInclude :: Maybe TermInclusion
1445− , termExclude :: Maybe TermInclusion
1446− , termOrder :: Maybe TermOrder
1447− , termMinDocCount :: Maybe Int
1448− , termSize :: Maybe Int
1449− , termShardSize :: Maybe Int
1450− , termCollectMode :: Maybe CollectionMode
1451− , termExecutionHint :: Maybe ExecutionHint
1452− , termAggs :: Maybe Aggregations
1453− } deriving (Eq, Show)
1454−
1455−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1456− , dateInterval :: Interval
1457− , dateFormat :: Maybe Text
1458− -- pre and post deprecated in 1.5
1459− , datePreZone :: Maybe Text
1460− , datePostZone :: Maybe Text
1461− , datePreOffset :: Maybe Text
1462− , datePostOffset :: Maybe Text
1463− , dateAggs :: Maybe Aggregations
1464− } deriving (Eq, Show)
1465−
1466−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1467−data ValueCountAggregation = FieldValueCount FieldName
1468− | ScriptValueCount Script deriving (Eq, Show)
1469−
1470−-- | Single-bucket filter aggregations. See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html#search-aggregations-bucket-filter-aggregation> for more information.
1471−data FilterAggregation = FilterAggregation { faFilter :: Filter
1472− , faAggs :: Maybe Aggregations} deriving (Eq, Show)
1473−
1474−mkTermsAggregation :: Text -> TermsAggregation
1475−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1476−
1477−mkTermsScriptAggregation :: Text -> TermsAggregation
1478−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1479−
1480−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1481−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1482−
1483−instance ToJSON TermOrder where
1484− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1485−
1486−instance ToJSON TermInclusion where
1487− toJSON (TermInclusion x) = toJSON x
1488− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1489− "flags" .= flags]
1490−
1491−instance ToJSON CollectionMode where
1492− toJSON BreadthFirst = "breadth_first"
1493− toJSON DepthFirst = "depth_first"
1494−
1495−instance ToJSON ExecutionHint where
1496− toJSON Ordinals = "ordinals"
1497− toJSON GlobalOrdinals = "global_ordinals"
1498− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1499− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1500− toJSON Map = "map"
1501−
1502−instance ToJSON Interval where
1503− toJSON Year = "year"
1504− toJSON Quarter = "quarter"
1505− toJSON Month = "month"
1506− toJSON Week = "week"
1507− toJSON Day = "day"
1508− toJSON Hour = "hour"
1509− toJSON Minute = "minute"
1510− toJSON Second = "second"
1511− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1512−
1513−instance Show TimeInterval where
1514− show Weeks = "w"
1515− show Days = "d"
1516− show Hours = "h"
1517− show Minutes = "m"
1518− show Seconds = "s"
1519−
1520−instance ToJSON Aggregation where
1521− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1522− omitNulls ["terms" .= omitNulls [ toJSON' term,
1523− "include" .= include,
1524− "exclude" .= exclude,
1525− "order" .= order,
1526− "min_doc_count" .= minDocCount,
1527− "size" .= size,
1528− "shard_size" .= shardSize,
1529− "collect_mode" .= collectMode,
1530− "execution_hint" .= executionHint
1531− ],
1532− "aggs" .= termAggs ]
1533− where
1534− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1535−
1536− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1537− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1538− "interval" .= interval,
1539− "format" .= format,
1540− "pre_zone" .= preZone,
1541− "post_zone" .= postZone,
1542− "pre_offset" .= preOffset,
1543− "post_offset" .= postOffset
1544− ],
1545− "aggs" .= dateHistoAggs ]
1546− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1547− where v = case a of
1548− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1549− (ScriptValueCount (Script s)) -> object ["script" .= s]
1550− toJSON (FilterAgg (FilterAggregation filt ags)) =
1551− omitNulls [ "filter" .= filt
1552− , "aggs" .= ags]
1553−
1554−type AggregationResults = M.Map Text Value
1555−
1556−class BucketAggregation a where
1557− key :: a -> Text
1558− docCount :: a -> Int
1559− aggs :: a -> Maybe AggregationResults
1560−
1561−
1562−data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1563−
1564−data TermsResult = TermsResult { termKey :: Text
1565− , termsDocCount :: Int
1566− , termsAggs :: Maybe AggregationResults } deriving (Show)
1567−
1568−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1569− , dateKeyStr :: Maybe Text
1570− , dateDocCount :: Int
1571− , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1572−
1573−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1574−toTerms t a = M.lookup t a >>= deserialize
1575− where deserialize = parseMaybe parseJSON
1576−
1577−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1578−toDateHistogram t a = M.lookup t a >>= deserialize
1579− where deserialize = parseMaybe parseJSON
1580−
1581−instance BucketAggregation TermsResult where
1582− key = termKey
1583− docCount = termsDocCount
1584− aggs = termsAggs
1585−
1586−instance BucketAggregation DateHistogramResult where
1587− key = showText . dateKey
1588− docCount = dateDocCount
1589− aggs = dateHistogramAggs
1590−
1591−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1592− parseJSON (Object v) = Bucket <$>
1593− v .: "buckets"
1594− parseJSON _ = mempty
1595−
1596−instance FromJSON TermsResult where
1597− parseJSON (Object v) = TermsResult <$>
1598− v .: "key" <*>
1599− v .: "doc_count" <*>
1600− v .:? "aggregations"
1601− parseJSON _ = mempty
1602−
1603−instance FromJSON DateHistogramResult where
1604− parseJSON (Object v) = DateHistogramResult <$>
1605− v .: "key" <*>
1606− v .:? "key_as_string" <*>
1607− v .: "doc_count" <*>
1608− v .:? "aggregations"
1609− parseJSON _ = mempty
1610−
1611−instance Monoid Filter where
1612− mempty = IdentityFilter
1613− mappend a b = AndFilter [a, b] defaultCache
1614−
1615−instance Seminearring Filter where
1616− a <||> b = OrFilter [a, b] defaultCache
1617−
1618−instance ToJSON Filter where
1619− toJSON (AndFilter filters cache) =
1620− object ["and" .=
1621− object [ "filters" .= fmap toJSON filters
1622− , "_cache" .= cache]]
1623−
1624− toJSON (OrFilter filters cache) =
1625− object ["or" .=
1626− object [ "filters" .= fmap toJSON filters
1627− , "_cache" .= cache]]
1628−
1629− toJSON (NotFilter notFilter cache) =
1630− object ["not" .=
1631− object ["filter" .= notFilter
1632− , "_cache" .= cache]]
1633−
1634− toJSON (IdentityFilter) =
1635− object ["match_all" .= object []]
1636−
1637− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1638− object ["term" .= object base]
1639− where base = [termFilterField .= termFilterValue,
1640− "_cache" .= cache]
1641−
1642− toJSON (ExistsFilter (FieldName fieldName)) =
1643− object ["exists" .= object
1644− ["field" .= fieldName]]
1645−
1646− toJSON (BoolFilter boolMatch) =
1647− object ["bool" .= boolMatch]
1648−
1649− toJSON (GeoBoundingBoxFilter bbConstraint) =
1650− object ["geo_bounding_box" .= bbConstraint]
1651−
1652− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1653− distance distanceType optimizeBbox cache) =
1654− object ["geo_distance" .=
1655− object ["distance" .= distance
1656− , "distance_type" .= distanceType
1657− , "optimize_bbox" .= optimizeBbox
1658− , distanceGeoField .= geoDistLatLon
1659− , "_cache" .= cache]]
1660−
1661− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1662− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1663− object ["geo_distance_range" .=
1664− object ["from" .= geoDistRangeDistFrom
1665− , "to" .= drDistanceTo
1666− , gddrField .= drLatLon]]
1667−
1668− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1669− object ["geo_polygon" .=
1670− object [geoPolygonFilterField .=
1671− object ["points" .= fmap toJSON latLons]]]
1672−
1673− toJSON (IdsFilter (MappingName mappingName) values) =
1674− object ["ids" .=
1675− object ["type" .= mappingName
1676− , "values" .= fmap unpackId values]]
1677−
1678− toJSON (LimitFilter limit) =
1679− object ["limit" .= object ["value" .= limit]]
1680−
1681− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1682− object ["missing" .=
1683− object ["field" .= fieldName
1684− , "existence" .= existence
1685− , "null_value" .= nullValue]]
1686−
1687− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1688− object ["prefix" .=
1689− object [fieldName .= fieldValue
1690− , "_cache" .= cache]]
1691−
1692− toJSON (QueryFilter query False) =
1693− object ["query" .= toJSON query ]
1694− toJSON (QueryFilter query True) =
1695− object ["fquery" .=
1696− object [ "query" .= toJSON query
1697− , "_cache" .= True ]]
1698−
1699− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1700− object ["range" .=
1701− object [ fieldName .= object (rangeValueToPair rangeValue)
1702− , "execution" .= rangeExecution
1703− , "_cache" .= cache]]
1704−
1705− toJSON (RegexpFilter (FieldName fieldName)
1706− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1707− object ["regexp" .=
1708− object [fieldName .=
1709− object ["value" .= regexText
1710− , "flags" .= flags]
1711− , "_name" .= cacheName
1712− , "_cache" .= cache
1713− , "_cache_key" .= cacheKey]]
1714−
1715−instance ToJSON GeoPoint where
1716− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
1717− object [ geoPointField .= geoPointLatLon ]
1718−
1719−
1720−instance ToJSON Query where
1721− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
1722− object [ "term" .=
1723− object [termQueryField .= object merged]]
1724− where
1725− base = [ "value" .= termQueryValue ]
1726− boosted = maybe [] (return . ("boost" .=)) boost
1727− merged = mappend base boosted
1728−
1729− toJSON (TermsQuery terms) =
1730− object [ "terms" .= object conjoined ]
1731− where conjoined = [ getTermsField terms .=
1732− fmap (toJSON . getTermValue) (toList terms)]
1733− getTermsField ((Term f _ ) :| _) = f
1734− getTermValue (Term _ v) = v
1735− toJSON (IdsQuery idsQueryMappingName docIds) =
1736− object [ "ids" .= object conjoined ]
1737− where conjoined = [ "type" .= idsQueryMappingName
1738− , "values" .= fmap toJSON docIds ]
1739−
1740− toJSON (QueryQueryStringQuery qQueryStringQuery) =
1741− object [ "query_string" .= qQueryStringQuery ]
1742−
1743− toJSON (QueryMatchQuery matchQuery) =
1744− object [ "match" .= matchQuery ]
1745−
1746− toJSON (QueryMultiMatchQuery multiMatchQuery) =
1747− toJSON multiMatchQuery
1748−
1749− toJSON (QueryBoolQuery boolQuery) =
1750− object [ "bool" .= boolQuery ]
1751−
1752− toJSON (QueryBoostingQuery boostingQuery) =
1753− object [ "boosting" .= boostingQuery ]
1754−
1755− toJSON (QueryCommonTermsQuery commonTermsQuery) =
1756− object [ "common" .= commonTermsQuery ]
1757−
1758− toJSON (ConstantScoreFilter csFilter boost) =
1759− object [ "constant_score" .= csFilter
1760− , "boost" .= boost]
1761−
1762− toJSON (ConstantScoreQuery query boost) =
1763− object [ "constant_score" .= query
1764− , "boost" .= boost]
1765−
1766− toJSON (QueryDisMaxQuery disMaxQuery) =
1767− object [ "dis_max" .= disMaxQuery ]
1768−
1769− toJSON (QueryFilteredQuery qFilteredQuery) =
1770− object [ "filtered" .= qFilteredQuery ]
1771−
1772− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
1773− object [ "fuzzy_like_this" .= fuzzyQuery ]
1774−
1775− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
1776− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
1777−
1778− toJSON (QueryFuzzyQuery fuzzyQuery) =
1779− object [ "fuzzy" .= fuzzyQuery ]
1780−
1781− toJSON (QueryHasChildQuery childQuery) =
1782− object [ "has_child" .= childQuery ]
1783−
1784− toJSON (QueryHasParentQuery parentQuery) =
1785− object [ "has_parent" .= parentQuery ]
1786−
1787− toJSON (QueryIndicesQuery qIndicesQuery) =
1788− object [ "indices" .= qIndicesQuery ]
1789−
1790− toJSON (MatchAllQuery boost) =
1791− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
1792−
1793− toJSON (QueryMoreLikeThisQuery query) =
1794− object [ "more_like_this" .= query ]
1795−
1796− toJSON (QueryMoreLikeThisFieldQuery query) =
1797− object [ "more_like_this_field" .= query ]
1798−
1799− toJSON (QueryNestedQuery query) =
1800− object [ "nested" .= query ]
1801−
1802− toJSON (QueryPrefixQuery query) =
1803− object [ "prefix" .= query ]
1804−
1805− toJSON (QueryRangeQuery query) =
1806− object [ "range" .= query ]
1807−
1808− toJSON (QueryRegexpQuery query) =
1809− object [ "regexp" .= query ]
1810−
1811− toJSON (QuerySimpleQueryStringQuery query) =
1812− object [ "simple_query_string" .= query ]
1813−
1814−
1815−omitNulls :: [(Text, Value)] -> Value
1816−omitNulls = object . filter notNull where
1817− notNull (_, Null) = False
1818− notNull (_, Array a) = (not . V.null) a
1819− notNull _ = True
1820−
1821−
1822−instance ToJSON SimpleQueryStringQuery where
1823− toJSON SimpleQueryStringQuery {..} =
1824− omitNulls (base ++ maybeAdd)
1825− where base = [ "query" .= simpleQueryStringQuery ]
1826− maybeAdd = [ "fields" .= simpleQueryStringField
1827− , "default_operator" .= simpleQueryStringOperator
1828− , "analyzer" .= simpleQueryStringAnalyzer
1829− , "flags" .= simpleQueryStringFlags
1830− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
1831− , "locale" .= simpleQueryStringLocale ]
1832−
1833−
1834−instance ToJSON FieldOrFields where
1835− toJSON (FofField fieldName) =
1836− toJSON fieldName
1837− toJSON (FofFields fieldNames) =
1838− toJSON fieldNames
1839−
1840−instance ToJSON SimpleQueryFlag where
1841− toJSON SimpleQueryAll = "ALL"
1842− toJSON SimpleQueryNone = "NONE"
1843− toJSON SimpleQueryAnd = "AND"
1844− toJSON SimpleQueryOr = "OR"
1845− toJSON SimpleQueryPrefix = "PREFIX"
1846− toJSON SimpleQueryPhrase = "PHRASE"
1847− toJSON SimpleQueryPrecedence = "PRECEDENCE"
1848− toJSON SimpleQueryEscape = "ESCAPE"
1849− toJSON SimpleQueryWhitespace = "WHITESPACE"
1850− toJSON SimpleQueryFuzzy = "FUZZY"
1851− toJSON SimpleQueryNear = "NEAR"
1852− toJSON SimpleQuerySlop = "SLOP"
1853−
1854−
1855−instance ToJSON RegexpQuery where
1856− toJSON (RegexpQuery (FieldName rqQueryField)
1857− (Regexp regexpQueryQuery) rqQueryFlags
1858− rqQueryBoost) =
1859− object [ rqQueryField .= omitNulls base ]
1860− where base = [ "value" .= regexpQueryQuery
1861− , "flags" .= rqQueryFlags
1862− , "boost" .= rqQueryBoost ]
1863−
1864−
1865−instance ToJSON QueryStringQuery where
1866− toJSON (QueryStringQuery qsQueryString
1867− qsDefaultField qsOperator
1868− qsAnalyzer qsAllowWildcard
1869− qsLowercaseExpanded qsEnablePositionIncrements
1870− qsFuzzyMaxExpansions qsFuzziness
1871− qsFuzzyPrefixLength qsPhraseSlop
1872− qsBoost qsAnalyzeWildcard
1873− qsGeneratePhraseQueries qsMinimumShouldMatch
1874− qsLenient qsLocale) =
1875− omitNulls base
1876− where
1877− base = [ "query" .= qsQueryString
1878− , "default_field" .= qsDefaultField
1879− , "default_operator" .= qsOperator
1880− , "analyzer" .= qsAnalyzer
1881− , "allow_leading_wildcard" .= qsAllowWildcard
1882− , "lowercase_expanded_terms" .= qsLowercaseExpanded
1883− , "enable_position_increments" .= qsEnablePositionIncrements
1884− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
1885− , "fuzziness" .= qsFuzziness
1886− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
1887− , "phrase_slop" .= qsPhraseSlop
1888− , "boost" .= qsBoost
1889− , "analyze_wildcard" .= qsAnalyzeWildcard
1890− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
1891− , "minimum_should_match" .= qsMinimumShouldMatch
1892− , "lenient" .= qsLenient
1893− , "locale" .= qsLocale ]
1894−
1895−
1896−instance ToJSON RangeQuery where
1897− toJSON (RangeQuery (FieldName fieldName) range boost) =
1898− object [ fieldName .= conjoined ]
1899− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
1900−
1901−
1902−instance ToJSON PrefixQuery where
1903− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
1904− object [ fieldName .= omitNulls base ]
1905− where base = [ "value" .= queryValue
1906− , "boost" .= boost ]
1907−
1908−
1909−instance ToJSON NestedQuery where
1910− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
1911− object [ "path" .= nqPath
1912− , "score_mode" .= nqScoreType
1913− , "query" .= nqQuery ]
1914−
1915−
1916−instance ToJSON MoreLikeThisFieldQuery where
1917− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
1918− percent mtf mqt stopwords mindf maxdf
1919− minwl maxwl boostTerms boost analyzer) =
1920− object [ fieldName .= omitNulls base ]
1921− where base = [ "like_text" .= text
1922− , "percent_terms_to_match" .= percent
1923− , "min_term_freq" .= mtf
1924− , "max_query_terms" .= mqt
1925− , "stop_words" .= stopwords
1926− , "min_doc_freq" .= mindf
1927− , "max_doc_freq" .= maxdf
1928− , "min_word_length" .= minwl
1929− , "max_word_length" .= maxwl
1930− , "boost_terms" .= boostTerms
1931− , "boost" .= boost
1932− , "analyzer" .= analyzer ]
1933−
1934−
1935−instance ToJSON MoreLikeThisQuery where
1936− toJSON (MoreLikeThisQuery text fields percent
1937− mtf mqt stopwords mindf maxdf
1938− minwl maxwl boostTerms boost analyzer) =
1939− omitNulls base
1940− where base = [ "like_text" .= text
1941− , "fields" .= fields
1942− , "percent_terms_to_match" .= percent
1943− , "min_term_freq" .= mtf
1944− , "max_query_terms" .= mqt
1945− , "stop_words" .= stopwords
1946− , "min_doc_freq" .= mindf
1947− , "max_doc_freq" .= maxdf
1948− , "min_word_length" .= minwl
1949− , "max_word_length" .= maxwl
1950− , "boost_terms" .= boostTerms
1951− , "boost" .= boost
1952− , "analyzer" .= analyzer ]
1953−
1954−
1955−instance ToJSON IndicesQuery where
1956− toJSON (IndicesQuery indices query noMatch) =
1957− omitNulls [ "indices" .= indices
1958− , "no_match_query" .= noMatch
1959− , "query" .= query ]
1960−
1961−
1962−instance ToJSON HasParentQuery where
1963− toJSON (HasParentQuery queryType query scoreType) =
1964− omitNulls [ "parent_type" .= queryType
1965− , "score_type" .= scoreType
1966− , "query" .= query ]
1967−
1968−
1969−instance ToJSON HasChildQuery where
1970− toJSON (HasChildQuery queryType query scoreType) =
1971− omitNulls [ "query" .= query
1972− , "score_type" .= scoreType
1973− , "type" .= queryType ]
1974−
1975−
1976−instance ToJSON FuzzyQuery where
1977− toJSON (FuzzyQuery (FieldName fieldName) queryText
1978− prefixLength maxEx fuzziness boost) =
1979− object [ fieldName .= omitNulls base ]
1980− where base = [ "value" .= queryText
1981− , "fuzziness" .= fuzziness
1982− , "prefix_length" .= prefixLength
1983− , "boost" .= boost
1984− , "max_expansions" .= maxEx ]
1985−
1986−
1987−instance ToJSON FuzzyLikeFieldQuery where
1988− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
1989− fieldText maxTerms ignoreFreq fuzziness prefixLength
1990− boost analyzer) =
1991− object [ fieldName .=
1992− omitNulls [ "like_text" .= fieldText
1993− , "max_query_terms" .= maxTerms
1994− , "ignore_tf" .= ignoreFreq
1995− , "fuzziness" .= fuzziness
1996− , "prefix_length" .= prefixLength
1997− , "analyzer" .= analyzer
1998− , "boost" .= boost ]]
1999−
2000−
2001−instance ToJSON FuzzyLikeThisQuery where
2002− toJSON (FuzzyLikeThisQuery fields text maxTerms
2003− ignoreFreq fuzziness prefixLength boost analyzer) =
2004− omitNulls base
2005− where base = [ "fields" .= fields
2006− , "like_text" .= text
2007− , "max_query_terms" .= maxTerms
2008− , "ignore_tf" .= ignoreFreq
2009− , "fuzziness" .= fuzziness
2010− , "prefix_length" .= prefixLength
2011− , "analyzer" .= analyzer
2012− , "boost" .= boost ]
2013−
2014−
2015−instance ToJSON FilteredQuery where
2016− toJSON (FilteredQuery query fFilter) =
2017− object [ "query" .= query
2018− , "filter" .= fFilter ]
2019−
2020−
2021−instance ToJSON DisMaxQuery where
2022− toJSON (DisMaxQuery queries tiebreaker boost) =
2023− omitNulls base
2024− where base = [ "queries" .= queries
2025− , "boost" .= boost
2026− , "tie_breaker" .= tiebreaker ]
2027−
2028−
2029−instance ToJSON CommonTermsQuery where
2030− toJSON (CommonTermsQuery (FieldName fieldName)
2031− (QueryString query) cf lfo hfo msm
2032− boost analyzer disableCoord) =
2033− object [fieldName .= omitNulls base ]
2034− where base = [ "query" .= query
2035− , "cutoff_frequency" .= cf
2036− , "low_freq_operator" .= lfo
2037− , "minimum_should_match" .= msm
2038− , "boost" .= boost
2039− , "analyzer" .= analyzer
2040− , "disable_coord" .= disableCoord
2041− , "high_freq_operator" .= hfo ]
2042−
2043−
2044−instance ToJSON CommonMinimumMatch where
2045− toJSON (CommonMinimumMatch mm) = toJSON mm
2046− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2047− object [ "low_freq" .= lowF
2048− , "high_freq" .= highF ]
2049−
2050−instance ToJSON BoostingQuery where
2051− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2052− object [ "positive" .= bqPositiveQuery
2053− , "negative" .= bqNegativeQuery
2054− , "negative_boost" .= bqNegativeBoost ]
2055−
2056−
2057−instance ToJSON BoolQuery where
2058− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2059− omitNulls base
2060− where base = [ "must" .= mustM
2061− , "must_not" .= notM
2062− , "should" .= shouldM
2063− , "minimum_should_match" .= bqMin
2064− , "boost" .= boost
2065− , "disable_coord" .= disableCoord ]
2066−
2067−
2068−instance ToJSON MatchQuery where
2069− toJSON (MatchQuery (FieldName fieldName)
2070− (QueryString mqQueryString) booleanOperator
2071− zeroTermsQuery cutoffFrequency matchQueryType
2072− analyzer maxExpansions lenient boost) =
2073− object [ fieldName .= omitNulls base ]
2074− where base = [ "query" .= mqQueryString
2075− , "operator" .= booleanOperator
2076− , "zero_terms_query" .= zeroTermsQuery
2077− , "cutoff_frequency" .= cutoffFrequency
2078− , "type" .= matchQueryType
2079− , "analyzer" .= analyzer
2080− , "max_expansions" .= maxExpansions
2081− , "lenient" .= lenient
2082− , "boost" .= boost ]
2083−
2084−
2085−instance ToJSON MultiMatchQuery where
2086− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2087− ztQ tb mmqt cf analyzer maxEx lenient) =
2088− object ["multi_match" .= omitNulls base]
2089− where base = [ "fields" .= fmap toJSON fields
2090− , "query" .= query
2091− , "operator" .= boolOp
2092− , "zero_terms_query" .= ztQ
2093− , "tiebreaker" .= tb
2094− , "type" .= mmqt
2095− , "cutoff_frequency" .= cf
2096− , "analyzer" .= analyzer
2097− , "max_expansions" .= maxEx
2098− , "lenient" .= lenient ]
2099−
2100−
2101−instance ToJSON MultiMatchQueryType where
2102− toJSON MultiMatchBestFields = "best_fields"
2103− toJSON MultiMatchMostFields = "most_fields"
2104− toJSON MultiMatchCrossFields = "cross_fields"
2105− toJSON MultiMatchPhrase = "phrase"
2106− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2107−
2108−instance ToJSON BooleanOperator where
2109− toJSON And = String "and"
2110− toJSON Or = String "or"
2111−
2112−instance ToJSON ZeroTermsQuery where
2113− toJSON ZeroTermsNone = String "none"
2114− toJSON ZeroTermsAll = String "all"
2115−
2116−instance ToJSON MatchQueryType where
2117− toJSON MatchPhrase = "phrase"
2118− toJSON MatchPhrasePrefix = "phrase_prefix"
2119−
2120−instance ToJSON FieldName where
2121− toJSON (FieldName fieldName) = String fieldName
2122−
2123−instance ToJSON ReplicaCount
2124−instance ToJSON ShardCount
2125−instance ToJSON CutoffFrequency
2126−instance ToJSON Analyzer
2127−instance ToJSON MaxExpansions
2128−instance ToJSON Lenient
2129−instance ToJSON Boost
2130−instance ToJSON Version
2131−instance ToJSON Tiebreaker
2132−instance ToJSON MinimumMatch
2133−instance ToJSON DisableCoord
2134−instance ToJSON PrefixLength
2135−instance ToJSON Fuzziness
2136−instance ToJSON IgnoreTermFrequency
2137−instance ToJSON MaxQueryTerms
2138−instance ToJSON TypeName
2139−instance ToJSON IndexName
2140−instance ToJSON TemplateName
2141−instance ToJSON TemplatePattern
2142−instance ToJSON BoostTerms
2143−instance ToJSON MaxWordLength
2144−instance ToJSON MinWordLength
2145−instance ToJSON MaxDocFrequency
2146−instance ToJSON MinDocFrequency
2147−instance ToJSON PhraseSlop
2148−instance ToJSON StopWord
2149−instance ToJSON QueryPath
2150−instance ToJSON MinimumTermFrequency
2151−instance ToJSON PercentMatch
2152−instance ToJSON MappingName
2153−instance ToJSON DocId
2154−instance ToJSON QueryString
2155−instance ToJSON AllowLeadingWildcard
2156−instance ToJSON LowercaseExpanded
2157−instance ToJSON AnalyzeWildcard
2158−instance ToJSON GeneratePhraseQueries
2159−instance ToJSON Locale
2160−instance ToJSON EnablePositionIncrements
2161−instance FromJSON Version
2162−instance FromJSON IndexName
2163−instance FromJSON MappingName
2164−instance FromJSON DocId
2165−
2166−
2167−instance FromJSON Status where
2168− parseJSON (Object v) = Status <$>
2169− v .:? "ok" <*>
2170− v .: "status" <*>
2171− v .: "name" <*>
2172− v .: "version" <*>
2173− v .: "tagline"
2174− parseJSON _ = empty
2175−
2176−
2177−instance ToJSON IndexSettings where
2178− toJSON (IndexSettings s r) = object ["settings" .=
2179− object ["index" .=
2180− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2181− ]
2182− ]
2183−
2184−instance ToJSON IndexSettingUpdate where
2185− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2186− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2187− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2188− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2189− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2190− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2191− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2192− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2193− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2194− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2195− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2196− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2197− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2198− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2199− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2200− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2201− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2202− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2203− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2204− toJSON (RoutingAllocationDisable x) = oPath ("index" :| ["routing", "allocation", "disable_allocation"]) x
2205− toJSON (RoutingAllocationDisableNew x) = oPath ("index" :| ["routing", "allocation", "disable_new_allocation"]) x
2206− toJSON (RoutingAllocationDisableReplica x) = oPath ("index" :| ["routing", "allocation", "disable_replica_allocation"]) x
2207− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2208− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2209− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2210− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2211− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2212− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2213− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2214− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2215− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2216−
2217−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2218−oPath (k :| []) v = object [k .= v]
2219−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2220−
2221−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2222−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2223− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2224−
2225−instance ToJSON ReplicaBounds where
2226− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2227− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2228− toJSON ReplicasUnbounded = Bool False
2229−
2230−instance ToJSON AllocationPolicy where
2231− toJSON AllocAll = String "all"
2232− toJSON AllocPrimaries = String "primaries"
2233− toJSON AllocNewPrimaries = String "new_primaries"
2234− toJSON AllocNone = String "none"
2235−
2236−instance ToJSON InitialShardCount where
2237− toJSON QuorumShards = String "quorum"
2238− toJSON QuorumMinus1Shards = String "quorum-1"
2239− toJSON FullShards = String "full"
2240− toJSON FullMinus1Shards = String "full-1"
2241− toJSON (ExplicitShards x) = toJSON x
2242−
2243−instance ToJSON FSType where
2244− toJSON FSSimple = "simple"
2245− toJSON FSBuffered = "buffered"
2246−
2247−instance ToJSON CompoundFormat where
2248− toJSON (CompoundFileFormat x) = Bool x
2249− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
2250−
2251−instance ToJSON NominalDiffTimeJSON where
2252− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
2253−
2254−instance ToJSON IndexTemplate where
2255− toJSON (IndexTemplate p s m) = merge
2256− (object [ "template" .= p
2257− , "mappings" .= foldl' merge (object []) m
2258− ])
2259− (toJSON s)
2260− where
2261− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
2262− merge o Null = o
2263− merge _ _ = undefined
2264−
2265−instance (FromJSON a) => FromJSON (EsResult a) where
2266− parseJSON jsonVal@(Object v) = do
2267− found <- v .:? "found" .!= False
2268− fr <- if found
2269− then parseJSON jsonVal
2270− else return Nothing
2271− EsResult <$> v .: "_index" <*>
2272− v .: "_type" <*>
2273− v .: "_id" <*>
2274− pure fr
2275− parseJSON _ = empty
2276−
2277−instance (FromJSON a) => FromJSON (EsResultFound a) where
2278− parseJSON (Object v) = EsResultFound <$>
2279− v .: "_version" <*>
2280− v .: "_source"
2281− parseJSON _ = empty
2282−
2283−instance ToJSON Search where
2284− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
2285− omitNulls [ "query" .= query
2286− , "filter" .= sFilter
2287− , "sort" .= sort
2288− , "aggregations" .= searchAggs
2289− , "highlight" .= highlight
2290− , "from" .= sFrom
2291− , "size" .= sSize
2292− , "track_scores" .= sTrackSortScores
2293− , "fields" .= sFields
2294− , "_source" .= sSource]
2295−
488+ deriving (Eq, Show)
2296489
2297490instance ToJSON Source where
2298491 toJSON NoSource = toJSON False
2299492 toJSON (SourcePatterns patterns) = toJSON patterns
2300− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
494+
495+data PatternOrPatterns = PopPattern Pattern
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
2301497
2302498instance ToJSON PatternOrPatterns where
2303499 toJSON (PopPattern pattern) = toJSON pattern
2304500 toJSON (PopPatterns patterns) = toJSON patterns
2305501
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
504+
2306505instance ToJSON Include where
2307506 toJSON (Include patterns) = toJSON patterns
2308507
2309508instance ToJSON Exclude where
2310509 toJSON (Exclude patterns) = toJSON patterns
2311510
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
512+
2312513instance ToJSON Pattern where
2313514 toJSON (Pattern pattern) = toJSON pattern
2314515
2315−
2316−instance ToJSON FieldHighlight where
2317− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
2318− object [ fName .= fSettings ]
2319− toJSON (FieldHighlight (FieldName fName) Nothing) =
2320− object [ fName .= emptyObject ]
2321−
2322−instance ToJSON Highlights where
2323− toJSON (Highlights global fields) =
2324− omitNulls (("fields" .= fields)
2325− : highlightSettingsPairs global)
2326−
2327−instance ToJSON HighlightSettings where
2328− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
2329−
2330−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
2331−highlightSettingsPairs Nothing = []
2332−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
2333−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
2334−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
2335−
2336−
2337−plainHighPairs :: Maybe PlainHighlight -> [Pair]
2338−plainHighPairs Nothing = []
2339−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
2340− [ "type" .= String "plain"]
2341− ++ commonHighlightPairs plCom
2342− ++ nonPostingsToPairs plNonPost
2343−
2344−postHighPairs :: Maybe PostingsHighlight -> [Pair]
2345−postHighPairs Nothing = []
2346−postHighPairs (Just (PostingsHighlight pCom)) =
2347− ("type" .= String "postings")
2348− : commonHighlightPairs pCom
2349−
2350−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
2351−fastVectorHighPairs Nothing = []
2352−fastVectorHighPairs (Just
2353− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
2354− fvBoundMaxScan fvFragOff fvMatchedFields
2355− fvPhraseLim)) =
2356− [ "type" .= String "fvh"
2357− , "boundary_chars" .= fvBoundChars
2358− , "boundary_max_scan" .= fvBoundMaxScan
2359− , "fragment_offset" .= fvFragOff
2360− , "matched_fields" .= fvMatchedFields
2361− , "phraseLimit" .= fvPhraseLim]
2362− ++ commonHighlightPairs fvCom
2363− ++ nonPostingsToPairs fvNonPostSettings
2364−
2365−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
2366−commonHighlightPairs Nothing = []
2367−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
2368− chNoMatchSize chHighlightQuery
2369− chRequireFieldMatch)) =
2370− [ "order" .= chScore
2371− , "force_source" .= chForceSource
2372− , "encoder" .= chEncoder
2373− , "no_match_size" .= chNoMatchSize
2374− , "highlight_query" .= chHighlightQuery
2375− , "require_fieldMatch" .= chRequireFieldMatch]
2376− ++ highlightTagToPairs chTag
2377−
2378−
2379−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
2380−nonPostingsToPairs Nothing = []
2381−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
2382− [ "fragment_size" .= npFragSize
2383− , "number_of_fragments" .= npNumOfFrags]
2384−
2385−
2386−
2387−instance ToJSON HighlightEncoder where
2388− toJSON DefaultEncoder = String "default"
2389− toJSON HTMLEncoder = String "html"
2390−
2391−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
2392−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
2393−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
2394− , "post_tags" .= post]
2395−highlightTagToPairs Nothing = []
2396−
2397−instance ToJSON SortSpec where
2398− toJSON (DefaultSortSpec
2399− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
2400− dsSortMode dsMissingSort dsNestedFilter)) =
2401− object [dsSortFieldName .= omitNulls base] where
2402− base = [ "order" .= dsSortOrder
2403− , "ignore_unmapped" .= dsIgnoreUnmapped
2404− , "mode" .= dsSortMode
2405− , "missing" .= dsMissingSort
2406− , "nested_filter" .= dsNestedFilter ]
2407−
2408− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
2409− object [ "unit" .= units
2410− , field .= gdsLatLon
2411− , "order" .= gdsSortOrder ]
2412−
2413−
2414−instance ToJSON SortOrder where
2415− toJSON Ascending = String "asc"
2416− toJSON Descending = String "desc"
2417−
2418−
2419−instance ToJSON SortMode where
2420− toJSON SortMin = String "min"
2421− toJSON SortMax = String "max"
2422− toJSON SortSum = String "sum"
2423− toJSON SortAvg = String "avg"
2424−
2425−
2426−instance ToJSON Missing where
2427− toJSON LastMissing = String "_last"
2428− toJSON FirstMissing = String "_first"
2429− toJSON (CustomMissing txt) = String txt
2430−
2431−
2432−instance ToJSON ScoreType where
2433− toJSON ScoreTypeMax = "max"
2434− toJSON ScoreTypeAvg = "avg"
2435− toJSON ScoreTypeSum = "sum"
2436− toJSON ScoreTypeNone = "none"
2437−
2438−
2439−instance ToJSON Distance where
2440− toJSON (Distance dCoefficient dUnit) =
2441− String boltedTogether where
2442− coefText = showText dCoefficient
2443− (String unitText) = toJSON dUnit
2444− boltedTogether = mappend coefText unitText
2445−
2446−
2447−instance ToJSON DistanceUnit where
2448− toJSON Miles = String "mi"
2449− toJSON Yards = String "yd"
2450− toJSON Feet = String "ft"
2451− toJSON Inches = String "in"
2452− toJSON Kilometers = String "km"
2453− toJSON Meters = String "m"
2454− toJSON Centimeters = String "cm"
2455− toJSON Millimeters = String "mm"
2456− toJSON NauticalMiles = String "nmi"
2457−
2458−
2459−instance ToJSON DistanceType where
2460− toJSON Arc = String "arc"
2461− toJSON SloppyArc = String "sloppy_arc"
2462− toJSON Plane = String "plane"
2463−
2464−
2465−instance ToJSON OptimizeBbox where
2466− toJSON NoOptimizeBbox = String "none"
2467− toJSON (OptimizeGeoFilterType gft) = toJSON gft
2468−
2469−
2470−instance ToJSON GeoBoundingBoxConstraint where
2471− toJSON (GeoBoundingBoxConstraint
2472− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
2473− object [gbbcGeoBBField .= gbbcConstraintBox
2474− , "_cache" .= cache
2475− , "type" .= type']
2476−
2477−
2478−instance ToJSON GeoFilterType where
2479− toJSON GeoFilterMemory = String "memory"
2480− toJSON GeoFilterIndexed = String "indexed"
2481−
2482−
2483−instance ToJSON GeoBoundingBox where
2484− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
2485− object ["top_left" .= gbbTopLeft
2486− , "bottom_right" .= gbbBottomRight]
2487−
2488−
2489−instance ToJSON LatLon where
2490− toJSON (LatLon lLat lLon) =
2491− object ["lat" .= lLat
2492− , "lon" .= lLon]
2493−
2494−
2495−-- index for smaller ranges, fielddata for longer ranges
2496−instance ToJSON RangeExecution where
2497− toJSON RangeExecutionIndex = "index"
2498− toJSON RangeExecutionFielddata = "fielddata"
2499−
2500−
2501−instance ToJSON RegexpFlags where
2502− toJSON AllRegexpFlags = String "ALL"
2503− toJSON NoRegexpFlags = String "NONE"
2504− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
2505− where flagStrs = map flagStr . nub $ h:fs
2506− flagStr AnyString = "ANYSTRING"
2507− flagStr Automaton = "AUTOMATON"
2508− flagStr Complement = "COMPLEMENT"
2509− flagStr Empty = "EMPTY"
2510− flagStr Intersection = "INTERSECTION"
2511− flagStr Interval = "INTERVAL"
2512−
2513−instance ToJSON Term where
2514− toJSON (Term field value) = object ["term" .= object
2515− [field .= value]]
2516−
2517−
2518−instance ToJSON BoolMatch where
2519− toJSON (MustMatch term cache) = object ["must" .= term,
2520− "_cache" .= cache]
2521− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
2522− "_cache" .= cache]
2523− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
2524− "_cache" .= cache]
2525−
516+data SearchResult a =
517+ SearchResult { took :: Int
518+ , timedOut :: Bool
519+ , shards :: ShardResult
520+ , searchHits :: SearchHits a
521+ , aggregations :: Maybe AggregationResults
522+ , scrollId :: Maybe ScrollId
523+ -- ^ Only one Suggestion request / response per
524+ -- Search is supported.
525+ , suggest :: Maybe NamedSuggestionResponse
526+ }
527+ deriving (Eq, Show)
2526528
2527529instance (FromJSON a) => FromJSON (SearchResult a) where
2528530 parseJSON (Object v) = SearchResult <$>
@@ -2531,52 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
2531533 v .: "_shards" <*>
2532534 v .: "hits" <*>
2533535 v .:? "aggregations" <*>
2534− v .:? "_scroll_id"
2535− parseJSON _ = empty
2536−
2537−instance (FromJSON a) => FromJSON (SearchHits a) where
2538− parseJSON (Object v) = SearchHits <$>
2539− v .: "total" <*>
2540− v .: "max_score" <*>
2541− v .: "hits"
536+ v .:? "_scroll_id" <*>
537+ v .:? "suggest"
2542538 parseJSON _ = empty
2543539
2544−instance (FromJSON a) => FromJSON (Hit a) where
2545− parseJSON (Object v) = Hit <$>
2546− v .: "_index" <*>
2547− v .: "_type" <*>
2548− v .: "_id" <*>
2549− v .: "_score" <*>
2550− v .: "_source" <*>
2551− v .:? "highlight"
2552− parseJSON _ = empty
2553−
2554−instance FromJSON ShardResult where
2555− parseJSON (Object v) = ShardResult <$>
2556− v .: "total" <*>
2557− v .: "successful" <*>
2558− v .: "failed"
2559− parseJSON _ = empty
2560−
2561−
2562−instance FromJSON DocVersion where
2563− parseJSON v = do
2564− i <- parseJSON v
2565− maybe (fail "DocVersion out of range") return $ mkDocVersion i
2566−
2567−instance Bounded DocVersion where
2568− minBound = DocVersion 1
2569− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
2570−
2571−instance Enum DocVersion where
2572− succ x
2573− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
2574− | otherwise = succError "DocVersion"
2575− pred x
2576− | x /= minBound = DocVersion (pred $ docVersionNumber x)
2577− | otherwise = predError "DocVersion"
2578− toEnum i =
2579− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
2580− fromEnum = docVersionNumber
2581− enumFrom = boundedEnumFrom
2582− enumFromThen = boundedEnumFromThen
540+newtype ScrollId =
541+ ScrollId Text
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)