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