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