@@ -1,8 +1,8 @@
1+{-# LANGUAGE DeriveGeneric #-}
12{-# LANGUAGE FlexibleContexts #-}
23{-# LANGUAGE FlexibleInstances #-}
34{-# LANGUAGE GeneralizedNewtypeDeriving #-}
45{-# 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, 2018 Chris Allen
13+-- Copyright : (C) 2014 Chris Allen
1414-- License : BSD-style (see the file LICENSE)
1515-- Maintainer : Chris Allen <cma@bitemyapp.com
1616-- Stability : provisional
17−-- Portability : RecordWildCards
17+-- Portability : DeriveGeneric, 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,53 +42,26 @@ module Database.Bloodhound.Types
4242 , mkTermsAggregation
4343 , mkTermsScriptAggregation
4444 , mkDateHistogram
45− , mkCardinalityAggregation
4645 , mkDocVersion
47− , mkStatsAggregation
48− , mkExtendedStatsAggregation
4946 , docVersionNumber
50− , toMissing
5147 , toTerms
5248 , toDateHistogram
53− , toTopHits
5449 , omitNulls
5550 , BH(..)
5651 , runBH
57− , BHEnv
58− , bhServer
59− , bhManager
60− , bhRequestHook
61− , mkBHEnv
52+ , BHEnv(..)
6253 , MonadBH(..)
6354 , Version(..)
64− , VersionNumber(..)
65− , MaybeNA(..)
66− , BuildHash(..)
6755 , Status(..)
6856 , Existence(..)
6957 , NullValue(..)
7058 , IndexSettings(..)
71− , UpdatableIndexSetting(..)
72− , IndexSettingsSummary(..)
73− , AllocationPolicy(..)
74− , Compression(..)
75− , ReplicaBounds(..)
76− , Bytes(..)
77− , gigabytes
78− , megabytes
79− , kilobytes
80− , FSType(..)
81− , InitialShardCount(..)
82− , NodeAttrFilter(..)
83− , NodeAttrName(..)
84− , CompoundFormat(..)
8559 , IndexTemplate(..)
8660 , Server(..)
8761 , Reply
8862 , EsResult(..)
8963 , EsResultFound(..)
9064 , EsError(..)
91− , EsProtocolException(..)
9265 , IndexAlias(..)
9366 , IndexAliasName(..)
9467 , IndexAliasAction(..)
@@ -108,7 +81,7 @@ module Database.Bloodhound.Types
10881 , Search(..)
10982 , SearchType(..)
11083 , SearchResult(..)
111− , ScrollId(..)
84+ , ScrollId
11285 , SearchHits(..)
11386 , TrackSortScores
11487 , From(..)
@@ -120,8 +93,8 @@ module Database.Bloodhound.Types
12093 , Pattern(..)
12194 , ShardResult(..)
12295 , Hit(..)
123− , HitFields(..)
12496 , Filter(..)
97+ , Seminearring(..)
12598 , BoolMatch(..)
12699 , Term(..)
127100 , GeoPoint(..)
@@ -148,22 +121,8 @@ module Database.Bloodhound.Types
148121 , RegexpFlags(..)
149122 , RegexpFlag(..)
150123 , FieldName(..)
151− , ScriptFields(..)
152− , ScriptFieldName
153− , ScriptFieldValue
154124 , Script(..)
155− , ScriptLanguage(..)
156− , ScriptInline(..)
157− , ScriptId(..)
158− , ScriptParams(..)
159− , ScriptParamName
160− , ScriptParamValue
161125 , IndexName(..)
162− , IndexSelection(..)
163− , NodeSelection(..)
164− , NodeSelector(..)
165− , ForceMergeIndexSettings(..)
166− , defaultForceMergeIndexSettings
167126 , TemplateName(..)
168127 , TemplatePattern(..)
169128 , MappingName(..)
@@ -187,19 +146,8 @@ module Database.Bloodhound.Types
187146 , BoolQuery(..)
188147 , BoostingQuery(..)
189148 , 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(..)
202149 , DisMaxQuery(..)
150+ , FilteredQuery(..)
203151 , FuzzyLikeThisQuery(..)
204152 , FuzzyLikeFieldQuery(..)
205153 , FuzzyQuery(..)
@@ -215,16 +163,10 @@ module Database.Bloodhound.Types
215163 , RangeQuery(..)
216164 , RegexpQuery(..)
217165 , QueryString(..)
218− , TemplateQueryInline(..)
219− , TemplateQueryKeyValuePairs(..)
220− , WildcardQuery(..)
221166 , BooleanOperator(..)
222167 , ZeroTermsQuery(..)
223168 , CutoffFrequency(..)
224169 , Analyzer(..)
225− , Tokenizer(..)
226− , TokenFilter(..)
227− , CharFilter(..)
228170 , MaxExpansions(..)
229171 , Lenient(..)
230172 , MatchQueryType(..)
@@ -271,118 +213,16 @@ module Database.Bloodhound.Types
271213 , CollectionMode(..)
272214 , TermOrder(..)
273215 , 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 (..)
363216
364217 , Aggregation(..)
365218 , Aggregations
366219 , AggregationResults
367− , BucketValue(..)
368220 , Bucket(..)
369221 , BucketAggregation(..)
370222 , TermsAggregation(..)
371− , MissingAggregation(..)
372223 , ValueCountAggregation(..)
373224 , FilterAggregation(..)
374− , CardinalityAggregation(..)
375− , MaxAggregation(..)
376225 , DateHistogramAggregation(..)
377− , DateRangeAggregation(..)
378− , DateRangeAggRange(..)
379− , DateMathExpr(..)
380− , DateMathAnchor(..)
381− , DateMathModifier(..)
382− , DateMathUnit(..)
383− , TopHitsAggregation(..)
384− , StatisticsAggregation(..)
385− , SearchAfterKey
386226
387227 , Highlights(..)
388228 , FieldHighlight(..)
@@ -396,36 +236,540 @@ module Database.Bloodhound.Types
396236 , HighlightTag(..)
397237 , HitHighlight
398238
399− , MissingResult(..)
400239 , TermsResult(..)
401240 , DateHistogramResult(..)
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
241+ ) where
242+
243+import Control.Applicative
244+import Control.Monad.Catch
245+import Control.Monad.Except
246+import Control.Monad.Reader
247+import Control.Monad.State
248+import Control.Monad.Writer
249+import Data.Aeson
250+import Data.Aeson.Types (Pair, Parser, emptyObject,
251+ parseMaybe)
252+import qualified Data.ByteString.Lazy.Char8 as L
253+import Data.Char
254+import Data.Hashable (Hashable)
255+import qualified Data.HashMap.Strict as HM
256+import Data.List (foldl', nub)
257+import Data.List.NonEmpty (NonEmpty (..), toList)
258+import qualified Data.Map.Strict as M
259+import Data.Maybe
260+import Data.Text (Text)
261+import qualified Data.Text as T
262+import Data.Time.Clock (UTCTime)
263+import qualified Data.Traversable as DT
264+import qualified Data.Vector as V
265+import GHC.Enum
266+import GHC.Generics (Generic)
267+import Network.HTTP.Client
268+import qualified Network.HTTP.Types.Method as NHTM
269+
270+import Debug.Trace
271+
272+import Database.Bloodhound.Types.Class
273+
274+-- $setup
275+-- >>> :set -XOverloadedStrings
276+-- >>> import Database.Bloodhound
277+-- >>> let testServer = (Server "http://localhost:9200")
278+-- >>> let testIndex = IndexName "twitter"
279+-- >>> let testMapping = MappingName "tweet"
280+-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
281+
282+-- defaultIndexSettings is exported by Database.Bloodhound as well
283+-- no trailing slashes in servers, library handles building the path.
284+
285+{-| Common environment for Elasticsearch calls. Connections will be
286+ pipelined according to the provided HTTP connection manager.
287+-}
288+data BHEnv = BHEnv { bhServer :: Server
289+ , bhManager :: Manager
290+ }
291+
292+{-| All API calls to Elasticsearch operate within
293+ MonadBH. The idea is that it can be easily embedded in your
294+ own monad transformer stack. A default instance for a ReaderT and
295+ alias 'BH' is provided for the simple case.
296+-}
297+class (Functor m, Applicative m, MonadIO m) => MonadBH m where
298+ getBHEnv :: m BHEnv
299+
300+newtype BH m a = BH {
301+ unBH :: ReaderT BHEnv m a
302+ } deriving ( Functor
303+ , Applicative
304+ , Monad
305+ , MonadIO
306+ , MonadState s
307+ , MonadWriter w
308+ , MonadError e
309+ , Alternative
310+ , MonadPlus
311+ , MonadFix
312+ , MonadThrow
313+ , MonadCatch
314+ , MonadMask)
315+
316+instance MonadTrans BH where
317+ lift = BH . lift
318+
319+instance (MonadReader r m) => MonadReader r (BH m) where
320+ ask = lift ask
321+ local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
322+ local f (m r)
323+
324+instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
325+ getBHEnv = BH getBHEnv
326+
327+
328+instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where
329+ getBHEnv = ask
330+
331+runBH :: BHEnv -> BH m a -> m a
332+runBH e f = runReaderT (unBH f) e
333+
334+{-| 'Version' is embedded in 'Status' -}
335+data Version = Version { number :: Text
336+ , build_hash :: Text
337+ , build_timestamp :: UTCTime
338+ , build_snapshot :: Bool
339+ , lucene_version :: Text } deriving (Eq, Show, Generic)
340+
341+{-| 'Status' is a data type for describing the JSON body returned by
342+ Elasticsearch when you query its status. This was deprecated in 1.2.0.
343+
344+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
345+-}
346+
347+data Status = Status { ok :: Maybe Bool
348+ , status :: Int
349+ , name :: Text
350+ , version :: Version
351+ , tagline :: Text } deriving (Eq, Show)
352+
353+{-| 'IndexSettings' is used to configure the shards and replicas when you create
354+ an Elasticsearch Index.
355+
356+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
357+-}
358+
359+data IndexSettings =
360+ IndexSettings { indexShards :: ShardCount
361+ , indexReplicas :: ReplicaCount } deriving (Eq, Show)
362+
363+{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
364+defaultIndexSettings :: IndexSettings
365+defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
366+
367+{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
368+type Reply = Network.HTTP.Client.Response L.ByteString
369+type Method = NHTM.Method
370+
371+{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
372+
373+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
374+-}
375+data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show)
376+
377+data FieldType = GeoPointType
378+ | GeoShapeType
379+ | FloatType
380+ | IntegerType
381+ | LongType
382+ | ShortType
383+ | ByteType deriving (Eq, Show)
384+
385+data FieldDefinition =
386+ FieldDefinition { fieldType :: FieldType } deriving (Eq, Show)
387+
388+{-| An 'IndexTemplate' defines a template that will automatically be
389+ applied to new indices created. The templates include both
390+ 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
391+ controls if the template will be applied to the index created.
392+ Specify mappings as follows: @[toJSON TweetMapping, ...]@
393+
394+ https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
395+-}
396+data IndexTemplate =
397+ IndexTemplate { templatePattern :: TemplatePattern
398+ , templateSettings :: Maybe IndexSettings
399+ , templateMappings :: [Value]
400+ }
401+
402+data MappingField =
403+ MappingField { mappingFieldName :: FieldName
404+ , fieldDefinition :: FieldDefinition } deriving (Eq, Show)
405+
406+{-| Support for type reification of 'Mapping's is currently incomplete, for
407+ now the mapping API verbiage expects a 'ToJSON'able blob.
408+
409+ Indexes have mappings, mappings are schemas for the documents contained in the
410+ index. I'd recommend having only one mapping per index, always having a mapping,
411+ and keeping different kinds of documents separated if possible.
412+-}
413+data Mapping = Mapping { typeName :: TypeName
414+ , mappingFields :: [MappingField] } deriving (Eq, Show)
415+
416+{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
417+ operation index, create, delete, and update. 'BulkIndex' behaves like an
418+ "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
419+
420+ <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
421+-}
422+data BulkOperation =
423+ BulkIndex IndexName MappingName DocId Value
424+ | BulkCreate IndexName MappingName DocId Value
425+ | BulkDelete IndexName MappingName DocId
426+ | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show)
427+
428+{-| 'EsResult' describes the standard wrapper JSON document that you see in
429+ successful Elasticsearch lookups or lookups that couldn't find the document.
430+-}
431+data EsResult a = EsResult { _index :: Text
432+ , _type :: Text
433+ , _id :: Text
434+ , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show)
435+
436+{-| 'EsResultFound' contains the document and its metadata inside of an
437+ 'EsResult' when the document was successfully found.
438+-}
439+data EsResultFound a = EsResultFound { _version :: DocVersion
440+ , _source :: a } deriving (Eq, Show)
441+
442+{-| 'EsError' is the generic type that will be returned when there was a
443+ problem. If you can't parse the expected response, its a good idea to
444+ try parsing this.
445+-}
446+data EsError = EsError { errorStatus :: Int
447+ , errorMessage :: Text } deriving (Eq, Show)
448+
449+data IndexAlias = IndexAlias { srcIndex :: IndexName
450+ , indexAlias :: IndexAliasName } deriving (Eq, Show)
451+
452+newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Show, ToJSON)
453+
454+data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
455+ | RemoveAlias IndexAlias deriving (Show, Eq)
456+
457+data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
458+ , aliasCreateFilter :: Maybe Filter}
459+ deriving (Show, Eq)
460+
461+data AliasRouting = AllAliasRouting RoutingValue
462+ | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
463+ deriving (Show, Eq)
464+
465+newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Show, Eq)
466+
467+newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Show, Eq, ToJSON, FromJSON)
468+
469+newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Show, Eq, ToJSON, FromJSON)
470+
471+newtype IndexAliasesSummary = IndexAliasesSummary [IndexAliasSummary]
472+
473+data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
474+ , indexAliasSummaryCreate :: IndexAliasCreate}
475+
476+{-| 'DocVersion' is an integer version number for a document between 1
477+and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
478+-}
479+newtype DocVersion = DocVersion {
480+ docVersionNumber :: Int
481+ } deriving (Eq, Show, Ord, ToJSON)
482+
483+-- | Smart constructor for in-range doc version
484+mkDocVersion :: Int -> Maybe DocVersion
485+mkDocVersion i
486+ | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
487+ Just $ DocVersion i
488+ | otherwise = Nothing
489+
490+
491+{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
492+own version numbers instead of ones from ES.
493+-}
494+newtype ExternalDocVersion = ExternalDocVersion DocVersion
495+ deriving (Eq, Show, Ord, Bounded, Enum, ToJSON)
496+
497+{-| 'VersionControl' is specified when indexing documents as a
498+optimistic concurrency control.
499+-}
500+data VersionControl = NoVersionControl
501+ -- ^ Don't send a version. This is a pure overwrite.
502+ | InternalVersion DocVersion
503+ -- ^ Use the default ES versioning scheme. Only
504+ -- index the document if the version is the same
505+ -- as the one specified. Only applicable to
506+ -- updates, as you should be getting Version from
507+ -- a search result.
508+ | ExternalGT ExternalDocVersion
509+ -- ^ Use your own version numbering. Only index
510+ -- the document if the version is strictly higher
511+ -- OR the document doesn't exist. The given
512+ -- version will be used as the new version number
513+ -- for the stored document. N.B. All updates must
514+ -- increment this number, meaning there is some
515+ -- global, external ordering of updates.
516+ | ExternalGTE ExternalDocVersion
517+ -- ^ Use your own version numbering. Only index
518+ -- the document if the version is equal or higher
519+ -- than the stored version. Will succeed if there
520+ -- is no existing document. The given version will
521+ -- be used as the new version number for the
522+ -- stored document. Use with care, as this could
523+ -- result in data loss.
524+ | ForceVersion ExternalDocVersion
525+ -- ^ The document will always be indexed and the
526+ -- given version will be the new version. This is
527+ -- typically used for correcting errors. Use with
528+ -- care, as this could result in data loss.
529+ deriving (Show, Eq, Ord)
530+
531+{-| 'DocumentParent' is used to specify a parent document.
532+-}
533+newtype DocumentParent = DocumentParent DocId
534+ deriving (Eq, Show)
535+
536+{-| 'IndexDocumentSettings' are special settings supplied when indexing
537+a document. For the best backwards compatiblity when new fields are
538+added, you should probably prefer to start with 'defaultIndexDocumentSettings'
539+-}
540+data IndexDocumentSettings =
541+ IndexDocumentSettings { idsVersionControl :: VersionControl
542+ , idsParent :: Maybe DocumentParent
543+ } deriving (Eq, Show)
544+
545+{-| Reasonable default settings. Chooses no version control and no parent.
546+-}
547+defaultIndexDocumentSettings :: IndexDocumentSettings
548+defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
549+
550+{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
551+ dependent with later sorts acting as tie-breakers for earlier sorts.
552+-}
553+type Sort = [SortSpec]
554+
555+{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
556+ 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
557+ 'DistanceUnit' to express "nearness" to a single geographical point as a
558+ sort specification.
559+
560+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
561+-}
562+data SortSpec = DefaultSortSpec DefaultSort
563+ | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show)
564+
565+{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
566+ 'mkSort' convenience function for when you want to specify only the most
567+ common parameters.
568+
569+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
570+-}
571+data DefaultSort =
572+ DefaultSort { sortFieldName :: FieldName
573+ , sortOrder :: SortOrder
574+ -- default False
575+ , ignoreUnmapped :: Bool
576+ , sortMode :: Maybe SortMode
577+ , missingSort :: Maybe Missing
578+ , nestedFilter :: Maybe Filter } deriving (Eq, Show)
579+
580+{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
581+ encoded into "asc" or "desc" when turned into JSON.
582+
583+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
584+-}
585+data SortOrder = Ascending
586+ | Descending deriving (Eq, Show)
587+
588+{-| 'Missing' prescribes how to handle missing fields. A missing field can be
589+ sorted last, first, or using a custom value as a substitute.
590+
591+<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
592+-}
593+data Missing = LastMissing
594+ | FirstMissing
595+ | CustomMissing Text deriving (Eq, Show)
596+
597+{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
598+
599+http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
600+-}
601+data SortMode = SortMin
602+ | SortMax
603+ | SortSum
604+ | SortAvg deriving (Eq, Show)
605+
606+{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
607+ that you can concisely describe the usual kind of 'SortSpec's you want.
608+-}
609+mkSort :: FieldName -> SortOrder -> DefaultSort
610+mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
611+
612+{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
613+ 'Query's cannot be cached.
614+-}
615+type Cache = Bool -- caching on/off
616+defaultCache :: Cache
617+defaultCache = False
618+
619+{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
620+-}
621+type PrefixValue = Text
622+
623+{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
624+ JSON encoding baked in. Used all over the place.
625+-}
626+data BooleanOperator = And | Or deriving (Eq, Show)
627+
628+{-| 'ShardCount' is part of 'IndexSettings'
629+-}
630+newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
631+
632+{-| 'ReplicaCount' is part of 'IndexSettings'
633+-}
634+newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
635+
636+{-| 'Server' is used with the client functions to point at the ES instance
637+-}
638+newtype Server = Server Text deriving (Eq, Show)
639+
640+{-| 'IndexName' is used to describe which index to query/create/delete
641+-}
642+newtype IndexName = IndexName Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
643+
644+{-| 'TemplateName' is used to describe which template to query/create/delete
645+-}
646+newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
647+
648+{-| 'TemplatePattern' represents a pattern which is matched against index names
649+-}
650+newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
651+
652+{-| 'MappingName' is part of mappings which are how ES describes and schematizes
653+ the data in the indices.
654+-}
655+newtype MappingName = MappingName Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
656+
657+{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
658+ Can be set by the user or created by ES itself. Often used in client
659+ functions for poking at specific documents.
660+-}
661+newtype DocId = DocId Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
662+
663+{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
664+-}
665+newtype QueryString = QueryString Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
666+
667+{-| 'FieldName' is used all over the place wherever a specific field within
668+ a document needs to be specified, usually in 'Query's or 'Filter's.
669+-}
670+newtype FieldName = FieldName Text deriving (Eq, Show, ToJSON, FromJSON)
671+
672+
673+{-| 'Script' is often used in place of 'FieldName' to specify more
674+complex ways of extracting a value from a document.
675+-}
676+newtype Script = Script { scriptText :: Text } deriving (Eq, Show)
677+
678+{-| 'CacheName' is used in 'RegexpFilter' for describing the
679+ 'CacheKey' keyed caching behavior.
680+-}
681+newtype CacheName = CacheName Text deriving (Eq, Show, ToJSON, FromJSON)
682+
683+{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
684+-}
685+newtype CacheKey =
686+ CacheKey Text deriving (Eq, Show, ToJSON, FromJSON)
687+newtype Existence =
688+ Existence Bool deriving (Eq, Show, ToJSON, FromJSON)
689+newtype NullValue =
690+ NullValue Bool deriving (Eq, Show, ToJSON, FromJSON)
691+newtype CutoffFrequency =
692+ CutoffFrequency Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
693+newtype Analyzer =
694+ Analyzer Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
695+newtype MaxExpansions =
696+ MaxExpansions Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
697+
698+{-| 'Lenient', if set to true, will cause format based failures to be
699+ ignored. I don't know what the bloody default is, Elasticsearch
700+ documentation didn't say what it was. Let me know if you figure it out.
701+-}
702+newtype Lenient =
703+ Lenient Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
704+newtype Tiebreaker =
705+ Tiebreaker Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
706+newtype Boost =
707+ Boost Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
708+newtype BoostTerms =
709+ BoostTerms Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
710+
711+{-| 'MinimumMatch' controls how many should clauses in the bool query should
712+ match. Can be an absolute value (2) or a percentage (30%) or a
713+ combination of both.
714+-}
715+newtype MinimumMatch =
716+ MinimumMatch Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
717+newtype DisableCoord =
718+ DisableCoord Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
719+newtype IgnoreTermFrequency =
720+ IgnoreTermFrequency Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
721+newtype MinimumTermFrequency =
722+ MinimumTermFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
723+newtype MaxQueryTerms =
724+ MaxQueryTerms Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
725+newtype Fuzziness =
726+ Fuzziness Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
727+
728+{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
729+newtype PrefixLength =
730+ PrefixLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
731+newtype TypeName =
732+ TypeName Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
733+newtype PercentMatch =
734+ PercentMatch Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
735+newtype StopWord =
736+ StopWord Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
737+newtype QueryPath =
738+ QueryPath Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
739+
740+{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
741+ heavy, because all terms in the index need to be examined, just in case
742+ they match. Leading wildcards can be disabled by setting
743+ 'AllowLeadingWildcard' to false. -}
744+newtype AllowLeadingWildcard =
745+ AllowLeadingWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
746+newtype LowercaseExpanded =
747+ LowercaseExpanded Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
748+newtype EnablePositionIncrements =
749+ EnablePositionIncrements Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
750+
751+{-| By default, wildcard terms in a query are not analyzed.
752+ Setting 'AnalyzeWildcard' to true enables best-effort analysis.
753+-}
754+newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
755+
756+{-| 'GeneratePhraseQueries' defaults to false.
757+-}
758+newtype GeneratePhraseQueries =
759+ GeneratePhraseQueries Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
760+
761+{-| 'Locale' is used for string conversions - defaults to ROOT.
762+-}
763+newtype Locale = Locale Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
764+newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
765+newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
766+
767+{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
768+ phrase matches. Default is 0.
769+-}
770+newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
771+newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
772+newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
429773
430774{-| 'unpackId' is a silly convenience function that gets used once.
431775-}
@@ -433,6 +777,8 @@ unpackId :: DocId -> Text
433777unpackId (DocId docId) = docId
434778
435779type TrackSortScores = Bool
780+newtype From = From Int deriving (Eq, Show, ToJSON)
781+newtype Size = Size Int deriving (Eq, Show, ToJSON)
436782
437783data Search = Search { queryBody :: Maybe Query
438784 , filterBody :: Maybe Filter
@@ -444,87 +790,2218 @@ data Search = Search { queryBody :: Maybe Query
444790 , from :: From
445791 , size :: Size
446792 , searchType :: SearchType
447− , searchAfterKey :: Maybe SearchAfterKey
448793 , fields :: Maybe [FieldName]
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] [] []
794+ , source :: Maybe Source } deriving (Eq, Show)
479795
480796data SearchType = SearchTypeQueryThenFetch
481797 | SearchTypeDfsQueryThenFetch
798+ | SearchTypeCount
799+ | SearchTypeScan
800+ | SearchTypeQueryAndFetch
801+ | SearchTypeDfsQueryAndFetch
482802 deriving (Eq, Show)
483803
484804data Source =
485805 NoSource
486806 | SourcePatterns PatternOrPatterns
487807 | SourceIncludeExclude Include Exclude
488− deriving (Eq, Show)
808+ deriving (Show, Eq)
809+
810+data PatternOrPatterns = PopPattern Pattern
811+ | PopPatterns [Pattern] deriving (Eq, Show)
812+
813+data Include = Include [Pattern] deriving (Eq, Show)
814+data Exclude = Exclude [Pattern] deriving (Eq, Show)
815+
816+newtype Pattern = Pattern Text deriving (Eq, Show)
817+
818+data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
819+ , highlightFields :: [FieldHighlight]
820+ } deriving (Show, Eq)
821+
822+data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
823+ deriving (Show, Eq)
824+
825+
826+data HighlightSettings = Plain PlainHighlight
827+ | Postings PostingsHighlight
828+ | FastVector FastVectorHighlight
829+ deriving (Show, Eq)
830+data PlainHighlight =
831+ PlainHighlight { plainCommon :: Maybe CommonHighlight
832+ , plainNonPost :: Maybe NonPostings } deriving (Show, Eq)
833+
834+ -- This requires that index_options are set to 'offset' in the mapping.
835+data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq)
836+
837+-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
838+data FastVectorHighlight =
839+ FastVectorHighlight { fvCommon :: Maybe CommonHighlight
840+ , fvNonPostSettings :: Maybe NonPostings
841+ , boundaryChars :: Maybe Text
842+ , boundaryMaxScan :: Maybe Int
843+ , fragmentOffset :: Maybe Int
844+ , matchedFields :: [Text]
845+ , phraseLimit :: Maybe Int
846+ } deriving (Show, Eq)
847+
848+data CommonHighlight =
849+ CommonHighlight { order :: Maybe Text
850+ , forceSource :: Maybe Bool
851+ , tag :: Maybe HighlightTag
852+ , encoder :: Maybe HighlightEncoder
853+ , noMatchSize :: Maybe Int
854+ , highlightQuery :: Maybe Query
855+ , requireFieldMatch :: Maybe Bool
856+ } deriving (Show, Eq)
857+
858+-- Settings that are only applicable to FastVector and Plain highlighters.
859+data NonPostings =
860+ NonPostings { fragmentSize :: Maybe Int
861+ , numberOfFragments :: Maybe Int} deriving (Show, Eq)
862+
863+data HighlightEncoder = DefaultEncoder
864+ | HTMLEncoder
865+ deriving (Show, Eq)
866+
867+-- NOTE: Should the tags use some kind of HTML type, rather than Text?
868+data HighlightTag = TagSchema Text
869+ | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
870+ deriving (Show, Eq)
871+
872+
873+data Query =
874+ TermQuery Term (Maybe Boost)
875+ | TermsQuery (NonEmpty Term)
876+ | QueryMatchQuery MatchQuery
877+ | QueryMultiMatchQuery MultiMatchQuery
878+ | QueryBoolQuery BoolQuery
879+ | QueryBoostingQuery BoostingQuery
880+ | QueryCommonTermsQuery CommonTermsQuery
881+ | ConstantScoreFilter Filter Boost
882+ | ConstantScoreQuery Query Boost
883+ | QueryDisMaxQuery DisMaxQuery
884+ | QueryFilteredQuery FilteredQuery
885+ | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
886+ | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
887+ | QueryFuzzyQuery FuzzyQuery
888+ | QueryHasChildQuery HasChildQuery
889+ | QueryHasParentQuery HasParentQuery
890+ | IdsQuery MappingName [DocId]
891+ | QueryIndicesQuery IndicesQuery
892+ | MatchAllQuery (Maybe Boost)
893+ | QueryMoreLikeThisQuery MoreLikeThisQuery
894+ | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
895+ | QueryNestedQuery NestedQuery
896+ | QueryPrefixQuery PrefixQuery
897+ | QueryQueryStringQuery QueryStringQuery
898+ | QuerySimpleQueryStringQuery SimpleQueryStringQuery
899+ | QueryRangeQuery RangeQuery
900+ | QueryRegexpQuery RegexpQuery
901+ deriving (Eq, Show)
902+
903+data RegexpQuery =
904+ RegexpQuery { regexpQueryField :: FieldName
905+ , regexpQuery :: Regexp
906+ , regexpQueryFlags :: RegexpFlags
907+ , regexpQueryBoost :: Maybe Boost
908+ } deriving (Eq, Show)
909+
910+data RangeQuery =
911+ RangeQuery { rangeQueryField :: FieldName
912+ , rangeQueryRange :: RangeValue
913+ , rangeQueryBoost :: Boost } deriving (Eq, Show)
914+
915+mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
916+mkRangeQuery f r = RangeQuery f r (Boost 1.0)
917+
918+data SimpleQueryStringQuery =
919+ SimpleQueryStringQuery
920+ { simpleQueryStringQuery :: QueryString
921+ , simpleQueryStringField :: Maybe FieldOrFields
922+ , simpleQueryStringOperator :: Maybe BooleanOperator
923+ , simpleQueryStringAnalyzer :: Maybe Analyzer
924+ , simpleQueryStringFlags :: Maybe [SimpleQueryFlag]
925+ , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
926+ , simpleQueryStringLocale :: Maybe Locale
927+ } deriving (Eq, Show)
928+
929+data SimpleQueryFlag =
930+ SimpleQueryAll
931+ | SimpleQueryNone
932+ | SimpleQueryAnd
933+ | SimpleQueryOr
934+ | SimpleQueryPrefix
935+ | SimpleQueryPhrase
936+ | SimpleQueryPrecedence
937+ | SimpleQueryEscape
938+ | SimpleQueryWhitespace
939+ | SimpleQueryFuzzy
940+ | SimpleQueryNear
941+ | SimpleQuerySlop deriving (Eq, Show)
942+
943+-- use_dis_max and tie_breaker when fields are plural?
944+data QueryStringQuery =
945+ QueryStringQuery
946+ { queryStringQuery :: QueryString
947+ , queryStringDefaultField :: Maybe FieldName
948+ , queryStringOperator :: Maybe BooleanOperator
949+ , queryStringAnalyzer :: Maybe Analyzer
950+ , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
951+ , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
952+ , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
953+ , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
954+ , queryStringFuzziness :: Maybe Fuzziness
955+ , queryStringFuzzyPrefixLength :: Maybe PrefixLength
956+ , queryStringPhraseSlop :: Maybe PhraseSlop
957+ , queryStringBoost :: Maybe Boost
958+ , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
959+ , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
960+ , queryStringMinimumShouldMatch :: Maybe MinimumMatch
961+ , queryStringLenient :: Maybe Lenient
962+ , queryStringLocale :: Maybe Locale
963+ } deriving (Eq, Show)
964+
965+mkQueryStringQuery :: QueryString -> QueryStringQuery
966+mkQueryStringQuery qs =
967+ QueryStringQuery qs Nothing Nothing
968+ Nothing Nothing Nothing Nothing
969+ Nothing Nothing Nothing Nothing
970+ Nothing Nothing Nothing Nothing
971+ Nothing Nothing
972+
973+data FieldOrFields = FofField FieldName
974+ | FofFields [FieldName] deriving (Eq, Show)
975+
976+data PrefixQuery =
977+ PrefixQuery
978+ { prefixQueryField :: FieldName
979+ , prefixQueryPrefixValue :: Text
980+ , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show)
981+
982+data NestedQuery =
983+ NestedQuery
984+ { nestedQueryPath :: QueryPath
985+ , nestedQueryScoreType :: ScoreType
986+ , nestedQuery :: Query } deriving (Eq, Show)
987+
988+data MoreLikeThisFieldQuery =
989+ MoreLikeThisFieldQuery
990+ { moreLikeThisFieldText :: Text
991+ , moreLikeThisFieldFields :: FieldName
992+ -- default 0.3 (30%)
993+ , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
994+ , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
995+ , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
996+ , moreLikeThisFieldStopWords :: Maybe [StopWord]
997+ , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
998+ , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
999+ , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1000+ , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1001+ , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1002+ , moreLikeThisFieldBoost :: Maybe Boost
1003+ , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1004+ } deriving (Eq, Show)
1005+
1006+data MoreLikeThisQuery =
1007+ MoreLikeThisQuery
1008+ { moreLikeThisText :: Text
1009+ , moreLikeThisFields :: Maybe [FieldName]
1010+ -- default 0.3 (30%)
1011+ , moreLikeThisPercentMatch :: Maybe PercentMatch
1012+ , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1013+ , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1014+ , moreLikeThisStopWords :: Maybe [StopWord]
1015+ , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1016+ , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1017+ , moreLikeThisMinWordLength :: Maybe MinWordLength
1018+ , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1019+ , moreLikeThisBoostTerms :: Maybe BoostTerms
1020+ , moreLikeThisBoost :: Maybe Boost
1021+ , moreLikeThisAnalyzer :: Maybe Analyzer
1022+ } deriving (Eq, Show)
1023+
1024+data IndicesQuery =
1025+ IndicesQuery
1026+ { indicesQueryIndices :: [IndexName]
1027+ , indicesQuery :: Query
1028+ -- default "all"
1029+ , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show)
1030+
1031+data HasParentQuery =
1032+ HasParentQuery
1033+ { hasParentQueryType :: TypeName
1034+ , hasParentQuery :: Query
1035+ , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1036+
1037+data HasChildQuery =
1038+ HasChildQuery
1039+ { hasChildQueryType :: TypeName
1040+ , hasChildQuery :: Query
1041+ , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show)
1042+
1043+data ScoreType =
1044+ ScoreTypeMax
1045+ | ScoreTypeSum
1046+ | ScoreTypeAvg
1047+ | ScoreTypeNone deriving (Eq, Show)
1048+
1049+data FuzzyQuery =
1050+ FuzzyQuery { fuzzyQueryField :: FieldName
1051+ , fuzzyQueryValue :: Text
1052+ , fuzzyQueryPrefixLength :: PrefixLength
1053+ , fuzzyQueryMaxExpansions :: MaxExpansions
1054+ , fuzzyQueryFuzziness :: Fuzziness
1055+ , fuzzyQueryBoost :: Maybe Boost
1056+ } deriving (Eq, Show)
1057+
1058+data FuzzyLikeFieldQuery =
1059+ FuzzyLikeFieldQuery
1060+ { fuzzyLikeField :: FieldName
1061+ -- anaphora is good for the soul.
1062+ , fuzzyLikeFieldText :: Text
1063+ , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1064+ , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1065+ , fuzzyLikeFieldFuzziness :: Fuzziness
1066+ , fuzzyLikeFieldPrefixLength :: PrefixLength
1067+ , fuzzyLikeFieldBoost :: Boost
1068+ , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1069+ } deriving (Eq, Show)
1070+
1071+data FuzzyLikeThisQuery =
1072+ FuzzyLikeThisQuery
1073+ { fuzzyLikeFields :: [FieldName]
1074+ , fuzzyLikeText :: Text
1075+ , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1076+ , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1077+ , fuzzyLikeFuzziness :: Fuzziness
1078+ , fuzzyLikePrefixLength :: PrefixLength
1079+ , fuzzyLikeBoost :: Boost
1080+ , fuzzyLikeAnalyzer :: Maybe Analyzer
1081+ } deriving (Eq, Show)
1082+
1083+data FilteredQuery =
1084+ FilteredQuery
1085+ { filteredQuery :: Query
1086+ , filteredFilter :: Filter } deriving (Eq, Show)
1087+
1088+data DisMaxQuery =
1089+ DisMaxQuery { disMaxQueries :: [Query]
1090+ -- default 0.0
1091+ , disMaxTiebreaker :: Tiebreaker
1092+ , disMaxBoost :: Maybe Boost
1093+ } deriving (Eq, Show)
1094+
1095+data MatchQuery =
1096+ MatchQuery { matchQueryField :: FieldName
1097+ , matchQueryQueryString :: QueryString
1098+ , matchQueryOperator :: BooleanOperator
1099+ , matchQueryZeroTerms :: ZeroTermsQuery
1100+ , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1101+ , matchQueryMatchType :: Maybe MatchQueryType
1102+ , matchQueryAnalyzer :: Maybe Analyzer
1103+ , matchQueryMaxExpansions :: Maybe MaxExpansions
1104+ , matchQueryLenient :: Maybe Lenient
1105+ , matchQueryBoost :: Maybe Boost } deriving (Eq, Show)
1106+
1107+{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1108+ enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1109+-}
1110+mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1111+mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1112+
1113+data MatchQueryType =
1114+ MatchPhrase
1115+ | MatchPhrasePrefix deriving (Eq, Show)
1116+
1117+data MultiMatchQuery =
1118+ MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1119+ , multiMatchQueryString :: QueryString
1120+ , multiMatchQueryOperator :: BooleanOperator
1121+ , multiMatchQueryZeroTerms :: ZeroTermsQuery
1122+ , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1123+ , multiMatchQueryType :: Maybe MultiMatchQueryType
1124+ , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1125+ , multiMatchQueryAnalyzer :: Maybe Analyzer
1126+ , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1127+ , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show)
1128+
1129+{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1130+ enabling you to provide only the list of 'FieldName's and 'QueryString' to
1131+ make a 'MultiMatchQuery'.
1132+-}
1133+
1134+mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1135+mkMultiMatchQuery matchFields query =
1136+ MultiMatchQuery matchFields query
1137+ Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1138+
1139+data MultiMatchQueryType =
1140+ MultiMatchBestFields
1141+ | MultiMatchMostFields
1142+ | MultiMatchCrossFields
1143+ | MultiMatchPhrase
1144+ | MultiMatchPhrasePrefix deriving (Eq, Show)
1145+
1146+data BoolQuery =
1147+ BoolQuery { boolQueryMustMatch :: [Query]
1148+ , boolQueryMustNotMatch :: [Query]
1149+ , boolQueryShouldMatch :: [Query]
1150+ , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1151+ , boolQueryBoost :: Maybe Boost
1152+ , boolQueryDisableCoord :: Maybe DisableCoord
1153+ } deriving (Eq, Show)
1154+
1155+mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1156+mkBoolQuery must mustNot should =
1157+ BoolQuery must mustNot should Nothing Nothing Nothing
1158+
1159+data BoostingQuery =
1160+ BoostingQuery { positiveQuery :: Query
1161+ , negativeQuery :: Query
1162+ , negativeBoost :: Boost } deriving (Eq, Show)
1163+
1164+data CommonTermsQuery =
1165+ CommonTermsQuery { commonField :: FieldName
1166+ , commonQuery :: QueryString
1167+ , commonCutoffFrequency :: CutoffFrequency
1168+ , commonLowFreqOperator :: BooleanOperator
1169+ , commonHighFreqOperator :: BooleanOperator
1170+ , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1171+ , commonBoost :: Maybe Boost
1172+ , commonAnalyzer :: Maybe Analyzer
1173+ , commonDisableCoord :: Maybe DisableCoord
1174+ } deriving (Eq, Show)
1175+
1176+data CommonMinimumMatch =
1177+ CommonMinimumMatchHighLow MinimumMatchHighLow
1178+ | CommonMinimumMatch MinimumMatch
1179+ deriving (Eq, Show)
1180+
1181+data MinimumMatchHighLow =
1182+ MinimumMatchHighLow { lowFreq :: MinimumMatch
1183+ , highFreq :: MinimumMatch } deriving (Eq, Show)
1184+
1185+data Filter = AndFilter [Filter] Cache
1186+ | OrFilter [Filter] Cache
1187+ | NotFilter Filter Cache
1188+ | IdentityFilter
1189+ | BoolFilter BoolMatch
1190+ | ExistsFilter FieldName -- always cached
1191+ | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1192+ | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1193+ | GeoDistanceRangeFilter GeoPoint DistanceRange
1194+ | GeoPolygonFilter FieldName [LatLon]
1195+ | IdsFilter MappingName [DocId]
1196+ | LimitFilter Int
1197+ | MissingFilter FieldName Existence NullValue
1198+ | PrefixFilter FieldName PrefixValue Cache
1199+ | QueryFilter Query Cache
1200+ | RangeFilter FieldName RangeValue RangeExecution Cache
1201+ | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1202+ | TermFilter Term Cache
1203+ deriving (Eq, Show)
1204+
1205+data ZeroTermsQuery = ZeroTermsNone
1206+ | ZeroTermsAll deriving (Eq, Show)
1207+
1208+data RangeExecution = RangeExecutionIndex
1209+ | RangeExecutionFielddata deriving (Eq, Show)
1210+
1211+newtype Regexp = Regexp Text deriving (Eq, Show, FromJSON)
1212+
1213+data RegexpFlags = AllRegexpFlags
1214+ | NoRegexpFlags
1215+ | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show)
1216+
1217+data RegexpFlag = AnyString
1218+ | Automaton
1219+ | Complement
1220+ | Empty
1221+ | Intersection
1222+ | Interval deriving (Eq, Show)
1223+
1224+newtype LessThan = LessThan Double deriving (Eq, Show)
1225+newtype LessThanEq = LessThanEq Double deriving (Eq, Show)
1226+newtype GreaterThan = GreaterThan Double deriving (Eq, Show)
1227+newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show)
1228+
1229+newtype LessThanD = LessThanD UTCTime deriving (Eq, Show)
1230+newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show)
1231+newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show)
1232+newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show)
1233+
1234+data RangeValue = RangeDateLte LessThanEqD
1235+ | RangeDateLt LessThanD
1236+ | RangeDateGte GreaterThanEqD
1237+ | RangeDateGt GreaterThanD
1238+ | RangeDateGtLt GreaterThanD LessThanD
1239+ | RangeDateGteLte GreaterThanEqD LessThanEqD
1240+ | RangeDateGteLt GreaterThanEqD LessThanD
1241+ | RangeDateGtLte GreaterThanD LessThanEqD
1242+ | RangeDoubleLte LessThanEq
1243+ | RangeDoubleLt LessThan
1244+ | RangeDoubleGte GreaterThanEq
1245+ | RangeDoubleGt GreaterThan
1246+ | RangeDoubleGtLt GreaterThan LessThan
1247+ | RangeDoubleGteLte GreaterThanEq LessThanEq
1248+ | RangeDoubleGteLt GreaterThanEq LessThan
1249+ | RangeDoubleGtLte GreaterThan LessThanEq
1250+ deriving (Eq, Show)
1251+
1252+rangeValueToPair :: RangeValue -> [Pair]
1253+rangeValueToPair rv = case rv of
1254+ RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1255+ RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1256+ RangeDateLt (LessThanD t) -> ["lt" .= t]
1257+ RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1258+ RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1259+ RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1260+ RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1261+ RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1262+ RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1263+ RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1264+ RangeDoubleLt (LessThan t) -> ["lt" .= t]
1265+ RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1266+ RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1267+ RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1268+ RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1269+ RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1270+
1271+data Term = Term { termField :: Text
1272+ , termValue :: Text } deriving (Eq, Show)
1273+
1274+data BoolMatch = MustMatch Term Cache
1275+ | MustNotMatch Term Cache
1276+ | ShouldMatch [Term] Cache deriving (Eq, Show)
1277+
1278+-- "memory" or "indexed"
1279+data GeoFilterType = GeoFilterMemory
1280+ | GeoFilterIndexed deriving (Eq, Show)
1281+
1282+data LatLon = LatLon { lat :: Double
1283+ , lon :: Double } deriving (Eq, Show)
1284+
1285+data GeoBoundingBox =
1286+ GeoBoundingBox { topLeft :: LatLon
1287+ , bottomRight :: LatLon } deriving (Eq, Show)
1288+
1289+data GeoBoundingBoxConstraint =
1290+ GeoBoundingBoxConstraint { geoBBField :: FieldName
1291+ , constraintBox :: GeoBoundingBox
1292+ , bbConstraintcache :: Cache
1293+ , geoType :: GeoFilterType
1294+ } deriving (Eq, Show)
1295+
1296+data GeoPoint =
1297+ GeoPoint { geoField :: FieldName
1298+ , latLon :: LatLon} deriving (Eq, Show)
1299+
1300+data DistanceUnit = Miles
1301+ | Yards
1302+ | Feet
1303+ | Inches
1304+ | Kilometers
1305+ | Meters
1306+ | Centimeters
1307+ | Millimeters
1308+ | NauticalMiles deriving (Eq, Show)
1309+
1310+data DistanceType = Arc
1311+ | SloppyArc -- doesn't exist <1.0
1312+ | Plane deriving (Eq, Show)
1313+
1314+data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1315+ | NoOptimizeBbox deriving (Eq, Show)
1316+
1317+data Distance =
1318+ Distance { coefficient :: Double
1319+ , unit :: DistanceUnit } deriving (Eq, Show)
1320+
1321+data DistanceRange =
1322+ DistanceRange { distanceFrom :: Distance
1323+ , distanceTo :: Distance } deriving (Eq, Show)
1324+
1325+data SearchResult a =
1326+ SearchResult { took :: Int
1327+ , timedOut :: Bool
1328+ , shards :: ShardResult
1329+ , searchHits :: SearchHits a
1330+ , aggregations :: Maybe AggregationResults
1331+ , scrollId :: Maybe ScrollId } deriving (Eq, Show)
1332+
1333+type ScrollId = Text -- Fixme: Newtype
1334+
1335+type Score = Maybe Double
1336+
1337+data SearchHits a =
1338+ SearchHits { hitsTotal :: Int
1339+ , maxScore :: Score
1340+ , hits :: [Hit a] } deriving (Eq, Show)
1341+
1342+
1343+instance Monoid (SearchHits a) where
1344+ mempty = SearchHits 0 Nothing mempty
1345+ mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1346+ SearchHits (ta + tb) (max ma mb) (ha <> hb)
1347+
1348+
1349+data Hit a =
1350+ Hit { hitIndex :: IndexName
1351+ , hitType :: MappingName
1352+ , hitDocId :: DocId
1353+ , hitScore :: Score
1354+ , hitSource :: Maybe a
1355+ , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show)
1356+
1357+data ShardResult =
1358+ ShardResult { shardTotal :: Int
1359+ , shardsSuccessful :: Int
1360+ , shardsFailed :: Int } deriving (Eq, Show, Generic)
1361+
1362+type HitHighlight = M.Map Text [Text]
1363+
1364+showText :: Show a => a -> Text
1365+showText = T.pack . show
1366+
1367+type Aggregations = M.Map Text Aggregation
1368+
1369+emptyAggregations :: Aggregations
1370+emptyAggregations = M.empty
1371+
1372+mkAggregations :: Text -> Aggregation -> Aggregations
1373+mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1374+
1375+data TermOrder = TermOrder{ termSortField :: Text
1376+ , termSortOrder :: SortOrder } deriving (Eq, Show)
1377+
1378+data TermInclusion = TermInclusion Text
1379+ | TermPattern Text Text deriving (Eq, Show)
1380+
1381+data CollectionMode = BreadthFirst
1382+ | DepthFirst deriving (Eq, Show)
1383+
1384+data ExecutionHint = Ordinals
1385+ | GlobalOrdinals
1386+ | GlobalOrdinalsHash
1387+ | GlobalOrdinalsLowCardinality
1388+ | Map deriving (Eq, Show)
1389+
1390+data TimeInterval = Weeks
1391+ | Days
1392+ | Hours
1393+ | Minutes
1394+ | Seconds deriving (Eq)
1395+
1396+data Interval = Year
1397+ | Quarter
1398+ | Month
1399+ | Week
1400+ | Day
1401+ | Hour
1402+ | Minute
1403+ | Second
1404+ | FractionalInterval Float TimeInterval deriving (Eq, Show)
1405+
1406+data Aggregation = TermsAgg TermsAggregation
1407+ | DateHistogramAgg DateHistogramAggregation
1408+ | ValueCountAgg ValueCountAggregation
1409+ | FilterAgg FilterAggregation deriving (Eq, Show)
1410+
1411+
1412+data TermsAggregation = TermsAggregation { term :: Either Text Text
1413+ , termInclude :: Maybe TermInclusion
1414+ , termExclude :: Maybe TermInclusion
1415+ , termOrder :: Maybe TermOrder
1416+ , termMinDocCount :: Maybe Int
1417+ , termSize :: Maybe Int
1418+ , termShardSize :: Maybe Int
1419+ , termCollectMode :: Maybe CollectionMode
1420+ , termExecutionHint :: Maybe ExecutionHint
1421+ , termAggs :: Maybe Aggregations
1422+ } deriving (Eq, Show)
1423+
1424+data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1425+ , dateInterval :: Interval
1426+ , dateFormat :: Maybe Text
1427+ -- pre and post deprecated in 1.5
1428+ , datePreZone :: Maybe Text
1429+ , datePostZone :: Maybe Text
1430+ , datePreOffset :: Maybe Text
1431+ , datePostOffset :: Maybe Text
1432+ , dateAggs :: Maybe Aggregations
1433+ } deriving (Eq, Show)
1434+
1435+-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1436+data ValueCountAggregation = FieldValueCount FieldName
1437+ | ScriptValueCount Script deriving (Eq, Show)
1438+
1439+-- | 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.
1440+data FilterAggregation = FilterAggregation { faFilter :: Filter
1441+ , faAggs :: Maybe Aggregations} deriving (Eq, Show)
1442+
1443+mkTermsAggregation :: Text -> TermsAggregation
1444+mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1445+
1446+mkTermsScriptAggregation :: Text -> TermsAggregation
1447+mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1448+
1449+mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1450+mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1451+
1452+instance ToJSON Version where
1453+ toJSON Version {..} = object ["number" .= number
1454+ ,"build_hash" .= build_hash
1455+ ,"build_timestamp" .= build_timestamp
1456+ ,"build_snapshot" .= build_snapshot
1457+ ,"lucene_version" .= lucene_version]
1458+
1459+instance FromJSON Version where
1460+ parseJSON = withObject "Version" parse
1461+ where parse o = Version
1462+ <$> o .: "number"
1463+ <*> o .: "build_hash"
1464+ <*> o .: "build_timestamp"
1465+ <*> o .: "build_snapshot"
1466+ <*> o .: "lucene_version"
1467+
1468+instance ToJSON TermOrder where
1469+ toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1470+
1471+instance ToJSON TermInclusion where
1472+ toJSON (TermInclusion x) = toJSON x
1473+ toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1474+ "flags" .= flags]
1475+
1476+instance ToJSON CollectionMode where
1477+ toJSON BreadthFirst = "breadth_first"
1478+ toJSON DepthFirst = "depth_first"
1479+
1480+instance ToJSON ExecutionHint where
1481+ toJSON Ordinals = "ordinals"
1482+ toJSON GlobalOrdinals = "global_ordinals"
1483+ toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1484+ toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1485+ toJSON Map = "map"
1486+
1487+instance ToJSON Interval where
1488+ toJSON Year = "year"
1489+ toJSON Quarter = "quarter"
1490+ toJSON Month = "month"
1491+ toJSON Week = "week"
1492+ toJSON Day = "day"
1493+ toJSON Hour = "hour"
1494+ toJSON Minute = "minute"
1495+ toJSON Second = "second"
1496+ toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1497+
1498+instance Show TimeInterval where
1499+ show Weeks = "w"
1500+ show Days = "d"
1501+ show Hours = "h"
1502+ show Minutes = "m"
1503+ show Seconds = "s"
1504+
1505+instance ToJSON Aggregation where
1506+ toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1507+ omitNulls ["terms" .= omitNulls [ toJSON' term,
1508+ "include" .= include,
1509+ "exclude" .= exclude,
1510+ "order" .= order,
1511+ "min_doc_count" .= minDocCount,
1512+ "size" .= size,
1513+ "shard_size" .= shardSize,
1514+ "collect_mode" .= collectMode,
1515+ "execution_hint" .= executionHint
1516+ ],
1517+ "aggs" .= termAggs ]
1518+ where
1519+ toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1520+
1521+ toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1522+ omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1523+ "interval" .= interval,
1524+ "format" .= format,
1525+ "pre_zone" .= preZone,
1526+ "post_zone" .= postZone,
1527+ "pre_offset" .= preOffset,
1528+ "post_offset" .= postOffset
1529+ ],
1530+ "aggs" .= dateHistoAggs ]
1531+ toJSON (ValueCountAgg a) = object ["value_count" .= v]
1532+ where v = case a of
1533+ (FieldValueCount (FieldName n)) -> object ["field" .= n]
1534+ (ScriptValueCount (Script s)) -> object ["script" .= s]
1535+ toJSON (FilterAgg (FilterAggregation filt ags)) =
1536+ omitNulls [ "filter" .= filt
1537+ , "aggs" .= ags]
1538+
1539+type AggregationResults = M.Map Text Value
1540+
1541+class BucketAggregation a where
1542+ key :: a -> Text
1543+ docCount :: a -> Int
1544+ aggs :: a -> Maybe AggregationResults
1545+
1546+
1547+data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1548+
1549+data TermsResult = TermsResult { termKey :: Text
1550+ , termsDocCount :: Int
1551+ , termsAggs :: Maybe AggregationResults } deriving (Show)
1552+
1553+data DateHistogramResult = DateHistogramResult { dateKey :: Int
1554+ , dateKeyStr :: Maybe Text
1555+ , dateDocCount :: Int
1556+ , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1557+
1558+toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1559+toTerms t a = M.lookup t a >>= deserialize
1560+ where deserialize = parseMaybe parseJSON
1561+
1562+toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1563+toDateHistogram t a = M.lookup t a >>= deserialize
1564+ where deserialize = parseMaybe parseJSON
1565+
1566+instance BucketAggregation TermsResult where
1567+ key = termKey
1568+ docCount = termsDocCount
1569+ aggs = termsAggs
1570+
1571+instance BucketAggregation DateHistogramResult where
1572+ key = showText . dateKey
1573+ docCount = dateDocCount
1574+ aggs = dateHistogramAggs
1575+
1576+instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1577+ parseJSON (Object v) = Bucket <$>
1578+ v .: "buckets"
1579+ parseJSON _ = mempty
1580+
1581+instance FromJSON TermsResult where
1582+ parseJSON (Object v) = TermsResult <$>
1583+ v .: "key" <*>
1584+ v .: "doc_count" <*>
1585+ v .:? "aggregations"
1586+ parseJSON _ = mempty
1587+
1588+instance FromJSON DateHistogramResult where
1589+ parseJSON (Object v) = DateHistogramResult <$>
1590+ v .: "key" <*>
1591+ v .:? "key_as_string" <*>
1592+ v .: "doc_count" <*>
1593+ v .:? "aggregations"
1594+ parseJSON _ = mempty
1595+
1596+instance Monoid Filter where
1597+ mempty = IdentityFilter
1598+ mappend a b = AndFilter [a, b] defaultCache
1599+
1600+instance Seminearring Filter where
1601+ a <||> b = OrFilter [a, b] defaultCache
1602+
1603+instance ToJSON Filter where
1604+ toJSON (AndFilter filters cache) =
1605+ object ["and" .=
1606+ object [ "filters" .= fmap toJSON filters
1607+ , "_cache" .= cache]]
1608+
1609+ toJSON (OrFilter filters cache) =
1610+ object ["or" .=
1611+ object [ "filters" .= fmap toJSON filters
1612+ , "_cache" .= cache]]
1613+
1614+ toJSON (NotFilter notFilter cache) =
1615+ object ["not" .=
1616+ object ["filter" .= notFilter
1617+ , "_cache" .= cache]]
1618+
1619+ toJSON (IdentityFilter) =
1620+ object ["match_all" .= object []]
1621+
1622+ toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1623+ object ["term" .= object base]
1624+ where base = [termFilterField .= termFilterValue,
1625+ "_cache" .= cache]
1626+
1627+ toJSON (ExistsFilter (FieldName fieldName)) =
1628+ object ["exists" .= object
1629+ ["field" .= fieldName]]
1630+
1631+ toJSON (BoolFilter boolMatch) =
1632+ object ["bool" .= boolMatch]
1633+
1634+ toJSON (GeoBoundingBoxFilter bbConstraint) =
1635+ object ["geo_bounding_box" .= bbConstraint]
1636+
1637+ toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1638+ distance distanceType optimizeBbox cache) =
1639+ object ["geo_distance" .=
1640+ object ["distance" .= distance
1641+ , "distance_type" .= distanceType
1642+ , "optimize_bbox" .= optimizeBbox
1643+ , distanceGeoField .= geoDistLatLon
1644+ , "_cache" .= cache]]
1645+
1646+ toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1647+ (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1648+ object ["geo_distance_range" .=
1649+ object ["from" .= geoDistRangeDistFrom
1650+ , "to" .= drDistanceTo
1651+ , gddrField .= drLatLon]]
1652+
1653+ toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1654+ object ["geo_polygon" .=
1655+ object [geoPolygonFilterField .=
1656+ object ["points" .= fmap toJSON latLons]]]
1657+
1658+ toJSON (IdsFilter (MappingName mappingName) values) =
1659+ object ["ids" .=
1660+ object ["type" .= mappingName
1661+ , "values" .= fmap unpackId values]]
1662+
1663+ toJSON (LimitFilter limit) =
1664+ object ["limit" .= object ["value" .= limit]]
1665+
1666+ toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1667+ object ["missing" .=
1668+ object ["field" .= fieldName
1669+ , "existence" .= existence
1670+ , "null_value" .= nullValue]]
1671+
1672+ toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1673+ object ["prefix" .=
1674+ object [fieldName .= fieldValue
1675+ , "_cache" .= cache]]
1676+
1677+ toJSON (QueryFilter query False) =
1678+ object ["query" .= toJSON query ]
1679+ toJSON (QueryFilter query True) =
1680+ object ["fquery" .=
1681+ object [ "query" .= toJSON query
1682+ , "_cache" .= True ]]
1683+
1684+ toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1685+ object ["range" .=
1686+ object [ fieldName .= object (rangeValueToPair rangeValue)
1687+ , "execution" .= rangeExecution
1688+ , "_cache" .= cache]]
1689+
1690+ toJSON (RegexpFilter (FieldName fieldName)
1691+ (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1692+ object ["regexp" .=
1693+ object [fieldName .=
1694+ object ["value" .= regexText
1695+ , "flags" .= flags]
1696+ , "_name" .= cacheName
1697+ , "_cache" .= cache
1698+ , "_cache_key" .= cacheKey]]
1699+
1700+instance FromJSON Filter where
1701+ parseJSON = withObject "Filter" parse
1702+ where parse o = andFilter `taggedWith` "and"
1703+ <|> orFilter `taggedWith` "or"
1704+ <|> notFilter `taggedWith` "not"
1705+ <|> identityFilter `taggedWith` "match_all"
1706+ <|> boolFilter `taggedWith` "bool"
1707+ <|> existsFilter `taggedWith` "exists"
1708+ <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
1709+ <|> geoDistanceFilter `taggedWith` "geo_distance"
1710+ <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
1711+ <|> geoPolygonFilter `taggedWith` "geo_polygon"
1712+ <|> idsFilter `taggedWith` "ids"
1713+ <|> limitFilter `taggedWith` "limit"
1714+ <|> missingFilter `taggedWith` "missing"
1715+ <|> prefixFilter `taggedWith` "prefix"
1716+ <|> queryFilter `taggedWith` "query"
1717+ <|> fqueryFilter `taggedWith` "fquery"
1718+ <|> rangeFilter `taggedWith` "range"
1719+ <|> regexpFilter `taggedWith` "regexp"
1720+ <|> termFilter `taggedWith` "term"
1721+ where taggedWith parser k = parser =<< o .: k
1722+ andFilter o = AndFilter <$> o .: "filters"
1723+ <*> o .:? "_cache" .!= defaultCache
1724+ orFilter o = OrFilter <$> o .: "filters"
1725+ <*> o .:? "_cache" .!= defaultCache
1726+ notFilter o = NotFilter <$> o .: "filter"
1727+ <*> o .: "_cache" .!= defaultCache
1728+ identityFilter :: Object -> Parser Filter
1729+ identityFilter m
1730+ | HM.null m = pure IdentityFilter
1731+ | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
1732+ boolFilter = pure . BoolFilter
1733+ existsFilter o = ExistsFilter <$> o .: "field"
1734+ geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1735+ geoDistanceFilter o = do
1736+ case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
1737+ [(fn, v)] -> do
1738+ gp <- GeoPoint (FieldName fn) <$> parseJSON v
1739+ GeoDistanceFilter gp <$> o .: "distance"
1740+ <*> o .: "distance_type"
1741+ <*> o .: "optimize_bbox"
1742+ <*> o .:? "_cache" .!= defaultCache
1743+ _ -> fail "Could not find GeoDistanceFilter field name"
1744+ geoDistanceRangeFilter o = flip fieldTagged o $ \fn o' -> do
1745+ gp <- GeoPoint fn <$> parseJSON (Object o')
1746+ rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1747+ return (GeoDistanceRangeFilter gp rng)
1748+ geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
1749+ idsFilter o = IdsFilter <$> o .: "type"
1750+ <*> o .: "values"
1751+ limitFilter o = LimitFilter <$> o .: "value"
1752+ missingFilter o = MissingFilter <$> o .: "field"
1753+ <*> o .: "existence"
1754+ <*> o .: "null_value"
1755+ prefixFilter o = case HM.toList (HM.delete "_cache" o) of
1756+ [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
1757+ _ -> fail "Could not parse PrefixFilter"
1758+
1759+ queryFilter q = pure (QueryFilter q False)
1760+ fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
1761+ rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
1762+ [(fn, v)] -> RangeFilter (FieldName fn)
1763+ <$> parseJSON v
1764+ <*> o .: "execution"
1765+ <*> o .:? "_cache" .!= defaultCache
1766+ _ -> fail "Could not find field name for RangeFilter"
1767+ regexpFilter = fieldTagged $ \fn o -> RegexpFilter fn <$> o .: "value"
1768+ <*> o .: "flags"
1769+ <*> o .: "_name"
1770+ <*> o .:? "_cache" .!= defaultCache
1771+ <*> o .: "_cache_key"
1772+ termFilter o = case HM.toList (HM.delete "_cache" o) of
1773+ [(termField, String termVal)] -> TermFilter (Term termField termVal)
1774+ <$> o .:? "_cache" .!= defaultCache
1775+ _ -> fail "Could not find term field for TermFilter"
1776+
1777+fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
1778+fieldTagged f o = case HM.toList o of
1779+ [(k, Object o')] -> f (FieldName k) o'
1780+ _ -> fail "Expected object with 1 field-named key"
1781+
1782+instance ToJSON GeoPoint where
1783+ toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
1784+ object [ geoPointField .= geoPointLatLon ]
1785+
1786+
1787+instance ToJSON Query where
1788+ toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
1789+ object [ "term" .=
1790+ object [termQueryField .= object merged]]
1791+ where
1792+ base = [ "value" .= termQueryValue ]
1793+ boosted = maybe [] (return . ("boost" .=)) boost
1794+ merged = mappend base boosted
1795+
1796+ toJSON (TermsQuery terms) =
1797+ object [ "terms" .= object conjoined ]
1798+ where conjoined = [ getTermsField terms .=
1799+ fmap (toJSON . getTermValue) (toList terms)]
1800+ getTermsField ((Term f _ ) :| _) = f
1801+ getTermValue (Term _ v) = v
1802+ toJSON (IdsQuery idsQueryMappingName docIds) =
1803+ object [ "ids" .= object conjoined ]
1804+ where conjoined = [ "type" .= idsQueryMappingName
1805+ , "values" .= fmap toJSON docIds ]
1806+
1807+ toJSON (QueryQueryStringQuery qQueryStringQuery) =
1808+ object [ "query_string" .= qQueryStringQuery ]
1809+
1810+ toJSON (QueryMatchQuery matchQuery) =
1811+ object [ "match" .= matchQuery ]
1812+
1813+ toJSON (QueryMultiMatchQuery multiMatchQuery) =
1814+ toJSON multiMatchQuery
1815+
1816+ toJSON (QueryBoolQuery boolQuery) =
1817+ object [ "bool" .= boolQuery ]
1818+
1819+ toJSON (QueryBoostingQuery boostingQuery) =
1820+ object [ "boosting" .= boostingQuery ]
1821+
1822+ toJSON (QueryCommonTermsQuery commonTermsQuery) =
1823+ object [ "common" .= commonTermsQuery ]
1824+
1825+ toJSON (ConstantScoreFilter csFilter boost) =
1826+ object [ "constant_score" .= csFilter
1827+ , "boost" .= boost]
1828+
1829+ toJSON (ConstantScoreQuery query boost) =
1830+ object [ "constant_score" .= query
1831+ , "boost" .= boost]
1832+
1833+ toJSON (QueryDisMaxQuery disMaxQuery) =
1834+ object [ "dis_max" .= disMaxQuery ]
1835+
1836+ toJSON (QueryFilteredQuery qFilteredQuery) =
1837+ object [ "filtered" .= qFilteredQuery ]
1838+
1839+ toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
1840+ object [ "fuzzy_like_this" .= fuzzyQuery ]
1841+
1842+ toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
1843+ object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
1844+
1845+ toJSON (QueryFuzzyQuery fuzzyQuery) =
1846+ object [ "fuzzy" .= fuzzyQuery ]
1847+
1848+ toJSON (QueryHasChildQuery childQuery) =
1849+ object [ "has_child" .= childQuery ]
1850+
1851+ toJSON (QueryHasParentQuery parentQuery) =
1852+ object [ "has_parent" .= parentQuery ]
1853+
1854+ toJSON (QueryIndicesQuery qIndicesQuery) =
1855+ object [ "indices" .= qIndicesQuery ]
1856+
1857+ toJSON (MatchAllQuery boost) =
1858+ object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
1859+
1860+ toJSON (QueryMoreLikeThisQuery query) =
1861+ object [ "more_like_this" .= query ]
1862+
1863+ toJSON (QueryMoreLikeThisFieldQuery query) =
1864+ object [ "more_like_this_field" .= query ]
1865+
1866+ toJSON (QueryNestedQuery query) =
1867+ object [ "nested" .= query ]
1868+
1869+ toJSON (QueryPrefixQuery query) =
1870+ object [ "prefix" .= query ]
1871+
1872+ toJSON (QueryRangeQuery query) =
1873+ object [ "range" .= query ]
1874+
1875+ toJSON (QueryRegexpQuery query) =
1876+ object [ "regexp" .= query ]
1877+
1878+ toJSON (QuerySimpleQueryStringQuery query) =
1879+ object [ "simple_query_string" .= query ]
1880+
1881+instance FromJSON Query where
1882+ parseJSON v = withObject "Query" parse v
1883+ where parse o = termQuery `taggedWith` "term"
1884+ <|> termsQuery `taggedWith` "terms"
1885+ <|> idsQuery `taggedWith` "ids"
1886+ <|> queryQueryStringQuery `taggedWith` "query_string"
1887+ <|> queryMatchQuery `taggedWith` "match"
1888+ <|> queryMultiMatchQuery --TODO: is this a precedence issue?
1889+ <|> queryBoolQuery `taggedWith` "bool"
1890+ <|> queryBoostingQuery `taggedWith` "boosting"
1891+ <|> queryCommonTermsQuery `taggedWith` "common"
1892+ <|> constantScoreFilter o
1893+ <|> constantScoreQuery o
1894+ <|> queryDisMaxQuery `taggedWith` "dis_max"
1895+ <|> queryFilteredQuery `taggedWith` "filtered"
1896+ <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
1897+ <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
1898+ <|> queryFuzzyQuery `taggedWith` "fuzzy"
1899+ <|> queryHasChildQuery `taggedWith` "has_child"
1900+ <|> queryHasParentQuery `taggedWith` "has_parent"
1901+ <|> queryIndicesQuery `taggedWith` "indices"
1902+ <|> matchAllQuery `taggedWith` "match_all"
1903+ <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
1904+ <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
1905+ <|> queryNestedQuery `taggedWith` "nested"
1906+ <|> queryPrefixQuery `taggedWith` "prefix"
1907+ <|> queryRangeQuery `taggedWith` "range"
1908+ <|> queryRegexpQuery `taggedWith` "regexp"
1909+ <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
1910+ where taggedWith parser k = parser =<< o .: k
1911+ termQuery = fieldTagged $ \(FieldName fn) o ->
1912+ TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
1913+ termsQuery o = case HM.toList o of
1914+ [(fn, vs)] -> do vals <- parseJSON vs
1915+ case vals of
1916+ x:xs -> return (TermsQuery (Term fn <$> x :| xs))
1917+ _ -> fail "Expected non empty list of values"
1918+ _ -> fail "Expected object with 1 field-named key"
1919+ idsQuery o = IdsQuery <$> o .: "type"
1920+ <*> o .: "values"
1921+ queryQueryStringQuery = pure . QueryQueryStringQuery
1922+ queryMatchQuery = pure . QueryMatchQuery
1923+ queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
1924+ queryBoolQuery = pure . QueryBoolQuery
1925+ queryBoostingQuery = pure . QueryBoostingQuery
1926+ queryCommonTermsQuery = pure . QueryCommonTermsQuery
1927+ constantScoreFilter o = ConstantScoreFilter <$> o .: "constant_score"
1928+ <*> o .: "boost"
1929+ constantScoreQuery o = ConstantScoreQuery <$> o .: "constant_score"
1930+ <*> o .: "boost"
1931+ queryDisMaxQuery = pure . QueryDisMaxQuery
1932+ queryFilteredQuery = pure . QueryFilteredQuery
1933+ queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
1934+ queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
1935+ queryFuzzyQuery = pure . QueryFuzzyQuery
1936+ queryHasChildQuery = pure . QueryHasChildQuery
1937+ queryHasParentQuery = pure . QueryHasParentQuery
1938+ queryIndicesQuery = pure . QueryIndicesQuery
1939+ matchAllQuery o = MatchAllQuery <$> o .:? "boost"
1940+ queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
1941+ queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
1942+ queryNestedQuery = pure . QueryNestedQuery
1943+ queryPrefixQuery = pure . QueryPrefixQuery
1944+ queryRangeQuery = pure . QueryRangeQuery
1945+ queryRegexpQuery = pure . QueryRegexpQuery
1946+ querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
1947+
1948+
1949+omitNulls :: [(Text, Value)] -> Value
1950+omitNulls = object . filter notNull where
1951+ notNull (_, Null) = False
1952+ notNull (_, Array a) = (not . V.null) a
1953+ notNull _ = True
1954+
1955+
1956+instance ToJSON SimpleQueryStringQuery where
1957+ toJSON SimpleQueryStringQuery {..} =
1958+ omitNulls (base ++ maybeAdd)
1959+ where base = [ "query" .= simpleQueryStringQuery ]
1960+ maybeAdd = [ "fields" .= simpleQueryStringField
1961+ , "default_operator" .= simpleQueryStringOperator
1962+ , "analyzer" .= simpleQueryStringAnalyzer
1963+ , "flags" .= simpleQueryStringFlags
1964+ , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
1965+ , "locale" .= simpleQueryStringLocale ]
1966+
1967+instance FromJSON SimpleQueryStringQuery where
1968+ parseJSON = withObject "SimpleQueryStringQuery" parse
1969+ where parse o = SimpleQueryStringQuery <$> o .: "query"
1970+ <*> o .:? "fields"
1971+ <*> o .:? "default_operator"
1972+ <*> o .:? "analyzer"
1973+ <*> o .:? "flags"
1974+ <*> o .:? "lowercase_expanded_terms"
1975+ <*> o .:? "locale"
1976+
1977+instance ToJSON FieldOrFields where
1978+ toJSON (FofField fieldName) =
1979+ toJSON fieldName
1980+ toJSON (FofFields fieldNames) =
1981+ toJSON fieldNames
1982+
1983+instance FromJSON FieldOrFields where
1984+ parseJSON v = FofField <$> parseJSON v
1985+ <|> FofFields <$> parseJSON v
1986+
1987+instance ToJSON SimpleQueryFlag where
1988+ toJSON SimpleQueryAll = "ALL"
1989+ toJSON SimpleQueryNone = "NONE"
1990+ toJSON SimpleQueryAnd = "AND"
1991+ toJSON SimpleQueryOr = "OR"
1992+ toJSON SimpleQueryPrefix = "PREFIX"
1993+ toJSON SimpleQueryPhrase = "PHRASE"
1994+ toJSON SimpleQueryPrecedence = "PRECEDENCE"
1995+ toJSON SimpleQueryEscape = "ESCAPE"
1996+ toJSON SimpleQueryWhitespace = "WHITESPACE"
1997+ toJSON SimpleQueryFuzzy = "FUZZY"
1998+ toJSON SimpleQueryNear = "NEAR"
1999+ toJSON SimpleQuerySlop = "SLOP"
2000+
2001+instance FromJSON SimpleQueryFlag where
2002+ parseJSON = withText "SimpleQueryFlag" parse
2003+ where parse "ALL" = pure SimpleQueryAll
2004+ parse "NONE" = pure SimpleQueryNone
2005+ parse "AND" = pure SimpleQueryAnd
2006+ parse "OR" = pure SimpleQueryOr
2007+ parse "PREFIX" = pure SimpleQueryPrefix
2008+ parse "PHRASE" = pure SimpleQueryPhrase
2009+ parse "PRECEDENCE" = pure SimpleQueryPrecedence
2010+ parse "ESCAPE" = pure SimpleQueryEscape
2011+ parse "WHITESPACE" = pure SimpleQueryWhitespace
2012+ parse "FUZZY" = pure SimpleQueryFuzzy
2013+ parse "NEAR" = pure SimpleQueryNear
2014+ parse "SLOP" = pure SimpleQuerySlop
2015+ parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2016+
2017+instance ToJSON RegexpQuery where
2018+ toJSON (RegexpQuery (FieldName rqQueryField)
2019+ (Regexp regexpQueryQuery) rqQueryFlags
2020+ rqQueryBoost) =
2021+ object [ rqQueryField .= omitNulls base ]
2022+ where base = [ "value" .= regexpQueryQuery
2023+ , "flags" .= rqQueryFlags
2024+ , "boost" .= rqQueryBoost ]
2025+
2026+instance FromJSON RegexpQuery where
2027+ parseJSON = withObject "RegexpQuery" parse
2028+ where parse = fieldTagged $ \fn o ->
2029+ RegexpQuery fn
2030+ <$> o .: "value"
2031+ <*> o .: "flags"
2032+ <*> o .:? "boost"
2033+
2034+instance ToJSON QueryStringQuery where
2035+ toJSON (QueryStringQuery qsQueryString
2036+ qsDefaultField qsOperator
2037+ qsAnalyzer qsAllowWildcard
2038+ qsLowercaseExpanded qsEnablePositionIncrements
2039+ qsFuzzyMaxExpansions qsFuzziness
2040+ qsFuzzyPrefixLength qsPhraseSlop
2041+ qsBoost qsAnalyzeWildcard
2042+ qsGeneratePhraseQueries qsMinimumShouldMatch
2043+ qsLenient qsLocale) =
2044+ omitNulls base
2045+ where
2046+ base = [ "query" .= qsQueryString
2047+ , "default_field" .= qsDefaultField
2048+ , "default_operator" .= qsOperator
2049+ , "analyzer" .= qsAnalyzer
2050+ , "allow_leading_wildcard" .= qsAllowWildcard
2051+ , "lowercase_expanded_terms" .= qsLowercaseExpanded
2052+ , "enable_position_increments" .= qsEnablePositionIncrements
2053+ , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2054+ , "fuzziness" .= qsFuzziness
2055+ , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2056+ , "phrase_slop" .= qsPhraseSlop
2057+ , "boost" .= qsBoost
2058+ , "analyze_wildcard" .= qsAnalyzeWildcard
2059+ , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2060+ , "minimum_should_match" .= qsMinimumShouldMatch
2061+ , "lenient" .= qsLenient
2062+ , "locale" .= qsLocale ]
2063+
2064+instance FromJSON QueryStringQuery where
2065+ parseJSON = withObject "QueryStringQuery" parse
2066+ where parse o = QueryStringQuery
2067+ <$> o .: "query"
2068+ <*> o .:? "default_field"
2069+ <*> o .:? "default_operator"
2070+ <*> o .:? "analyzer"
2071+ <*> o .:? "allow_leading_wildcard"
2072+ <*> o .:? "lowercase_expanded_terms"
2073+ <*> o .:? "enable_position_increments"
2074+ <*> o .:? "fuzzy_max_expansions"
2075+ <*> o .:? "fuzziness"
2076+ <*> o .:? "fuzzy_prefix_length"
2077+ <*> o .:? "phrase_slop"
2078+ <*> o .:? "boost"
2079+ <*> o .:? "analyze_wildcard"
2080+ <*> o .:? "auto_generate_phrase_queries"
2081+ <*> o .:? "minimum_should_match"
2082+ <*> o .:? "lenient"
2083+ <*> o .:? "locale"
2084+
2085+instance ToJSON RangeQuery where
2086+ toJSON (RangeQuery (FieldName fieldName) range boost) =
2087+ object [ fieldName .= object conjoined ]
2088+ where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2089+
2090+instance FromJSON RangeQuery where
2091+ parseJSON = withObject "RangeQuery" parse
2092+ where parse = fieldTagged $ \fn o ->
2093+ RangeQuery fn
2094+ <$> parseJSON (Object o)
2095+ <*> o .: "boost"
2096+
2097+instance FromJSON RangeValue where
2098+ parseJSON = withObject "RangeValue" parse
2099+ where parse o = parseDate o
2100+ <|> parseDouble o
2101+ parseDate o = do lt <- o .:? "lt"
2102+ lte <- o .:? "lte"
2103+ gt <- o .:? "gt"
2104+ gte <- o .:? "gte"
2105+ case (lt, lte, gt, gte) of
2106+ (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD a) (LessThanD b))
2107+ (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD a) (LessThanD b))
2108+ (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD a) (LessThanEqD b))
2109+ (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD a) (LessThanEqD b))
2110+ (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2111+ (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2112+ (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2113+ (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2114+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2115+ parseDouble o = do lt <- o .:? "lt"
2116+ lte <- o .:? "lte"
2117+ gt <- o .:? "gt"
2118+ gte <- o .:? "gte"
2119+ case (lt, lte, gt, gte) of
2120+ (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan a) (LessThan b))
2121+ (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq a) (LessThan b))
2122+ (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan a) (LessThanEq b))
2123+ (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq a) (LessThanEq b))
2124+ (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2125+ (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2126+ (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2127+ (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2128+ (Nothing, Nothing, Nothing, Nothing) -> mzero
2129+
2130+instance ToJSON PrefixQuery where
2131+ toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2132+ object [ fieldName .= omitNulls base ]
2133+ where base = [ "value" .= queryValue
2134+ , "boost" .= boost ]
2135+
2136+instance FromJSON PrefixQuery where
2137+ parseJSON = withObject "PrefixQuery" parse
2138+ where parse = fieldTagged $ \fn o ->
2139+ PrefixQuery fn
2140+ <$> o .: "value"
2141+ <*> o .:? "boost"
2142+
2143+instance ToJSON NestedQuery where
2144+ toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2145+ object [ "path" .= nqPath
2146+ , "score_mode" .= nqScoreType
2147+ , "query" .= nqQuery ]
2148+
2149+instance FromJSON NestedQuery where
2150+ parseJSON = withObject "NestedQuery" parse
2151+ where parse o = NestedQuery
2152+ <$> o .: "path"
2153+ <*> o .: "score_mode"
2154+ <*> o .: "query"
2155+
2156+instance ToJSON MoreLikeThisFieldQuery where
2157+ toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2158+ percent mtf mqt stopwords mindf maxdf
2159+ minwl maxwl boostTerms boost analyzer) =
2160+ object [ fieldName .= omitNulls base ]
2161+ where base = [ "like_text" .= text
2162+ , "percent_terms_to_match" .= percent
2163+ , "min_term_freq" .= mtf
2164+ , "max_query_terms" .= mqt
2165+ , "stop_words" .= stopwords
2166+ , "min_doc_freq" .= mindf
2167+ , "max_doc_freq" .= maxdf
2168+ , "min_word_length" .= minwl
2169+ , "max_word_length" .= maxwl
2170+ , "boost_terms" .= boostTerms
2171+ , "boost" .= boost
2172+ , "analyzer" .= analyzer ]
2173+
2174+instance FromJSON MoreLikeThisFieldQuery where
2175+ parseJSON = withObject "MoreLikeThisFieldQuery" parse
2176+ where parse = fieldTagged $ \fn o ->
2177+ MoreLikeThisFieldQuery
2178+ <$> o .: "like_text"
2179+ <*> pure fn
2180+ <*> o .:? "percent_terms_to_match"
2181+ <*> o .:? "min_term_freq"
2182+ <*> o .:? "max_query_terms"
2183+ <*> o .:? "stop_words"
2184+ <*> o .:? "min_doc_freq"
2185+ <*> o .:? "max_doc_freq"
2186+ <*> o .:? "min_word_length"
2187+ <*> o .:? "max_word_length"
2188+ <*> o .:? "boost_terms"
2189+ <*> o .:? "boost"
2190+ <*> o .:? "analyzer"
2191+
2192+instance ToJSON MoreLikeThisQuery where
2193+ toJSON (MoreLikeThisQuery text fields percent
2194+ mtf mqt stopwords mindf maxdf
2195+ minwl maxwl boostTerms boost analyzer) =
2196+ omitNulls base
2197+ where base = [ "like_text" .= text
2198+ , "fields" .= fields
2199+ , "percent_terms_to_match" .= percent
2200+ , "min_term_freq" .= mtf
2201+ , "max_query_terms" .= mqt
2202+ , "stop_words" .= stopwords
2203+ , "min_doc_freq" .= mindf
2204+ , "max_doc_freq" .= maxdf
2205+ , "min_word_length" .= minwl
2206+ , "max_word_length" .= maxwl
2207+ , "boost_terms" .= boostTerms
2208+ , "boost" .= boost
2209+ , "analyzer" .= analyzer ]
2210+
2211+instance FromJSON MoreLikeThisQuery where
2212+ parseJSON = withObject "MoreLikeThisQuery" parse
2213+ where parse o = MoreLikeThisQuery
2214+ <$> o .: "like_text"
2215+ <*> o .:? "fields"
2216+ <*> o .:? "percent_terms_to_match"
2217+ <*> o .:? "min_term_freq"
2218+ <*> o .:? "max_query_terms"
2219+ <*> o .:? "stop_words"
2220+ <*> o .:? "min_doc_freq"
2221+ <*> o .:? "max_doc_freq"
2222+ <*> o .:? "min_word_length"
2223+ <*> o .:? "max_word_length"
2224+ <*> o .:? "boost_terms"
2225+ <*> o .:? "boost"
2226+ <*> o .:? "analyzer"
2227+
2228+instance ToJSON IndicesQuery where
2229+ toJSON (IndicesQuery indices query noMatch) =
2230+ omitNulls [ "indices" .= indices
2231+ , "no_match_query" .= noMatch
2232+ , "query" .= query ]
2233+
2234+instance FromJSON IndicesQuery where
2235+ parseJSON = withObject "IndicesQuery" parse
2236+ where parse o = IndicesQuery
2237+ <$> o .: "indices"
2238+ <*> o .: "query"
2239+ <*> o .:? "no_match_query"
2240+
2241+instance ToJSON HasParentQuery where
2242+ toJSON (HasParentQuery queryType query scoreType) =
2243+ omitNulls [ "parent_type" .= queryType
2244+ , "score_type" .= scoreType
2245+ , "query" .= query ]
2246+
2247+instance FromJSON HasParentQuery where
2248+ parseJSON = withObject "HasParentQuery" parse
2249+ where parse o = HasParentQuery
2250+ <$> o .: "parent_type"
2251+ <*> o .: "query"
2252+ <*> o .:? "score_type"
2253+
2254+instance ToJSON HasChildQuery where
2255+ toJSON (HasChildQuery queryType query scoreType) =
2256+ omitNulls [ "query" .= query
2257+ , "score_type" .= scoreType
2258+ , "type" .= queryType ]
2259+
2260+instance FromJSON HasChildQuery where
2261+ parseJSON = withObject "HasChildQuery" parse
2262+ where parse o = HasChildQuery
2263+ <$> o .: "type"
2264+ <*> o .: "query"
2265+ <*> o .:? "score_type"
2266+
2267+instance ToJSON FuzzyQuery where
2268+ toJSON (FuzzyQuery (FieldName fieldName) queryText
2269+ prefixLength maxEx fuzziness boost) =
2270+ object [ fieldName .= omitNulls base ]
2271+ where base = [ "value" .= queryText
2272+ , "fuzziness" .= fuzziness
2273+ , "prefix_length" .= prefixLength
2274+ , "boost" .= boost
2275+ , "max_expansions" .= maxEx ]
2276+
2277+instance FromJSON FuzzyQuery where
2278+ parseJSON = withObject "FuzzyQuery" parse
2279+ where parse = fieldTagged $ \fn o ->
2280+ FuzzyQuery fn
2281+ <$> o .: "value"
2282+ <*> o .: "prefix_length"
2283+ <*> o .: "max_expansions"
2284+ <*> o .: "fuzziness"
2285+ <*> o .:? "boost"
2286+
2287+instance ToJSON FuzzyLikeFieldQuery where
2288+ toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2289+ fieldText maxTerms ignoreFreq fuzziness prefixLength
2290+ boost analyzer) =
2291+ object [ fieldName .=
2292+ omitNulls [ "like_text" .= fieldText
2293+ , "max_query_terms" .= maxTerms
2294+ , "ignore_tf" .= ignoreFreq
2295+ , "fuzziness" .= fuzziness
2296+ , "prefix_length" .= prefixLength
2297+ , "analyzer" .= analyzer
2298+ , "boost" .= boost ]]
2299+
2300+instance FromJSON FuzzyLikeFieldQuery where
2301+ parseJSON = withObject "FuzzyLikeFieldQuery" parse
2302+ where parse = fieldTagged $ \fn o ->
2303+ FuzzyLikeFieldQuery fn
2304+ <$> o .: "like_text"
2305+ <*> o .: "max_query_terms"
2306+ <*> o .: "ignore_tf"
2307+ <*> o .: "fuzziness"
2308+ <*> o .: "prefix_length"
2309+ <*> o .: "boost"
2310+ <*> o .:? "analyzer"
2311+
2312+instance ToJSON FuzzyLikeThisQuery where
2313+ toJSON (FuzzyLikeThisQuery fields text maxTerms
2314+ ignoreFreq fuzziness prefixLength boost analyzer) =
2315+ omitNulls base
2316+ where base = [ "fields" .= fields
2317+ , "like_text" .= text
2318+ , "max_query_terms" .= maxTerms
2319+ , "ignore_tf" .= ignoreFreq
2320+ , "fuzziness" .= fuzziness
2321+ , "prefix_length" .= prefixLength
2322+ , "analyzer" .= analyzer
2323+ , "boost" .= boost ]
2324+
2325+instance FromJSON FuzzyLikeThisQuery where
2326+ parseJSON = withObject "FuzzyLikeThisQuery" parse
2327+ where parse o = FuzzyLikeThisQuery
2328+ <$> o .:? "fields" .!= []
2329+ <*> o .: "like_text"
2330+ <*> o .: "max_query_terms"
2331+ <*> o .: "ignore_tf"
2332+ <*> o .: "fuzziness"
2333+ <*> o .: "prefix_length"
2334+ <*> o .: "boost"
2335+ <*> o .:? "analyzer"
2336+
2337+instance ToJSON FilteredQuery where
2338+ toJSON (FilteredQuery query fFilter) =
2339+ object [ "query" .= query
2340+ , "filter" .= fFilter ]
2341+
2342+instance FromJSON FilteredQuery where
2343+ parseJSON = withObject "FilteredQuery" parse
2344+ where parse o = FilteredQuery
2345+ <$> o .: "query"
2346+ <*> o .: "filter"
2347+
2348+instance ToJSON DisMaxQuery where
2349+ toJSON (DisMaxQuery queries tiebreaker boost) =
2350+ omitNulls base
2351+ where base = [ "queries" .= queries
2352+ , "boost" .= boost
2353+ , "tie_breaker" .= tiebreaker ]
2354+
2355+instance FromJSON DisMaxQuery where
2356+ parseJSON = withObject "DisMaxQuery" parse
2357+ where parse o = DisMaxQuery
2358+ <$> o .:? "queries" .!= []
2359+ <*> o .: "tie_breaker"
2360+ <*> o .:? "boost"
2361+
2362+instance ToJSON CommonTermsQuery where
2363+ toJSON (CommonTermsQuery (FieldName fieldName)
2364+ (QueryString query) cf lfo hfo msm
2365+ boost analyzer disableCoord) =
2366+ object [fieldName .= omitNulls base ]
2367+ where base = [ "query" .= query
2368+ , "cutoff_frequency" .= cf
2369+ , "low_freq_operator" .= lfo
2370+ , "minimum_should_match" .= msm
2371+ , "boost" .= boost
2372+ , "analyzer" .= analyzer
2373+ , "disable_coord" .= disableCoord
2374+ , "high_freq_operator" .= hfo ]
2375+
2376+instance FromJSON CommonTermsQuery where
2377+ parseJSON = withObject "CommonTermsQuery" parse
2378+ where parse = fieldTagged $ \fn o ->
2379+ CommonTermsQuery fn
2380+ <$> o .: "query"
2381+ <*> o .: "cutoff_frequency"
2382+ <*> o .: "low_freq_operator"
2383+ <*> o .: "high_freq_operator"
2384+ <*> o .:? "minimum_should_match"
2385+ <*> o .:? "boost"
2386+ <*> o .:? "analyzer"
2387+ <*> o .:? "disable_coord"
2388+
2389+instance ToJSON CommonMinimumMatch where
2390+ toJSON (CommonMinimumMatch mm) = toJSON mm
2391+ toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2392+ object [ "low_freq" .= lowF
2393+ , "high_freq" .= highF ]
2394+
2395+instance FromJSON CommonMinimumMatch where
2396+ parseJSON v = parseMinimum v
2397+ <|> parseMinimumHighLow v
2398+ where parseMinimum = fmap CommonMinimumMatch . parseJSON
2399+ parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2400+ MinimumMatchHighLow
2401+ <$> o .: "low_freq"
2402+ <*> o .: "high_freq")
2403+
2404+
2405+instance ToJSON BoostingQuery where
2406+ toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2407+ object [ "positive" .= bqPositiveQuery
2408+ , "negative" .= bqNegativeQuery
2409+ , "negative_boost" .= bqNegativeBoost ]
2410+
2411+instance FromJSON BoostingQuery where
2412+ parseJSON = withObject "BoostingQuery" parse
2413+ where parse o = BoostingQuery
2414+ <$> o .: "positive"
2415+ <*> o .: "negative"
2416+ <*> o .: "negative_boost"
2417+
2418+instance ToJSON BoolQuery where
2419+ toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2420+ omitNulls base
2421+ where base = [ "must" .= mustM
2422+ , "must_not" .= notM
2423+ , "should" .= shouldM
2424+ , "minimum_should_match" .= bqMin
2425+ , "boost" .= boost
2426+ , "disable_coord" .= disableCoord ]
2427+
2428+instance FromJSON BoolQuery where
2429+ parseJSON = withObject "BoolQuery" parse
2430+ where parse o = BoolQuery
2431+ <$> o .:? "must" .!= []
2432+ <*> o .:? "must_not" .!= []
2433+ <*> o .:? "should" .!= []
2434+ <*> o .:? "minimum_should_match"
2435+ <*> o .:? "boost"
2436+ <*> o .:? "disable_coord"
2437+
2438+instance ToJSON MatchQuery where
2439+ toJSON (MatchQuery (FieldName fieldName)
2440+ (QueryString mqQueryString) booleanOperator
2441+ zeroTermsQuery cutoffFrequency matchQueryType
2442+ analyzer maxExpansions lenient boost) =
2443+ object [ fieldName .= omitNulls base ]
2444+ where base = [ "query" .= mqQueryString
2445+ , "operator" .= booleanOperator
2446+ , "zero_terms_query" .= zeroTermsQuery
2447+ , "cutoff_frequency" .= cutoffFrequency
2448+ , "type" .= matchQueryType
2449+ , "analyzer" .= analyzer
2450+ , "max_expansions" .= maxExpansions
2451+ , "lenient" .= lenient
2452+ , "boost" .= boost ]
2453+
2454+instance FromJSON MatchQuery where
2455+ parseJSON = withObject "MatchQuery" parse
2456+ where parse = fieldTagged $ \fn o ->
2457+ MatchQuery fn
2458+ <$> o .: "query"
2459+ <*> o .: "operator"
2460+ <*> o .: "zero_terms_query"
2461+ <*> o .:? "cutoff_frequency"
2462+ <*> o .:? "type"
2463+ <*> o .:? "analyzer"
2464+ <*> o .:? "max_expansions"
2465+ <*> o .:? "lenient"
2466+ <*> o .:? "boost"
2467+
2468+instance ToJSON MultiMatchQuery where
2469+ toJSON (MultiMatchQuery fields (QueryString query) boolOp
2470+ ztQ tb mmqt cf analyzer maxEx lenient) =
2471+ object ["multi_match" .= omitNulls base]
2472+ where base = [ "fields" .= fmap toJSON fields
2473+ , "query" .= query
2474+ , "operator" .= boolOp
2475+ , "zero_terms_query" .= ztQ
2476+ , "tiebreaker" .= tb
2477+ , "type" .= mmqt
2478+ , "cutoff_frequency" .= cf
2479+ , "analyzer" .= analyzer
2480+ , "max_expansions" .= maxEx
2481+ , "lenient" .= lenient ]
2482+
2483+instance FromJSON MultiMatchQuery where
2484+ parseJSON = withObject "MultiMatchQuery" parse
2485+ where parse raw = do o <- raw .: "multi_match"
2486+ MultiMatchQuery
2487+ <$> o .:? "fields" .!= []
2488+ <*> o .: "query"
2489+ <*> o .: "operator"
2490+ <*> o .: "zero_terms_query"
2491+ <*> o .:? "tiebreaker"
2492+ <*> o .:? "type"
2493+ <*> o .:? "cutoff_frequency"
2494+ <*> o .:? "analyzer"
2495+ <*> o .:? "max_expansions"
2496+ <*> o .:? "lenient"
2497+
2498+instance ToJSON MultiMatchQueryType where
2499+ toJSON MultiMatchBestFields = "best_fields"
2500+ toJSON MultiMatchMostFields = "most_fields"
2501+ toJSON MultiMatchCrossFields = "cross_fields"
2502+ toJSON MultiMatchPhrase = "phrase"
2503+ toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2504+
2505+instance FromJSON MultiMatchQueryType where
2506+ parseJSON = withText "MultiMatchPhrasePrefix" parse
2507+ where parse "best_fields" = pure MultiMatchBestFields
2508+ parse "most_fields" = pure MultiMatchMostFields
2509+ parse "cross_fields" = pure MultiMatchCrossFields
2510+ parse "phrase" = pure MultiMatchPhrase
2511+ parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2512+ parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2513+
2514+instance ToJSON BooleanOperator where
2515+ toJSON And = String "and"
2516+ toJSON Or = String "or"
2517+
2518+instance FromJSON BooleanOperator where
2519+ parseJSON = withText "BooleanOperator" parse
2520+ where parse "and" = pure And
2521+ parse "or" = pure Or
2522+ parse o = fail ("Unexpected BooleanOperator: " <> show o)
2523+
2524+instance ToJSON ZeroTermsQuery where
2525+ toJSON ZeroTermsNone = String "none"
2526+ toJSON ZeroTermsAll = String "all"
2527+
2528+instance FromJSON ZeroTermsQuery where
2529+ parseJSON = withText "ZeroTermsQuery" parse
2530+ where parse "none" = pure ZeroTermsNone
2531+ parse "all" = pure ZeroTermsAll
2532+ parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2533+
2534+instance ToJSON MatchQueryType where
2535+ toJSON MatchPhrase = "phrase"
2536+ toJSON MatchPhrasePrefix = "phrase_prefix"
2537+
2538+instance FromJSON MatchQueryType where
2539+ parseJSON = withText "MatchQueryType" parse
2540+ where parse "phrase" = pure MatchPhrase
2541+ parse "phrase_prefix" = pure MatchPhrasePrefix
2542+ parse t = fail ("Unexpected MatchQueryType: " <> show t)
2543+
2544+instance FromJSON Status where
2545+ parseJSON (Object v) = Status <$>
2546+ v .:? "ok" <*>
2547+ v .: "status" <*>
2548+ v .: "name" <*>
2549+ v .: "version" <*>
2550+ v .: "tagline"
2551+ parseJSON _ = empty
2552+
2553+
2554+instance ToJSON IndexSettings where
2555+ toJSON (IndexSettings s r) = object ["settings" .=
2556+ object ["index" .=
2557+ object ["number_of_shards" .= s, "number_of_replicas" .= r]
2558+ ]
2559+ ]
2560+
2561+instance ToJSON IndexTemplate where
2562+ toJSON (IndexTemplate p s m) = merge
2563+ (object [ "template" .= p
2564+ , "mappings" .= foldl' merge (object []) m
2565+ ])
2566+ (toJSON s)
2567+ where
2568+ merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
2569+ merge o Null = o
2570+ merge _ _ = undefined
2571+
2572+instance (FromJSON a) => FromJSON (EsResult a) where
2573+ parseJSON jsonVal@(Object v) = do
2574+ found <- v .:? "found" .!= False
2575+ fr <- if found
2576+ then parseJSON jsonVal
2577+ else return Nothing
2578+ EsResult <$> v .: "_index" <*>
2579+ v .: "_type" <*>
2580+ v .: "_id" <*>
2581+ pure fr
2582+ parseJSON _ = empty
2583+
2584+instance (FromJSON a) => FromJSON (EsResultFound a) where
2585+ parseJSON (Object v) = EsResultFound <$>
2586+ v .: "_version" <*>
2587+ v .: "_source"
2588+ parseJSON _ = empty
2589+
2590+instance FromJSON EsError where
2591+ parseJSON (Object v) = EsError <$>
2592+ v .: "status" <*>
2593+ v .: "error"
2594+ parseJSON _ = empty
2595+
2596+instance FromJSON IndexAliasesSummary where
2597+ parseJSON = withObject "IndexAliasesSummary" parse
2598+ where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
2599+ go ixn = withObject "index aliases" $ \ia -> do
2600+ aliases <- ia .: "aliases"
2601+ forM (HM.toList aliases) $ \(aName, v) -> do
2602+ let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
2603+ IndexAliasSummary indexAlias <$> parseJSON v
2604+
2605+
2606+instance ToJSON IndexAliasAction where
2607+ toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
2608+ where Object iaObj = toJSON ia
2609+ Object optsObj = toJSON opts
2610+ toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
2611+ where Object iaObj = toJSON ia
2612+
2613+instance ToJSON IndexAlias where
2614+ toJSON IndexAlias {..} = object ["index" .= srcIndex
2615+ , "alias" .= indexAlias
2616+ ]
2617+
2618+instance ToJSON IndexAliasCreate where
2619+ toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
2620+ where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
2621+ Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
2622+
2623+instance ToJSON AliasRouting where
2624+ toJSON (AllAliasRouting v) = object ["routing" .= v]
2625+ toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
2626+ where prs = [("search_routing" .=) <$> srch
2627+ ,("index_routing" .=) <$> idx]
2628+
2629+instance FromJSON AliasRouting where
2630+ parseJSON = withObject "AliasRouting" parse
2631+ where parse o = parseAll o <|> parseGranular o
2632+ parseAll o = AllAliasRouting <$> o .: "routing"
2633+ parseGranular o = do
2634+ sr <- o .:? "search_routing"
2635+ ir <- o .:? "index_routing"
2636+ if isNothing sr && isNothing ir
2637+ then fail "Both search_routing and index_routing can't be blank"
2638+ else return (GranularAliasRouting sr ir)
2639+
2640+instance FromJSON IndexAliasCreate where
2641+ parseJSON v = withObject "IndexAliasCreate" parse v
2642+ where parse o = IndexAliasCreate <$> optional (parseJSON v)
2643+ <*> o .:? "filter"
2644+
2645+instance ToJSON SearchAliasRouting where
2646+ toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
2647+
2648+instance FromJSON SearchAliasRouting where
2649+ parseJSON = withText "SearchAliasRouting" parse
2650+ where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
2651+
2652+instance ToJSON Search where
2653+ toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
2654+ omitNulls [ "query" .= query
2655+ , "filter" .= sFilter
2656+ , "sort" .= sort
2657+ , "aggregations" .= searchAggs
2658+ , "highlight" .= highlight
2659+ , "from" .= sFrom
2660+ , "size" .= sSize
2661+ , "track_scores" .= sTrackSortScores
2662+ , "fields" .= sFields
2663+ , "_source" .= sSource]
2664+
4892665
4902666instance ToJSON Source where
4912667 toJSON NoSource = toJSON False
4922668 toJSON (SourcePatterns patterns) = toJSON patterns
493− toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
494−
495−data PatternOrPatterns = PopPattern Pattern
496− | PopPatterns [Pattern] deriving (Eq, Read, Show)
2669+ toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
4972670
4982671instance ToJSON PatternOrPatterns where
4992672 toJSON (PopPattern pattern) = toJSON pattern
5002673 toJSON (PopPatterns patterns) = toJSON patterns
5012674
502−data Include = Include [Pattern] deriving (Eq, Read, Show)
503−data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
504−
5052675instance ToJSON Include where
5062676 toJSON (Include patterns) = toJSON patterns
5072677
5082678instance ToJSON Exclude where
5092679 toJSON (Exclude patterns) = toJSON patterns
5102680
511−newtype Pattern = Pattern Text deriving (Eq, Read, Show)
512−
5132681instance ToJSON Pattern where
5142682 toJSON (Pattern pattern) = toJSON pattern
5152683
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)
2684+
2685+instance ToJSON FieldHighlight where
2686+ toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
2687+ object [ fName .= fSettings ]
2688+ toJSON (FieldHighlight (FieldName fName) Nothing) =
2689+ object [ fName .= emptyObject ]
2690+
2691+instance ToJSON Highlights where
2692+ toJSON (Highlights global fields) =
2693+ omitNulls (("fields" .= fields)
2694+ : highlightSettingsPairs global)
2695+
2696+instance ToJSON HighlightSettings where
2697+ toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
2698+
2699+highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
2700+highlightSettingsPairs Nothing = []
2701+highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
2702+highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
2703+highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
2704+
2705+
2706+plainHighPairs :: Maybe PlainHighlight -> [Pair]
2707+plainHighPairs Nothing = []
2708+plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
2709+ [ "type" .= String "plain"]
2710+ ++ commonHighlightPairs plCom
2711+ ++ nonPostingsToPairs plNonPost
2712+
2713+postHighPairs :: Maybe PostingsHighlight -> [Pair]
2714+postHighPairs Nothing = []
2715+postHighPairs (Just (PostingsHighlight pCom)) =
2716+ ("type" .= String "postings")
2717+ : commonHighlightPairs pCom
2718+
2719+fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
2720+fastVectorHighPairs Nothing = []
2721+fastVectorHighPairs (Just
2722+ (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
2723+ fvBoundMaxScan fvFragOff fvMatchedFields
2724+ fvPhraseLim)) =
2725+ [ "type" .= String "fvh"
2726+ , "boundary_chars" .= fvBoundChars
2727+ , "boundary_max_scan" .= fvBoundMaxScan
2728+ , "fragment_offset" .= fvFragOff
2729+ , "matched_fields" .= fvMatchedFields
2730+ , "phraseLimit" .= fvPhraseLim]
2731+ ++ commonHighlightPairs fvCom
2732+ ++ nonPostingsToPairs fvNonPostSettings
2733+
2734+deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
2735+deleteSeveral ks hm = foldr HM.delete hm ks
2736+
2737+commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
2738+commonHighlightPairs Nothing = []
2739+commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
2740+ chNoMatchSize chHighlightQuery
2741+ chRequireFieldMatch)) =
2742+ [ "order" .= chScore
2743+ , "force_source" .= chForceSource
2744+ , "encoder" .= chEncoder
2745+ , "no_match_size" .= chNoMatchSize
2746+ , "highlight_query" .= chHighlightQuery
2747+ , "require_fieldMatch" .= chRequireFieldMatch]
2748+ ++ highlightTagToPairs chTag
2749+
2750+
2751+nonPostingsToPairs :: Maybe NonPostings -> [Pair]
2752+nonPostingsToPairs Nothing = []
2753+nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
2754+ [ "fragment_size" .= npFragSize
2755+ , "number_of_fragments" .= npNumOfFrags]
2756+
2757+parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
2758+parseNEJSON [] = fail "Expected non-empty list"
2759+parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
2760+
2761+
2762+instance ToJSON HighlightEncoder where
2763+ toJSON DefaultEncoder = String "default"
2764+ toJSON HTMLEncoder = String "html"
2765+
2766+highlightTagToPairs :: Maybe HighlightTag -> [Pair]
2767+highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
2768+highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
2769+ , "post_tags" .= post]
2770+highlightTagToPairs Nothing = []
2771+
2772+instance ToJSON SortSpec where
2773+ toJSON (DefaultSortSpec
2774+ (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
2775+ dsSortMode dsMissingSort dsNestedFilter)) =
2776+ object [dsSortFieldName .= omitNulls base] where
2777+ base = [ "order" .= dsSortOrder
2778+ , "ignore_unmapped" .= dsIgnoreUnmapped
2779+ , "mode" .= dsSortMode
2780+ , "missing" .= dsMissingSort
2781+ , "nested_filter" .= dsNestedFilter ]
2782+
2783+ toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
2784+ object [ "unit" .= units
2785+ , field .= gdsLatLon
2786+ , "order" .= gdsSortOrder ]
2787+
2788+
2789+instance ToJSON SortOrder where
2790+ toJSON Ascending = String "asc"
2791+ toJSON Descending = String "desc"
2792+
2793+
2794+instance ToJSON SortMode where
2795+ toJSON SortMin = String "min"
2796+ toJSON SortMax = String "max"
2797+ toJSON SortSum = String "sum"
2798+ toJSON SortAvg = String "avg"
2799+
2800+
2801+instance ToJSON Missing where
2802+ toJSON LastMissing = String "_last"
2803+ toJSON FirstMissing = String "_first"
2804+ toJSON (CustomMissing txt) = String txt
2805+
2806+
2807+instance ToJSON ScoreType where
2808+ toJSON ScoreTypeMax = "max"
2809+ toJSON ScoreTypeAvg = "avg"
2810+ toJSON ScoreTypeSum = "sum"
2811+ toJSON ScoreTypeNone = "none"
2812+
2813+instance FromJSON ScoreType where
2814+ parseJSON = withText "ScoreType" parse
2815+ where parse "max" = pure ScoreTypeMax
2816+ parse "avg" = pure ScoreTypeAvg
2817+ parse "sum" = pure ScoreTypeSum
2818+ parse "none" = pure ScoreTypeNone
2819+ parse t = fail ("Unexpected ScoreType: " <> show t)
2820+
2821+instance ToJSON Distance where
2822+ toJSON (Distance dCoefficient dUnit) =
2823+ String boltedTogether where
2824+ coefText = showText dCoefficient
2825+ (String unitText) = toJSON dUnit
2826+ boltedTogether = mappend coefText unitText
2827+
2828+instance FromJSON Distance where
2829+ parseJSON = withText "Distance" parse
2830+ where parse t = Distance <$> parseCoeff nT
2831+ <*> parseJSON (String unitT)
2832+ where (nT, unitT) = T.span validForNumber t
2833+ -- may be a better way to do this
2834+ validForNumber '-' = True
2835+ validForNumber '.' = True
2836+ validForNumber 'e' = True
2837+ validForNumber c = isNumber c
2838+ parseCoeff "" = fail "Empty string cannot be parsed as number"
2839+ parseCoeff s = return (read (T.unpack s))
2840+
2841+instance ToJSON DistanceUnit where
2842+ toJSON Miles = String "mi"
2843+ toJSON Yards = String "yd"
2844+ toJSON Feet = String "ft"
2845+ toJSON Inches = String "in"
2846+ toJSON Kilometers = String "km"
2847+ toJSON Meters = String "m"
2848+ toJSON Centimeters = String "cm"
2849+ toJSON Millimeters = String "mm"
2850+ toJSON NauticalMiles = String "nmi"
2851+
2852+
2853+instance FromJSON DistanceUnit where
2854+ parseJSON = withText "DistanceUnit" parse
2855+ where parse "mi" = pure Miles
2856+ parse "yd" = pure Yards
2857+ parse "ft" = pure Feet
2858+ parse "in" = pure Inches
2859+ parse "km" = pure Kilometers
2860+ parse "m" = pure Meters
2861+ parse "cm" = pure Centimeters
2862+ parse "mm" = pure Millimeters
2863+ parse "nmi" = pure NauticalMiles
2864+ parse u = fail ("Unrecognized DistanceUnit: " <> show u)
2865+
2866+instance ToJSON DistanceType where
2867+ toJSON Arc = String "arc"
2868+ toJSON SloppyArc = String "sloppy_arc"
2869+ toJSON Plane = String "plane"
2870+
2871+instance FromJSON DistanceType where
2872+ parseJSON = withText "DistanceType" parse
2873+ where parse "arc" = pure Arc
2874+ parse "sloppy_arc" = pure SloppyArc
2875+ parse "plane" = pure Plane
2876+ parse t = fail ("Unrecognized DistanceType: " <> show t)
2877+
2878+
2879+instance ToJSON OptimizeBbox where
2880+ toJSON NoOptimizeBbox = String "none"
2881+ toJSON (OptimizeGeoFilterType gft) = toJSON gft
2882+
2883+instance FromJSON OptimizeBbox where
2884+ parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
2885+ <|> parseOptimize v
2886+ where parseNoOptimize "none" = pure NoOptimizeBbox
2887+ parseNoOptimize _ = mzero
2888+ parseOptimize = fmap OptimizeGeoFilterType . parseJSON
2889+
2890+instance ToJSON GeoBoundingBoxConstraint where
2891+ toJSON (GeoBoundingBoxConstraint
2892+ (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
2893+ object [gbbcGeoBBField .= gbbcConstraintBox
2894+ , "_cache" .= cache
2895+ , "type" .= type']
2896+
2897+instance FromJSON GeoBoundingBoxConstraint where
2898+ parseJSON = withObject "GeoBoundingBoxConstraint" parse
2899+ where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
2900+ [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
2901+ <$> parseJSON v
2902+ <*> o .:? "_cache" .!= defaultCache
2903+ <*> o .: "type"
2904+ _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
2905+
2906+instance ToJSON GeoFilterType where
2907+ toJSON GeoFilterMemory = String "memory"
2908+ toJSON GeoFilterIndexed = String "indexed"
2909+
2910+instance FromJSON GeoFilterType where
2911+ parseJSON = withText "GeoFilterType" parse
2912+ where parse "memory" = pure GeoFilterMemory
2913+ parse "indexed" = pure GeoFilterIndexed
2914+ parse t = fail ("Unrecognized GeoFilterType: " <> show t)
2915+
2916+instance ToJSON GeoBoundingBox where
2917+ toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
2918+ object ["top_left" .= gbbTopLeft
2919+ , "bottom_right" .= gbbBottomRight]
2920+
2921+instance FromJSON GeoBoundingBox where
2922+ parseJSON = withObject "GeoBoundingBox" parse
2923+ where parse o = GeoBoundingBox
2924+ <$> o .: "top_left"
2925+ <*> o .: "bottom_right"
2926+
2927+instance ToJSON LatLon where
2928+ toJSON (LatLon lLat lLon) =
2929+ object ["lat" .= lLat
2930+ , "lon" .= lLon]
2931+
2932+instance FromJSON LatLon where
2933+ parseJSON = withObject "LatLon" parse
2934+ where parse o = LatLon <$> o .: "lat"
2935+ <*> o .: "lon"
2936+
2937+-- index for smaller ranges, fielddata for longer ranges
2938+instance ToJSON RangeExecution where
2939+ toJSON RangeExecutionIndex = "index"
2940+ toJSON RangeExecutionFielddata = "fielddata"
2941+
2942+
2943+instance FromJSON RangeExecution where
2944+ parseJSON = withText "RangeExecution" parse
2945+ where parse "index" = pure RangeExecutionIndex
2946+ parse "fielddata" = pure RangeExecutionFielddata
2947+ parse t = error ("Unrecognized RangeExecution " <> show t)
2948+
2949+instance ToJSON RegexpFlags where
2950+ toJSON AllRegexpFlags = String "ALL"
2951+ toJSON NoRegexpFlags = String "NONE"
2952+ toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
2953+ where flagStrs = map flagStr . nub $ h:fs
2954+ flagStr AnyString = "ANYSTRING"
2955+ flagStr Automaton = "AUTOMATON"
2956+ flagStr Complement = "COMPLEMENT"
2957+ flagStr Empty = "EMPTY"
2958+ flagStr Intersection = "INTERSECTION"
2959+ flagStr Interval = "INTERVAL"
2960+
2961+instance FromJSON RegexpFlags where
2962+ parseJSON = withText "RegexpFlags" parse
2963+ where parse "ALL" = pure AllRegexpFlags
2964+ parse "NONE" = pure NoRegexpFlags
2965+ parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
2966+
2967+instance FromJSON RegexpFlag where
2968+ parseJSON = withText "RegexpFlag" parse
2969+ where parse "ANYSTRING" = pure AnyString
2970+ parse "AUTOMATON" = pure Automaton
2971+ parse "COMPLEMENT" = pure Complement
2972+ parse "EMPTY" = pure Empty
2973+ parse "INTERSECTION" = pure Intersection
2974+ parse "INTERVAL" = pure Interval
2975+ parse f = fail ("Unknown RegexpFlag: " <> show f)
2976+
2977+instance ToJSON Term where
2978+ toJSON (Term field value) = object ["term" .= object
2979+ [field .= value]]
2980+
2981+instance FromJSON Term where
2982+ parseJSON = withObject "Term" parse
2983+ where parse o = do termObj <- o .: "term"
2984+ case HM.toList termObj of
2985+ [(fn, v)] -> Term fn <$> parseJSON v
2986+ _ -> fail "Expected object with 1 field-named key"
2987+
2988+instance ToJSON BoolMatch where
2989+ toJSON (MustMatch term cache) = object ["must" .= term,
2990+ "_cache" .= cache]
2991+ toJSON (MustNotMatch term cache) = object ["must_not" .= term,
2992+ "_cache" .= cache]
2993+ toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
2994+ "_cache" .= cache]
2995+
2996+instance FromJSON BoolMatch where
2997+ parseJSON = withObject "BoolMatch" parse
2998+ where parse o = mustMatch `taggedWith` "must"
2999+ <|> mustNotMatch `taggedWith` "must_not"
3000+ <|> shouldMatch `taggedWith` "should"
3001+ where taggedWith parser k = parser =<< o .: k
3002+ mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3003+ mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3004+ shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
5283005
5293006instance (FromJSON a) => FromJSON (SearchResult a) where
5303007 parseJSON (Object v) = SearchResult <$>
@@ -533,10 +3010,52 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
5333010 v .: "_shards" <*>
5343011 v .: "hits" <*>
5353012 v .:? "aggregations" <*>
536− v .:? "_scroll_id" <*>
537− v .:? "suggest"
3013+ v .:? "_scroll_id"
3014+ parseJSON _ = empty
3015+
3016+instance (FromJSON a) => FromJSON (SearchHits a) where
3017+ parseJSON (Object v) = SearchHits <$>
3018+ v .: "total" <*>
3019+ v .: "max_score" <*>
3020+ v .: "hits"
5383021 parseJSON _ = empty
5393022
540−newtype ScrollId =
541− ScrollId Text
542− deriving (Eq, Show, Ord, ToJSON, FromJSON)
3023+instance (FromJSON a) => FromJSON (Hit a) where
3024+ parseJSON (Object v) = Hit <$>
3025+ v .: "_index" <*>
3026+ v .: "_type" <*>
3027+ v .: "_id" <*>
3028+ v .: "_score" <*>
3029+ v .:? "_source" <*>
3030+ v .:? "highlight"
3031+ parseJSON _ = empty
3032+
3033+instance FromJSON ShardResult where
3034+ parseJSON (Object v) = ShardResult <$>
3035+ v .: "total" <*>
3036+ v .: "successful" <*>
3037+ v .: "failed"
3038+ parseJSON _ = empty
3039+
3040+
3041+instance FromJSON DocVersion where
3042+ parseJSON v = do
3043+ i <- parseJSON v
3044+ maybe (fail "DocVersion out of range") return $ mkDocVersion i
3045+
3046+instance Bounded DocVersion where
3047+ minBound = DocVersion 1
3048+ maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3049+
3050+instance Enum DocVersion where
3051+ succ x
3052+ | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3053+ | otherwise = succError "DocVersion"
3054+ pred x
3055+ | x /= minBound = DocVersion (pred $ docVersionNumber x)
3056+ | otherwise = predError "DocVersion"
3057+ toEnum i =
3058+ fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3059+ fromEnum = docVersionNumber
3060+ enumFrom = boundedEnumFrom
3061+ enumFromThen = boundedEnumFromThen