@@ -1,8 +1,8 @@
1−{-# LANGUAGE DeriveGeneric #-}
21{-# LANGUAGE FlexibleContexts #-}
32{-# LANGUAGE FlexibleInstances #-}
43{-# LANGUAGE GeneralizedNewtypeDeriving #-}
54{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE NamedFieldPuns #-}
66{-# LANGUAGE OverloadedStrings #-}
77{-# LANGUAGE RecordWildCards #-}
88{-# LANGUAGE UndecidableInstances #-}
@@ -10,11 +10,11 @@
1010-------------------------------------------------------------------------------
1111-- |
1212-- Module : Database.Bloodhound.Types
13−-- Copyright : (C) 2014 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
1414-- License : BSD-style (see the file LICENSE)
1515-- Maintainer : Chris Allen <cma@bitemyapp.com
1616-- Stability : provisional
17−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
1818--
1919-- Data types for describing actions and data structures performed to interact
2020-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -42,26 +42,53 @@ module Database.Bloodhound.Types
4242 , mkTermsAggregation
4343 , mkTermsScriptAggregation
4444 , mkDateHistogram
45+ , mkCardinalityAggregation
4546 , mkDocVersion
47+ , mkStatsAggregation
48+ , mkExtendedStatsAggregation
4649 , docVersionNumber
50+ , toMissing
4751 , toTerms
4852 , toDateHistogram
53+ , toTopHits
4954 , omitNulls
5055 , BH(..)
5156 , runBH
52− , BHEnv(..)
57+ , BHEnv
58+ , bhServer
59+ , bhManager
60+ , bhRequestHook
61+ , mkBHEnv
5362 , MonadBH(..)
5463 , Version(..)
64+ , VersionNumber(..)
65+ , MaybeNA(..)
66+ , BuildHash(..)
5567 , Status(..)
5668 , Existence(..)
5769 , NullValue(..)
5870 , IndexSettings(..)
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(..)
5985 , IndexTemplate(..)
6086 , Server(..)
6187 , Reply
6288 , EsResult(..)
6389 , EsResultFound(..)
6490 , EsError(..)
91+ , EsProtocolException(..)
6592 , IndexAlias(..)
6693 , IndexAliasName(..)
6794 , IndexAliasAction(..)
@@ -81,7 +108,7 @@ module Database.Bloodhound.Types
81108 , Search(..)
82109 , SearchType(..)
83110 , SearchResult(..)
84− , ScrollId
111+ , ScrollId(..)
85112 , SearchHits(..)
86113 , TrackSortScores
87114 , From(..)
@@ -93,8 +120,8 @@ module Database.Bloodhound.Types
93120 , Pattern(..)
94121 , ShardResult(..)
95122 , Hit(..)
123+ , HitFields(..)
96124 , Filter(..)
97− , Seminearring(..)
98125 , BoolMatch(..)
99126 , Term(..)
100127 , GeoPoint(..)
@@ -121,8 +148,22 @@ module Database.Bloodhound.Types
121148 , RegexpFlags(..)
122149 , RegexpFlag(..)
123150 , FieldName(..)
151+ , ScriptFields(..)
152+ , ScriptFieldName
153+ , ScriptFieldValue
124154 , Script(..)
155+ , ScriptLanguage(..)
156+ , ScriptInline(..)
157+ , ScriptId(..)
158+ , ScriptParams(..)
159+ , ScriptParamName
160+ , ScriptParamValue
125161 , IndexName(..)
162+ , IndexSelection(..)
163+ , NodeSelection(..)
164+ , NodeSelector(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
126167 , TemplateName(..)
127168 , TemplatePattern(..)
128169 , MappingName(..)
@@ -146,8 +187,19 @@ module Database.Bloodhound.Types
146187 , BoolQuery(..)
147188 , BoostingQuery(..)
148189 , 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(..)
149202 , DisMaxQuery(..)
150− , FilteredQuery(..)
151203 , FuzzyLikeThisQuery(..)
152204 , FuzzyLikeFieldQuery(..)
153205 , FuzzyQuery(..)
@@ -163,10 +215,16 @@ module Database.Bloodhound.Types
163215 , RangeQuery(..)
164216 , RegexpQuery(..)
165217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
220+ , WildcardQuery(..)
166221 , BooleanOperator(..)
167222 , ZeroTermsQuery(..)
168223 , CutoffFrequency(..)
169224 , Analyzer(..)
225+ , Tokenizer(..)
226+ , TokenFilter(..)
227+ , CharFilter(..)
170228 , MaxExpansions(..)
171229 , Lenient(..)
172230 , MatchQueryType(..)
@@ -213,16 +271,118 @@ module Database.Bloodhound.Types
213271 , CollectionMode(..)
214272 , TermOrder(..)
215273 , 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 (..)
216363
217364 , Aggregation(..)
218365 , Aggregations
219366 , AggregationResults
367+ , BucketValue(..)
220368 , Bucket(..)
221369 , BucketAggregation(..)
222370 , TermsAggregation(..)
371+ , MissingAggregation(..)
223372 , ValueCountAggregation(..)
224373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
225376 , DateHistogramAggregation(..)
377+ , DateRangeAggregation(..)
378+ , DateRangeAggRange(..)
379+ , DateMathExpr(..)
380+ , DateMathAnchor(..)
381+ , DateMathModifier(..)
382+ , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
385+ , SearchAfterKey
226386
227387 , Highlights(..)
228388 , FieldHighlight(..)
@@ -236,539 +396,36 @@ module Database.Bloodhound.Types
236396 , HighlightTag(..)
237397 , HitHighlight
238398
399+ , MissingResult(..)
239400 , TermsResult(..)
240401 , DateHistogramResult(..)
241− ) where
242−
243−import Control.Applicative
244−import Control.Monad.Catch
245−import Control.Monad.Except
246−import Control.Monad.Reader
247−import Control.Monad.State
248−import Control.Monad.Writer
249−import Data.Aeson
250−import Data.Aeson.Types (Pair, Parser, emptyObject,
251− parseMaybe)
252−import qualified Data.ByteString.Lazy.Char8 as L
253−import Data.Char
254−import qualified Data.HashMap.Strict as HM
255−import Data.List (foldl', nub)
256−import Data.List.NonEmpty (NonEmpty (..), toList)
257−import qualified Data.Map.Strict as M
258−import Data.Maybe
259−import Data.Text (Text)
260−import qualified Data.Text as T
261−import Data.Time.Clock (UTCTime)
262−import qualified Data.Traversable as DT
263−import qualified Data.Vector as V
264−import GHC.Enum
265−import GHC.Generics (Generic)
266−import Network.HTTP.Client
267−import qualified Network.HTTP.Types.Method as NHTM
268−
269−import Database.Bloodhound.Types.Class
270−
271−-- $setup
272−-- >>> :set -XOverloadedStrings
273−-- >>> import Database.Bloodhound
274−-- >>> let testServer = (Server "http://localhost:9200")
275−-- >>> let testIndex = IndexName "twitter"
276−-- >>> let testMapping = MappingName "tweet"
277−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
278−
279−-- defaultIndexSettings is exported by Database.Bloodhound as well
280−-- no trailing slashes in servers, library handles building the path.
281−
282−{-| Common environment for Elasticsearch calls. Connections will be
283− pipelined according to the provided HTTP connection manager.
284−-}
285−data BHEnv = BHEnv { bhServer :: Server
286− , bhManager :: Manager
287− }
288−
289−{-| All API calls to Elasticsearch operate within
290− MonadBH. The idea is that it can be easily embedded in your
291− own monad transformer stack. A default instance for a ReaderT and
292− alias 'BH' is provided for the simple case.
293−-}
294−class (Functor m, Applicative m, MonadIO m) => MonadBH m where
295− getBHEnv :: m BHEnv
296−
297−newtype BH m a = BH {
298− unBH :: ReaderT BHEnv m a
299− } deriving ( Functor
300− , Applicative
301− , Monad
302− , MonadIO
303− , MonadState s
304− , MonadWriter w
305− , MonadError e
306− , Alternative
307− , MonadPlus
308− , MonadFix
309− , MonadThrow
310− , MonadCatch
311− , MonadMask)
312−
313−instance MonadTrans BH where
314− lift = BH . lift
315−
316−instance (MonadReader r m) => MonadReader r (BH m) where
317− ask = lift ask
318− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
319− local f (m r)
320−
321−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
322− getBHEnv = BH getBHEnv
323−
324−
325−instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where
326− getBHEnv = ask
327−
328−runBH :: BHEnv -> BH m a -> m a
329−runBH e f = runReaderT (unBH f) e
330−
331−{-| 'Version' is embedded in 'Status' -}
332−data Version = Version { number :: Text
333− , build_hash :: Text
334− , build_timestamp :: UTCTime
335− , build_snapshot :: Bool
336− , lucene_version :: Text } deriving (Eq, Show, Generic)
337−
338−{-| 'Status' is a data type for describing the JSON body returned by
339− Elasticsearch when you query its status. This was deprecated in 1.2.0.
340−
341− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
342−-}
343−
344−data Status = Status { ok :: Maybe Bool
345− , status :: Int
346− , name :: Text
347− , version :: Version
348− , tagline :: Text } deriving (Eq, Show)
349−
350−{-| 'IndexSettings' is used to configure the shards and replicas when you create
351− an Elasticsearch Index.
352−
353− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
354−-}
355−
356−data IndexSettings =
357− IndexSettings { indexShards :: ShardCount
358− , indexReplicas :: ReplicaCount } deriving (Eq, Show)
359−
360−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
361−defaultIndexSettings :: IndexSettings
362−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
363−
364−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
365−type Reply = Network.HTTP.Client.Response L.ByteString
366−type Method = NHTM.Method
367−
368−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
369−
370− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
371−-}
372−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show)
373−
374−data FieldType = GeoPointType
375− | GeoShapeType
376− | FloatType
377− | IntegerType
378− | LongType
379− | ShortType
380− | ByteType deriving (Eq, Show)
381−
382−data FieldDefinition =
383− FieldDefinition { fieldType :: FieldType } deriving (Eq, Show)
384−
385−{-| An 'IndexTemplate' defines a template that will automatically be
386− applied to new indices created. The templates include both
387− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
388− controls if the template will be applied to the index created.
389− Specify mappings as follows: @[toJSON TweetMapping, ...]@
390−
391− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
392−-}
393−data IndexTemplate =
394− IndexTemplate { templatePattern :: TemplatePattern
395− , templateSettings :: Maybe IndexSettings
396− , templateMappings :: [Value]
397− }
398−
399−data MappingField =
400− MappingField { mappingFieldName :: FieldName
401− , fieldDefinition :: FieldDefinition } deriving (Eq, Show)
402−
403−{-| Support for type reification of 'Mapping's is currently incomplete, for
404− now the mapping API verbiage expects a 'ToJSON'able blob.
405−
406− Indexes have mappings, mappings are schemas for the documents contained in the
407− index. I'd recommend having only one mapping per index, always having a mapping,
408− and keeping different kinds of documents separated if possible.
409−-}
410−data Mapping = Mapping { typeName :: TypeName
411− , mappingFields :: [MappingField] } deriving (Eq, Show)
412−
413−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
414− operation index, create, delete, and update. 'BulkIndex' behaves like an
415− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
416−
417− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
418−-}
419−data BulkOperation =
420− BulkIndex IndexName MappingName DocId Value
421− | BulkCreate IndexName MappingName DocId Value
422− | BulkDelete IndexName MappingName DocId
423− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show)
424−
425−{-| 'EsResult' describes the standard wrapper JSON document that you see in
426− successful Elasticsearch lookups or lookups that couldn't find the document.
427−-}
428−data EsResult a = EsResult { _index :: Text
429− , _type :: Text
430− , _id :: Text
431− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show)
432−
433−{-| 'EsResultFound' contains the document and its metadata inside of an
434− 'EsResult' when the document was successfully found.
435−-}
436−data EsResultFound a = EsResultFound { _version :: DocVersion
437− , _source :: a } deriving (Eq, Show)
438−
439−{-| 'EsError' is the generic type that will be returned when there was a
440− problem. If you can't parse the expected response, its a good idea to
441− try parsing this.
442−-}
443−data EsError = EsError { errorStatus :: Int
444− , errorMessage :: Text } deriving (Eq, Show)
445−
446−data IndexAlias = IndexAlias { srcIndex :: IndexName
447− , indexAlias :: IndexAliasName } deriving (Eq, Show)
448−
449−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Show, ToJSON)
450−
451−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
452− | RemoveAlias IndexAlias deriving (Show, Eq)
453−
454−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
455− , aliasCreateFilter :: Maybe Filter}
456− deriving (Show, Eq)
457−
458−data AliasRouting = AllAliasRouting RoutingValue
459− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
460− deriving (Show, Eq)
461−
462−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Show, Eq)
463−
464−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Show, Eq, ToJSON, FromJSON)
465−
466−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Show, Eq, ToJSON, FromJSON)
467−
468−newtype IndexAliasesSummary = IndexAliasesSummary [IndexAliasSummary]
469−
470−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
471− , indexAliasSummaryCreate :: IndexAliasCreate}
472−
473−{-| 'DocVersion' is an integer version number for a document between 1
474−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
475−-}
476−newtype DocVersion = DocVersion {
477− docVersionNumber :: Int
478− } deriving (Eq, Show, Ord, ToJSON)
479−
480−-- | Smart constructor for in-range doc version
481−mkDocVersion :: Int -> Maybe DocVersion
482−mkDocVersion i
483− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
484− Just $ DocVersion i
485− | otherwise = Nothing
486−
487−
488−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
489−own version numbers instead of ones from ES.
490−-}
491−newtype ExternalDocVersion = ExternalDocVersion DocVersion
492− deriving (Eq, Show, Ord, Bounded, Enum, ToJSON)
493−
494−{-| 'VersionControl' is specified when indexing documents as a
495−optimistic concurrency control.
496−-}
497−data VersionControl = NoVersionControl
498− -- ^ Don't send a version. This is a pure overwrite.
499− | InternalVersion DocVersion
500− -- ^ Use the default ES versioning scheme. Only
501− -- index the document if the version is the same
502− -- as the one specified. Only applicable to
503− -- updates, as you should be getting Version from
504− -- a search result.
505− | ExternalGT ExternalDocVersion
506− -- ^ Use your own version numbering. Only index
507− -- the document if the version is strictly higher
508− -- OR the document doesn't exist. The given
509− -- version will be used as the new version number
510− -- for the stored document. N.B. All updates must
511− -- increment this number, meaning there is some
512− -- global, external ordering of updates.
513− | ExternalGTE ExternalDocVersion
514− -- ^ Use your own version numbering. Only index
515− -- the document if the version is equal or higher
516− -- than the stored version. Will succeed if there
517− -- is no existing document. The given version will
518− -- be used as the new version number for the
519− -- stored document. Use with care, as this could
520− -- result in data loss.
521− | ForceVersion ExternalDocVersion
522− -- ^ The document will always be indexed and the
523− -- given version will be the new version. This is
524− -- typically used for correcting errors. Use with
525− -- care, as this could result in data loss.
526− deriving (Show, Eq, Ord)
527−
528−{-| 'DocumentParent' is used to specify a parent document.
529−-}
530−newtype DocumentParent = DocumentParent DocId
531− deriving (Eq, Show)
532−
533−{-| 'IndexDocumentSettings' are special settings supplied when indexing
534−a document. For the best backwards compatiblity when new fields are
535−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
536−-}
537−data IndexDocumentSettings =
538− IndexDocumentSettings { idsVersionControl :: VersionControl
539− , idsParent :: Maybe DocumentParent
540− } deriving (Eq, Show)
541−
542−{-| Reasonable default settings. Chooses no version control and no parent.
543−-}
544−defaultIndexDocumentSettings :: IndexDocumentSettings
545−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
546−
547−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
548− dependent with later sorts acting as tie-breakers for earlier sorts.
549−-}
550−type Sort = [SortSpec]
551−
552−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
553− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
554− 'DistanceUnit' to express "nearness" to a single geographical point as a
555− sort specification.
556−
557−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
558−-}
559−data SortSpec = DefaultSortSpec DefaultSort
560− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show)
561−
562−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
563− 'mkSort' convenience function for when you want to specify only the most
564− common parameters.
565−
566−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
567−-}
568−data DefaultSort =
569− DefaultSort { sortFieldName :: FieldName
570− , sortOrder :: SortOrder
571− -- default False
572− , ignoreUnmapped :: Bool
573− , sortMode :: Maybe SortMode
574− , missingSort :: Maybe Missing
575− , nestedFilter :: Maybe Filter } deriving (Eq, Show)
576−
577−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
578− encoded into "asc" or "desc" when turned into JSON.
579−
580−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
581−-}
582−data SortOrder = Ascending
583− | Descending deriving (Eq, Show)
584−
585−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
586− sorted last, first, or using a custom value as a substitute.
587−
588−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
589−-}
590−data Missing = LastMissing
591− | FirstMissing
592− | CustomMissing Text deriving (Eq, Show)
593−
594−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
595−
596−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
597−-}
598−data SortMode = SortMin
599− | SortMax
600− | SortSum
601− | SortAvg deriving (Eq, Show)
602−
603−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
604− that you can concisely describe the usual kind of 'SortSpec's you want.
605−-}
606−mkSort :: FieldName -> SortOrder -> DefaultSort
607−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
608−
609−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
610− 'Query's cannot be cached.
611−-}
612−type Cache = Bool -- caching on/off
613−defaultCache :: Cache
614−defaultCache = False
615−
616−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
617−-}
618−type PrefixValue = Text
619−
620−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
621− JSON encoding baked in. Used all over the place.
622−-}
623−data BooleanOperator = And | Or deriving (Eq, Show)
624−
625−{-| 'ShardCount' is part of 'IndexSettings'
626−-}
627−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
628−
629−{-| 'ReplicaCount' is part of 'IndexSettings'
630−-}
631−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
632−
633−{-| 'Server' is used with the client functions to point at the ES instance
634−-}
635−newtype Server = Server Text deriving (Eq, Show)
636−
637−{-| 'IndexName' is used to describe which index to query/create/delete
638−-}
639−newtype IndexName = IndexName Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
640−
641−{-| 'TemplateName' is used to describe which template to query/create/delete
642−-}
643−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
644−
645−{-| 'TemplatePattern' represents a pattern which is matched against index names
646−-}
647−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
648−
649−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
650− the data in the indices.
651−-}
652−newtype MappingName = MappingName Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
653−
654−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
655− Can be set by the user or created by ES itself. Often used in client
656− functions for poking at specific documents.
657−-}
658−newtype DocId = DocId Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
659−
660−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
661−-}
662−newtype QueryString = QueryString Text deriving (Eq, Generic, Show, ToJSON, FromJSON)
663−
664−{-| 'FieldName' is used all over the place wherever a specific field within
665− a document needs to be specified, usually in 'Query's or 'Filter's.
666−-}
667−newtype FieldName = FieldName Text deriving (Eq, Show, ToJSON, FromJSON)
668−
669−
670−{-| 'Script' is often used in place of 'FieldName' to specify more
671−complex ways of extracting a value from a document.
672−-}
673−newtype Script = Script { scriptText :: Text } deriving (Eq, Show)
674−
675−{-| 'CacheName' is used in 'RegexpFilter' for describing the
676− 'CacheKey' keyed caching behavior.
677−-}
678−newtype CacheName = CacheName Text deriving (Eq, Show, ToJSON, FromJSON)
679−
680−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
681−-}
682−newtype CacheKey =
683− CacheKey Text deriving (Eq, Show, ToJSON, FromJSON)
684−newtype Existence =
685− Existence Bool deriving (Eq, Show, ToJSON, FromJSON)
686−newtype NullValue =
687− NullValue Bool deriving (Eq, Show, ToJSON, FromJSON)
688−newtype CutoffFrequency =
689− CutoffFrequency Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
690−newtype Analyzer =
691− Analyzer Text deriving (Eq, Show, Generic, ToJSON, FromJSON)
692−newtype MaxExpansions =
693− MaxExpansions Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
694−
695−{-| 'Lenient', if set to true, will cause format based failures to be
696− ignored. I don't know what the bloody default is, Elasticsearch
697− documentation didn't say what it was. Let me know if you figure it out.
698−-}
699−newtype Lenient =
700− Lenient Bool deriving (Eq, Show, Generic, ToJSON, FromJSON)
701−newtype Tiebreaker =
702− Tiebreaker Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
703−newtype Boost =
704− Boost Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
705−newtype BoostTerms =
706− BoostTerms Double deriving (Eq, Show, Generic, ToJSON, FromJSON)
707−
708−{-| 'MinimumMatch' controls how many should clauses in the bool query should
709− match. Can be an absolute value (2) or a percentage (30%) or a
710− combination of both.
711−-}
712−newtype MinimumMatch =
713− MinimumMatch Int deriving (Eq, Show, Generic, ToJSON, FromJSON)
714−newtype MinimumMatchText =
715− MinimumMatchText Text deriving (Eq, Show, 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,2179 +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 (NonEmpty Term)
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 [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 [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 [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 [FieldName]
1009− -- default 0.3 (30%)
1010− , moreLikeThisPercentMatch :: Maybe PercentMatch
1011− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1012− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1013− , moreLikeThisStopWords :: Maybe [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 .: "filters"
1726− <*> o .: "_cache" .!= defaultCache
1727− identityFilter () = pure IdentityFilter
1728− boolFilter = pure . BoolFilter
1729− existsFilter o = ExistsFilter <$> o .: "field"
1730− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1731− geoDistanceFilter o = flip fieldTagged o $ \fn o' -> do
1732− gp <- GeoPoint fn <$> parseJSON (Object o')
1733− GeoDistanceFilter gp <$> o .: "distance"
1734− <*> o .: "distance_type"
1735− <*> o .: "optimize_bbox"
1736− <*> o .:? "_cache" .!= defaultCache
1737− geoDistanceRangeFilter o = flip fieldTagged o $ \fn o' -> do
1738− gp <- GeoPoint fn <$> parseJSON (Object o')
1739− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1740− return (GeoDistanceRangeFilter gp rng)
1741− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
1742− idsFilter o = IdsFilter <$> o .: "type"
1743− <*> o .: "values"
1744− limitFilter o = LimitFilter <$> o .: "value"
1745− missingFilter o = MissingFilter <$> o .: "field"
1746− <*> o .: "existence"
1747− <*> o .: "null_value"
1748− prefixFilter o = flip fieldTagged o $ \fn o' -> PrefixFilter fn <$> parseJSON (Object o')
1749− <*> o .:? "_cache" .!= defaultCache
1750− queryFilter q = pure (QueryFilter q False)
1751− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
1752− rangeFilter o = flip fieldTagged o $ \fn o' -> RangeFilter fn <$> parseJSON (Object o')
1753− <*> o .: "execution"
1754− <*> o .:? "_cache" .!= defaultCache
1755− regexpFilter = fieldTagged $ \fn o -> RegexpFilter fn <$> o .: "value"
1756− <*> o .: "flags"
1757− <*> o .: "_name"
1758− <*> o .:? "_cache" .!= defaultCache
1759− <*> o .: "_cache_key"
1760− termFilter o = flip fieldTagged o $ \(FieldName fn) o' -> do
1761− trm <- Term fn <$> parseJSON (Object o')
1762− TermFilter trm <$> o .: "_cache" .!= defaultCache
1763−
1764−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
1765−fieldTagged f o = case HM.toList o of
1766− [(k, Object o')] -> f (FieldName k) o'
1767− _ -> fail "Expected object with 1 field-named key"
1768−
1769−instance ToJSON GeoPoint where
1770− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
1771− object [ geoPointField .= geoPointLatLon ]
1772−
1773−
1774−instance ToJSON Query where
1775− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
1776− object [ "term" .=
1777− object [termQueryField .= object merged]]
1778− where
1779− base = [ "value" .= termQueryValue ]
1780− boosted = maybe [] (return . ("boost" .=)) boost
1781− merged = mappend base boosted
1782−
1783− toJSON (TermsQuery terms) =
1784− object [ "terms" .= object conjoined ]
1785− where conjoined = [ getTermsField terms .=
1786− fmap (toJSON . getTermValue) (toList terms)]
1787− getTermsField ((Term f _ ) :| _) = f
1788− getTermValue (Term _ v) = v
1789− toJSON (IdsQuery idsQueryMappingName docIds) =
1790− object [ "ids" .= object conjoined ]
1791− where conjoined = [ "type" .= idsQueryMappingName
1792− , "values" .= fmap toJSON docIds ]
1793−
1794− toJSON (QueryQueryStringQuery qQueryStringQuery) =
1795− object [ "query_string" .= qQueryStringQuery ]
1796−
1797− toJSON (QueryMatchQuery matchQuery) =
1798− object [ "match" .= matchQuery ]
1799−
1800− toJSON (QueryMultiMatchQuery multiMatchQuery) =
1801− toJSON multiMatchQuery
1802−
1803− toJSON (QueryBoolQuery boolQuery) =
1804− object [ "bool" .= boolQuery ]
1805−
1806− toJSON (QueryBoostingQuery boostingQuery) =
1807− object [ "boosting" .= boostingQuery ]
1808−
1809− toJSON (QueryCommonTermsQuery commonTermsQuery) =
1810− object [ "common" .= commonTermsQuery ]
1811−
1812− toJSON (ConstantScoreFilter csFilter boost) =
1813− object [ "constant_score" .= csFilter
1814− , "boost" .= boost]
1815−
1816− toJSON (ConstantScoreQuery query boost) =
1817− object [ "constant_score" .= query
1818− , "boost" .= boost]
1819−
1820− toJSON (QueryDisMaxQuery disMaxQuery) =
1821− object [ "dis_max" .= disMaxQuery ]
1822−
1823− toJSON (QueryFilteredQuery qFilteredQuery) =
1824− object [ "filtered" .= qFilteredQuery ]
1825−
1826− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
1827− object [ "fuzzy_like_this" .= fuzzyQuery ]
1828−
1829− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
1830− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
1831−
1832− toJSON (QueryFuzzyQuery fuzzyQuery) =
1833− object [ "fuzzy" .= fuzzyQuery ]
1834−
1835− toJSON (QueryHasChildQuery childQuery) =
1836− object [ "has_child" .= childQuery ]
1837−
1838− toJSON (QueryHasParentQuery parentQuery) =
1839− object [ "has_parent" .= parentQuery ]
1840−
1841− toJSON (QueryIndicesQuery qIndicesQuery) =
1842− object [ "indices" .= qIndicesQuery ]
1843−
1844− toJSON (MatchAllQuery boost) =
1845− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
1846−
1847− toJSON (QueryMoreLikeThisQuery query) =
1848− object [ "more_like_this" .= query ]
1849−
1850− toJSON (QueryMoreLikeThisFieldQuery query) =
1851− object [ "more_like_this_field" .= query ]
1852−
1853− toJSON (QueryNestedQuery query) =
1854− object [ "nested" .= query ]
1855−
1856− toJSON (QueryPrefixQuery query) =
1857− object [ "prefix" .= query ]
1858−
1859− toJSON (QueryRangeQuery query) =
1860− object [ "range" .= query ]
1861−
1862− toJSON (QueryRegexpQuery query) =
1863− object [ "regexp" .= query ]
1864−
1865− toJSON (QuerySimpleQueryStringQuery query) =
1866− object [ "simple_query_string" .= query ]
1867−
1868−instance FromJSON Query where
1869− parseJSON = withObject "Query" parse
1870− where parse o = termQuery `taggedWith` "term"
1871− <|> termsQuery `taggedWith` "terms"
1872− <|> idsQuery `taggedWith` "ids"
1873− <|> queryQueryStringQuery `taggedWith` "query_string"
1874− <|> queryMatchQuery `taggedWith` "match"
1875− <|> queryMultiMatchQuery o --TODO: is this a precedence issue?
1876− <|> queryBoolQuery `taggedWith` "bool"
1877− <|> queryBoostingQuery `taggedWith` "boosting"
1878− <|> queryCommonTermsQuery `taggedWith` "common"
1879− <|> constantScoreFilter o
1880− <|> constantScoreQuery o
1881− <|> queryDisMaxQuery `taggedWith` "dis_max"
1882− <|> queryFilteredQuery `taggedWith` "filtered"
1883− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
1884− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
1885− <|> queryFuzzyQuery `taggedWith` "fuzzy"
1886− <|> queryHasChildQuery `taggedWith` "has_child"
1887− <|> queryHasParentQuery `taggedWith` "has_parent"
1888− <|> queryIndicesQuery `taggedWith` "indices"
1889− <|> matchAllQuery `taggedWith` "match_all"
1890− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
1891− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
1892− <|> queryNestedQuery `taggedWith` "nested"
1893− <|> queryPrefixQuery `taggedWith` "prefix"
1894− <|> queryRangeQuery `taggedWith` "range"
1895− <|> queryRegexpQuery `taggedWith` "regexp"
1896− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
1897− where taggedWith parser k = parser =<< o .: k
1898− termQuery o = TermQuery <$> parseJSON (Object o)
1899− <*> o .:? "boost"
1900− termsQuery o = case HM.toList o of
1901− [(fn, vs)] -> do vals <- parseJSON vs
1902− case vals of
1903− x:xs -> return (TermsQuery (Term fn <$> x :| xs))
1904− _ -> fail "Expected non empty list of values"
1905− _ -> fail "Expected object with 1 field-named key"
1906− idsQuery o = IdsQuery <$> o .: "type"
1907− <*> o .: "values"
1908− queryQueryStringQuery = pure . QueryQueryStringQuery
1909− queryMatchQuery = pure . QueryMatchQuery
1910− queryMultiMatchQuery = undefined
1911− queryBoolQuery = pure . QueryBoolQuery
1912− queryBoostingQuery = pure . QueryBoostingQuery
1913− queryCommonTermsQuery = pure . QueryCommonTermsQuery
1914− constantScoreFilter o = ConstantScoreFilter <$> o .: "constant_score"
1915− <*> o .: "boost"
1916− constantScoreQuery o = ConstantScoreQuery <$> o .: "constant_score"
1917− <*> o .: "boost"
1918− queryDisMaxQuery = pure . QueryDisMaxQuery
1919− queryFilteredQuery = pure . QueryFilteredQuery
1920− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
1921− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
1922− queryFuzzyQuery = pure . QueryFuzzyQuery
1923− queryHasChildQuery = pure . QueryHasChildQuery
1924− queryHasParentQuery = pure . QueryHasParentQuery
1925− queryIndicesQuery = pure . QueryIndicesQuery
1926− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
1927− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
1928− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
1929− queryNestedQuery = pure . QueryNestedQuery
1930− queryPrefixQuery = pure . QueryPrefixQuery
1931− queryRangeQuery = pure . QueryRangeQuery
1932− queryRegexpQuery = pure . QueryRegexpQuery
1933− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
1934−
1935−
1936−omitNulls :: [(Text, Value)] -> Value
1937−omitNulls = object . filter notNull where
1938− notNull (_, Null) = False
1939− notNull (_, Array a) = (not . V.null) a
1940− notNull _ = True
1941−
1942−
1943−instance ToJSON SimpleQueryStringQuery where
1944− toJSON SimpleQueryStringQuery {..} =
1945− omitNulls (base ++ maybeAdd)
1946− where base = [ "query" .= simpleQueryStringQuery ]
1947− maybeAdd = [ "fields" .= simpleQueryStringField
1948− , "default_operator" .= simpleQueryStringOperator
1949− , "analyzer" .= simpleQueryStringAnalyzer
1950− , "flags" .= simpleQueryStringFlags
1951− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
1952− , "locale" .= simpleQueryStringLocale ]
1953−
1954−instance FromJSON SimpleQueryStringQuery where
1955− parseJSON = withObject "SimpleQueryStringQuery" parse
1956− where parse o = SimpleQueryStringQuery <$> o .: "query"
1957− <*> o .:? "fields"
1958− <*> o .:? "default_operator"
1959− <*> o .:? "analyzer"
1960− <*> o .:? "flags"
1961− <*> o .:? "lowercase_expanded_terms"
1962− <*> o .:? "locale"
1963−
1964−instance ToJSON FieldOrFields where
1965− toJSON (FofField fieldName) =
1966− toJSON fieldName
1967− toJSON (FofFields fieldNames) =
1968− toJSON fieldNames
1969−
1970−instance FromJSON FieldOrFields where
1971− parseJSON v = FofField <$> parseJSON v
1972− <|> FofFields <$> parseJSON v
1973−
1974−instance ToJSON SimpleQueryFlag where
1975− toJSON SimpleQueryAll = "ALL"
1976− toJSON SimpleQueryNone = "NONE"
1977− toJSON SimpleQueryAnd = "AND"
1978− toJSON SimpleQueryOr = "OR"
1979− toJSON SimpleQueryPrefix = "PREFIX"
1980− toJSON SimpleQueryPhrase = "PHRASE"
1981− toJSON SimpleQueryPrecedence = "PRECEDENCE"
1982− toJSON SimpleQueryEscape = "ESCAPE"
1983− toJSON SimpleQueryWhitespace = "WHITESPACE"
1984− toJSON SimpleQueryFuzzy = "FUZZY"
1985− toJSON SimpleQueryNear = "NEAR"
1986− toJSON SimpleQuerySlop = "SLOP"
1987−
1988−instance FromJSON SimpleQueryFlag where
1989− parseJSON = withText "SimpleQueryFlag" parse
1990− where parse "ALL" = pure SimpleQueryAll
1991− parse "NONE" = pure SimpleQueryNone
1992− parse "AND" = pure SimpleQueryAnd
1993− parse "OR" = pure SimpleQueryOr
1994− parse "PREFIX" = pure SimpleQueryPrefix
1995− parse "PHRASE" = pure SimpleQueryPhrase
1996− parse "PRECEDENCE" = pure SimpleQueryPrecedence
1997− parse "ESCAPE" = pure SimpleQueryEscape
1998− parse "WHITESPACE" = pure SimpleQueryWhitespace
1999− parse "FUZZY" = pure SimpleQueryFuzzy
2000− parse "NEAR" = pure SimpleQueryNear
2001− parse "SLOP" = pure SimpleQuerySlop
2002− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2003−
2004−instance ToJSON RegexpQuery where
2005− toJSON (RegexpQuery (FieldName rqQueryField)
2006− (Regexp regexpQueryQuery) rqQueryFlags
2007− rqQueryBoost) =
2008− object [ rqQueryField .= omitNulls base ]
2009− where base = [ "value" .= regexpQueryQuery
2010− , "flags" .= rqQueryFlags
2011− , "boost" .= rqQueryBoost ]
2012−
2013−instance FromJSON RegexpQuery where
2014− parseJSON = withObject "RegexpQuery" parse
2015− where parse = fieldTagged $ \fn o ->
2016− RegexpQuery fn
2017− <$> o .: "value"
2018− <*> o .: "flags"
2019− <*> o .:? "boost"
2020−
2021−instance ToJSON QueryStringQuery where
2022− toJSON (QueryStringQuery qsQueryString
2023− qsDefaultField qsOperator
2024− qsAnalyzer qsAllowWildcard
2025− qsLowercaseExpanded qsEnablePositionIncrements
2026− qsFuzzyMaxExpansions qsFuzziness
2027− qsFuzzyPrefixLength qsPhraseSlop
2028− qsBoost qsAnalyzeWildcard
2029− qsGeneratePhraseQueries qsMinimumShouldMatch
2030− qsLenient qsLocale) =
2031− omitNulls base
2032− where
2033− base = [ "query" .= qsQueryString
2034− , "default_field" .= qsDefaultField
2035− , "default_operator" .= qsOperator
2036− , "analyzer" .= qsAnalyzer
2037− , "allow_leading_wildcard" .= qsAllowWildcard
2038− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2039− , "enable_position_increments" .= qsEnablePositionIncrements
2040− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2041− , "fuzziness" .= qsFuzziness
2042− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2043− , "phrase_slop" .= qsPhraseSlop
2044− , "boost" .= qsBoost
2045− , "analyze_wildcard" .= qsAnalyzeWildcard
2046− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2047− , "minimum_should_match" .= qsMinimumShouldMatch
2048− , "lenient" .= qsLenient
2049− , "locale" .= qsLocale ]
2050−
2051−instance FromJSON QueryStringQuery where
2052− parseJSON = withObject "QueryStringQuery" parse
2053− where parse o = QueryStringQuery
2054− <$> o .: "query"
2055− <*> o .:? "default_field"
2056− <*> o .:? "default_operator"
2057− <*> o .:? "analyzer"
2058− <*> o .:? "allow_leading_wildcard"
2059− <*> o .:? "lowercase_expanded_terms"
2060− <*> o .:? "enable_position_increments"
2061− <*> o .:? "fuzzy_max_expansions"
2062− <*> o .:? "fuzziness"
2063− <*> o .:? "fuzzy_prefix_length"
2064− <*> o .:? "phrase_slop"
2065− <*> o .:? "boost"
2066− <*> o .:? "analyze_wildcard"
2067− <*> o .:? "auto_generate_phrase_queries"
2068− <*> o .:? "minimum_should_match"
2069− <*> o .:? "lenient"
2070− <*> o .:? "locale"
2071−
2072−instance ToJSON RangeQuery where
2073− toJSON (RangeQuery (FieldName fieldName) range boost) =
2074− object [ fieldName .= conjoined ]
2075− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2076−
2077−instance FromJSON RangeQuery where
2078− parseJSON = withObject "RangeQuery" parse
2079− where parse = fieldTagged $ \fn o ->
2080− RangeQuery fn
2081− <$> parseJSON (Object o)
2082− <*> o .: "boost"
2083−
2084−instance FromJSON RangeValue where
2085− parseJSON = withObject "RangeValue" parse
2086− where parse o = parseDate o
2087− <|> parseDouble o
2088− parseDate o = do lt <- o .:? "lt"
2089− lte <- o .:? "lte"
2090− gt <- o .:? "gt"
2091− gte <- o .:? "gte"
2092− case (lt, lte, gt, gte) of
2093− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD a) (LessThanD b))
2094− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD a) (LessThanD b))
2095− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD a) (LessThanEqD b))
2096− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD a) (LessThanEqD b))
2097− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2098− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2099− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2100− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2101− (Nothing, Nothing, Nothing, Nothing) -> mzero
2102− parseDouble o = do lt <- o .:? "lt"
2103− lte <- o .:? "lte"
2104− gt <- o .:? "gt"
2105− gte <- o .:? "gte"
2106− case (lt, lte, gt, gte) of
2107− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan a) (LessThan b))
2108− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq a) (LessThan b))
2109− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan a) (LessThanEq b))
2110− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq a) (LessThanEq b))
2111− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2112− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2113− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2114− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2115− (Nothing, Nothing, Nothing, Nothing) -> mzero
2116−
2117−instance ToJSON PrefixQuery where
2118− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2119− object [ fieldName .= omitNulls base ]
2120− where base = [ "value" .= queryValue
2121− , "boost" .= boost ]
2122−
2123−instance FromJSON PrefixQuery where
2124− parseJSON = withObject "PrefixQuery" parse
2125− where parse = fieldTagged $ \fn o ->
2126− PrefixQuery fn
2127− <$> o .: "value"
2128− <*> o .:? "boost"
2129−
2130−instance ToJSON NestedQuery where
2131− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2132− object [ "path" .= nqPath
2133− , "score_mode" .= nqScoreType
2134− , "query" .= nqQuery ]
2135−
2136−instance FromJSON NestedQuery where
2137− parseJSON = withObject "NestedQuery" parse
2138− where parse o = NestedQuery
2139− <$> o .: "path"
2140− <*> o .: "score_mode"
2141− <*> o .: "query"
2142−
2143−instance ToJSON MoreLikeThisFieldQuery where
2144− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2145− percent mtf mqt stopwords mindf maxdf
2146− minwl maxwl boostTerms boost analyzer) =
2147− object [ fieldName .= omitNulls base ]
2148− where base = [ "like_text" .= text
2149− , "percent_terms_to_match" .= percent
2150− , "min_term_freq" .= mtf
2151− , "max_query_terms" .= mqt
2152− , "stop_words" .= stopwords
2153− , "min_doc_freq" .= mindf
2154− , "max_doc_freq" .= maxdf
2155− , "min_word_length" .= minwl
2156− , "max_word_length" .= maxwl
2157− , "boost_terms" .= boostTerms
2158− , "boost" .= boost
2159− , "analyzer" .= analyzer ]
2160−
2161−instance FromJSON MoreLikeThisFieldQuery where
2162− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2163− where parse = fieldTagged $ \fn o ->
2164− MoreLikeThisFieldQuery
2165− <$> o .: "like_text"
2166− <*> pure fn
2167− <*> o .:? "percent_terms_to_match"
2168− <*> o .:? "min_term_freq"
2169− <*> o .:? "max_query_terms"
2170− <*> o .:? "stop_words"
2171− <*> o .:? "min_doc_freq"
2172− <*> o .:? "max_doc_freq"
2173− <*> o .:? "min_word_length"
2174− <*> o .:? "max_word_length"
2175− <*> o .:? "boost_terms"
2176− <*> o .:? "boost"
2177− <*> o .:? "analyzer"
2178−
2179−instance ToJSON MoreLikeThisQuery where
2180− toJSON (MoreLikeThisQuery text fields percent
2181− mtf mqt stopwords mindf maxdf
2182− minwl maxwl boostTerms boost analyzer) =
2183− omitNulls base
2184− where base = [ "like_text" .= text
2185− , "fields" .= fields
2186− , "percent_terms_to_match" .= percent
2187− , "min_term_freq" .= mtf
2188− , "max_query_terms" .= mqt
2189− , "stop_words" .= stopwords
2190− , "min_doc_freq" .= mindf
2191− , "max_doc_freq" .= maxdf
2192− , "min_word_length" .= minwl
2193− , "max_word_length" .= maxwl
2194− , "boost_terms" .= boostTerms
2195− , "boost" .= boost
2196− , "analyzer" .= analyzer ]
2197−
2198−instance FromJSON MoreLikeThisQuery where
2199− parseJSON = withObject "MoreLikeThisQuery" parse
2200− where parse o = MoreLikeThisQuery
2201− <$> o .: "like_text"
2202− <*> o .:? "fields"
2203− <*> o .:? "percent_terms_to_match"
2204− <*> o .:? "min_term_freq"
2205− <*> o .:? "max_query_terms"
2206− <*> o .:? "stop_words"
2207− <*> o .:? "min_doc_freq"
2208− <*> o .:? "max_doc_freq"
2209− <*> o .:? "min_word_length"
2210− <*> o .:? "max_word_length"
2211− <*> o .:? "boost_terms"
2212− <*> o .:? "boost"
2213− <*> o .:? "analyzer"
2214−
2215−instance ToJSON IndicesQuery where
2216− toJSON (IndicesQuery indices query noMatch) =
2217− omitNulls [ "indices" .= indices
2218− , "no_match_query" .= noMatch
2219− , "query" .= query ]
2220−
2221−instance FromJSON IndicesQuery where
2222− parseJSON = withObject "IndicesQuery" parse
2223− where parse o = IndicesQuery
2224− <$> o .: "indices"
2225− <*> o .: "query"
2226− <*> o .:? "no_match_query"
2227−
2228−instance ToJSON HasParentQuery where
2229− toJSON (HasParentQuery queryType query scoreType) =
2230− omitNulls [ "parent_type" .= queryType
2231− , "score_type" .= scoreType
2232− , "query" .= query ]
2233−
2234−instance FromJSON HasParentQuery where
2235− parseJSON = withObject "HasParentQuery" parse
2236− where parse o = HasParentQuery
2237− <$> o .: "parent_type"
2238− <*> o .: "query"
2239− <*> o .:? "score_type"
2240−
2241−instance ToJSON HasChildQuery where
2242− toJSON (HasChildQuery queryType query scoreType) =
2243− omitNulls [ "query" .= query
2244− , "score_type" .= scoreType
2245− , "type" .= queryType ]
2246−
2247−instance FromJSON HasChildQuery where
2248− parseJSON = withObject "HasChildQuery" parse
2249− where parse o = HasChildQuery
2250− <$> o .: "type"
2251− <*> o .: "query"
2252− <*> o .:? "score_type"
2253−
2254−instance ToJSON FuzzyQuery where
2255− toJSON (FuzzyQuery (FieldName fieldName) queryText
2256− prefixLength maxEx fuzziness boost) =
2257− object [ fieldName .= omitNulls base ]
2258− where base = [ "value" .= queryText
2259− , "fuzziness" .= fuzziness
2260− , "prefix_length" .= prefixLength
2261− , "boost" .= boost
2262− , "max_expansions" .= maxEx ]
2263−
2264−instance FromJSON FuzzyQuery where
2265− parseJSON = withObject "FuzzyQuery" parse
2266− where parse = fieldTagged $ \fn o ->
2267− FuzzyQuery fn
2268− <$> o .: "value"
2269− <*> o .: "prefix_length"
2270− <*> o .: "max_expansions"
2271− <*> o .: "fuzziness"
2272− <*> o .:? "boost"
2273−
2274−instance ToJSON FuzzyLikeFieldQuery where
2275− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2276− fieldText maxTerms ignoreFreq fuzziness prefixLength
2277− boost analyzer) =
2278− object [ fieldName .=
2279− omitNulls [ "like_text" .= fieldText
2280− , "max_query_terms" .= maxTerms
2281− , "ignore_tf" .= ignoreFreq
2282− , "fuzziness" .= fuzziness
2283− , "prefix_length" .= prefixLength
2284− , "analyzer" .= analyzer
2285− , "boost" .= boost ]]
2286−
2287−instance FromJSON FuzzyLikeFieldQuery where
2288− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2289− where parse = fieldTagged $ \fn o ->
2290− FuzzyLikeFieldQuery fn
2291− <$> o .: "like_text"
2292− <*> o .: "max_query_terms"
2293− <*> o .: "ignore_tf"
2294− <*> o .: "fuzziness"
2295− <*> o .: "prefix_length"
2296− <*> o .: "boost"
2297− <*> o .:? "analyzer"
2298−
2299−instance ToJSON FuzzyLikeThisQuery where
2300− toJSON (FuzzyLikeThisQuery fields text maxTerms
2301− ignoreFreq fuzziness prefixLength boost analyzer) =
2302− omitNulls base
2303− where base = [ "fields" .= fields
2304− , "like_text" .= text
2305− , "max_query_terms" .= maxTerms
2306− , "ignore_tf" .= ignoreFreq
2307− , "fuzziness" .= fuzziness
2308− , "prefix_length" .= prefixLength
2309− , "analyzer" .= analyzer
2310− , "boost" .= boost ]
2311−
2312−instance FromJSON FuzzyLikeThisQuery where
2313− parseJSON = withObject "FuzzyLikeThisQuery" parse
2314− where parse o = FuzzyLikeThisQuery
2315− <$> o .: "fields"
2316− <*> o .: "like_text"
2317− <*> o .: "max_query_terms"
2318− <*> o .: "ignore_tf"
2319− <*> o .: "fuzziness"
2320− <*> o .: "prefix_length"
2321− <*> o .: "boost"
2322− <*> o .:? "analyzer"
2323−
2324−instance ToJSON FilteredQuery where
2325− toJSON (FilteredQuery query fFilter) =
2326− object [ "query" .= query
2327− , "filter" .= fFilter ]
2328−
2329−instance FromJSON FilteredQuery where
2330− parseJSON = withObject "FilteredQuery" parse
2331− where parse o = FilteredQuery
2332− <$> o .: "query"
2333− <*> o .: "filter"
2334−
2335−instance ToJSON DisMaxQuery where
2336− toJSON (DisMaxQuery queries tiebreaker boost) =
2337− omitNulls base
2338− where base = [ "queries" .= queries
2339− , "boost" .= boost
2340− , "tie_breaker" .= tiebreaker ]
2341−
2342−instance FromJSON DisMaxQuery where
2343− parseJSON = withObject "DisMaxQuery" parse
2344− where parse o = DisMaxQuery
2345− <$> o .: "queries"
2346− <*> o .: "tie_breaker"
2347− <*> o .:? "boost"
2348−
2349−instance ToJSON CommonTermsQuery where
2350− toJSON (CommonTermsQuery (FieldName fieldName)
2351− (QueryString query) cf lfo hfo msm
2352− boost analyzer disableCoord) =
2353− object [fieldName .= omitNulls base ]
2354− where base = [ "query" .= query
2355− , "cutoff_frequency" .= cf
2356− , "low_freq_operator" .= lfo
2357− , "minimum_should_match" .= msm
2358− , "boost" .= boost
2359− , "analyzer" .= analyzer
2360− , "disable_coord" .= disableCoord
2361− , "high_freq_operator" .= hfo ]
2362−
2363−instance FromJSON CommonTermsQuery where
2364− parseJSON = withObject "CommonTermsQuery" parse
2365− where parse = fieldTagged $ \fn o ->
2366− CommonTermsQuery fn
2367− <$> o .: "query"
2368− <*> o .: "cutoff_frequency"
2369− <*> o .: "low_freq_operator"
2370− <*> o .: "high_freq_operator"
2371− <*> o .:? "minimum_should_match"
2372− <*> o .:? "boost"
2373− <*> o .:? "analyzer"
2374− <*> o .:? "disable_coord"
2375−
2376−instance ToJSON CommonMinimumMatch where
2377− toJSON (CommonMinimumMatch mm) = toJSON mm
2378− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2379− object [ "low_freq" .= lowF
2380− , "high_freq" .= highF ]
2381−
2382−instance FromJSON CommonMinimumMatch where
2383− parseJSON v = parseMinimum v
2384− <|> parseMinimumHighLow v
2385− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2386− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2387− MinimumMatchHighLow
2388− <$> o .: "low_freq"
2389− <*> o .: "high_freq")
2390−
2391−
2392−instance ToJSON BoostingQuery where
2393− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2394− object [ "positive" .= bqPositiveQuery
2395− , "negative" .= bqNegativeQuery
2396− , "negative_boost" .= bqNegativeBoost ]
2397−
2398−instance FromJSON BoostingQuery where
2399− parseJSON = withObject "BoostingQuery" parse
2400− where parse o = BoostingQuery
2401− <$> o .: "positive"
2402− <*> o .: "negative"
2403− <*> o .: "negative_boost"
2404−
2405−instance ToJSON BoolQuery where
2406− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2407− omitNulls base
2408− where base = [ "must" .= mustM
2409− , "must_not" .= notM
2410− , "should" .= shouldM
2411− , "minimum_should_match" .= bqMin
2412− , "boost" .= boost
2413− , "disable_coord" .= disableCoord ]
2414−
2415−instance FromJSON BoolQuery where
2416− parseJSON = withObject "BoolQuery" parse
2417− where parse o = BoolQuery
2418− <$> o .:? "must" .!= []
2419− <*> o .:? "must_not" .!= []
2420− <*> o .:? "should" .!= []
2421− <*> o .:? "minimum_should_match"
2422− <*> o .:? "boost"
2423− <*> o .:? "disable_coord"
2424−
2425−instance ToJSON MatchQuery where
2426− toJSON (MatchQuery (FieldName fieldName)
2427− (QueryString mqQueryString) booleanOperator
2428− zeroTermsQuery cutoffFrequency matchQueryType
2429− analyzer maxExpansions lenient boost) =
2430− object [ fieldName .= omitNulls base ]
2431− where base = [ "query" .= mqQueryString
2432− , "operator" .= booleanOperator
2433− , "zero_terms_query" .= zeroTermsQuery
2434− , "cutoff_frequency" .= cutoffFrequency
2435− , "type" .= matchQueryType
2436− , "analyzer" .= analyzer
2437− , "max_expansions" .= maxExpansions
2438− , "lenient" .= lenient
2439− , "boost" .= boost ]
2440−
2441−instance FromJSON MatchQuery where
2442− parseJSON = withObject "MatchQuery" parse
2443− where parse = fieldTagged $ \fn o ->
2444− MatchQuery fn
2445− <$> o .: "query"
2446− <*> o .: "operator"
2447− <*> o .: "zero_terms_query"
2448− <*> o .:? "cutoff_frequency"
2449− <*> o .:? "type"
2450− <*> o .:? "analyzer"
2451− <*> o .:? "max_expansions"
2452− <*> o .:? "lenient"
2453− <*> o .:? "boost"
2454−
2455−instance ToJSON MultiMatchQuery where
2456− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2457− ztQ tb mmqt cf analyzer maxEx lenient) =
2458− object ["multi_match" .= omitNulls base]
2459− where base = [ "fields" .= fmap toJSON fields
2460− , "query" .= query
2461− , "operator" .= boolOp
2462− , "zero_terms_query" .= ztQ
2463− , "tiebreaker" .= tb
2464− , "type" .= mmqt
2465− , "cutoff_frequency" .= cf
2466− , "analyzer" .= analyzer
2467− , "max_expansions" .= maxEx
2468− , "lenient" .= lenient ]
2469−
2470−
2471−instance ToJSON MultiMatchQueryType where
2472− toJSON MultiMatchBestFields = "best_fields"
2473− toJSON MultiMatchMostFields = "most_fields"
2474− toJSON MultiMatchCrossFields = "cross_fields"
2475− toJSON MultiMatchPhrase = "phrase"
2476− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2477−
2478−instance FromJSON MultiMatchQueryType where
2479− parseJSON = withText "MultiMatchPhrasePrefix" parse
2480− where parse "best_fields" = pure MultiMatchBestFields
2481− parse "most_fields" = pure MultiMatchMostFields
2482− parse "cross_fields" = pure MultiMatchCrossFields
2483− parse "phrase" = pure MultiMatchPhrase
2484− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2485− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2486−
2487−instance ToJSON BooleanOperator where
2488− toJSON And = String "and"
2489− toJSON Or = String "or"
2490−
2491−instance FromJSON BooleanOperator where
2492− parseJSON = withText "BooleanOperator" parse
2493− where parse "and" = pure And
2494− parse "or" = pure Or
2495− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2496−
2497−instance ToJSON ZeroTermsQuery where
2498− toJSON ZeroTermsNone = String "none"
2499− toJSON ZeroTermsAll = String "all"
2500−
2501−instance FromJSON ZeroTermsQuery where
2502− parseJSON = withText "ZeroTermsQuery" parse
2503− where parse "none" = pure ZeroTermsNone
2504− parse "all" = pure ZeroTermsAll
2505− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2506−
2507−instance ToJSON MatchQueryType where
2508− toJSON MatchPhrase = "phrase"
2509− toJSON MatchPhrasePrefix = "phrase_prefix"
2510−
2511−instance FromJSON MatchQueryType where
2512− parseJSON = withText "MatchQueryType" parse
2513− where parse "phrase" = pure MatchPhrase
2514− parse "phrase_prefix" = pure MatchPhrasePrefix
2515− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2516−
2517−instance FromJSON Status where
2518− parseJSON (Object v) = Status <$>
2519− v .:? "ok" <*>
2520− v .: "status" <*>
2521− v .: "name" <*>
2522− v .: "version" <*>
2523− v .: "tagline"
2524− parseJSON _ = empty
2525−
2526−
2527−instance ToJSON IndexSettings where
2528− toJSON (IndexSettings s r) = object ["settings" .=
2529− object ["index" .=
2530− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2531− ]
2532− ]
2533−
2534−instance ToJSON IndexTemplate where
2535− toJSON (IndexTemplate p s m) = merge
2536− (object [ "template" .= p
2537− , "mappings" .= foldl' merge (object []) m
2538− ])
2539− (toJSON s)
2540− where
2541− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
2542− merge o Null = o
2543− merge _ _ = undefined
2544−
2545−instance (FromJSON a) => FromJSON (EsResult a) where
2546− parseJSON jsonVal@(Object v) = do
2547− found <- v .:? "found" .!= False
2548− fr <- if found
2549− then parseJSON jsonVal
2550− else return Nothing
2551− EsResult <$> v .: "_index" <*>
2552− v .: "_type" <*>
2553− v .: "_id" <*>
2554− pure fr
2555− parseJSON _ = empty
2556−
2557−instance (FromJSON a) => FromJSON (EsResultFound a) where
2558− parseJSON (Object v) = EsResultFound <$>
2559− v .: "_version" <*>
2560− v .: "_source"
2561− parseJSON _ = empty
2562−
2563−instance FromJSON EsError where
2564− parseJSON (Object v) = EsError <$>
2565− v .: "status" <*>
2566− v .: "error"
2567− parseJSON _ = empty
2568−
2569−instance FromJSON IndexAliasesSummary where
2570− parseJSON = withObject "IndexAliasesSummary" parse
2571− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
2572− go ixn = withObject "index aliases" $ \ia -> do
2573− aliases <- ia .: "aliases"
2574− forM (HM.toList aliases) $ \(aName, v) -> do
2575− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
2576− IndexAliasSummary indexAlias <$> parseJSON v
2577−
2578−
2579−instance ToJSON IndexAliasAction where
2580− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
2581− where Object iaObj = toJSON ia
2582− Object optsObj = toJSON opts
2583− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
2584− where Object iaObj = toJSON ia
2585−
2586−instance ToJSON IndexAlias where
2587− toJSON IndexAlias {..} = object ["index" .= srcIndex
2588− , "alias" .= indexAlias
2589− ]
2590−
2591−instance ToJSON IndexAliasCreate where
2592− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
2593− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
2594− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
2595−
2596−instance ToJSON AliasRouting where
2597− toJSON (AllAliasRouting v) = object ["routing" .= v]
2598− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
2599− where prs = [("search_routing" .=) <$> srch
2600− ,("index_routing" .=) <$> idx]
2601−
2602−instance FromJSON AliasRouting where
2603− parseJSON = withObject "AliasRouting" parse
2604− where parse o = parseAll o <|> parseGranular o
2605− parseAll o = AllAliasRouting <$> o .: "routing"
2606− parseGranular o = GranularAliasRouting <$> o .:? "search_routing"
2607− <*> o .:? "index_routing"
2608−
2609−instance FromJSON IndexAliasCreate where
2610− parseJSON v = withObject "IndexAliasCreate" parse v
2611− where parse o = IndexAliasCreate <$> parseJSON v
2612− <*> o .:? "filter"
2613−
2614−instance ToJSON SearchAliasRouting where
2615− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
2616−
2617−instance FromJSON SearchAliasRouting where
2618− parseJSON = withText "SearchAliasRouting" parse
2619− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
2620−
2621−instance ToJSON Search where
2622− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
2623− omitNulls [ "query" .= query
2624− , "filter" .= sFilter
2625− , "sort" .= sort
2626− , "aggregations" .= searchAggs
2627− , "highlight" .= highlight
2628− , "from" .= sFrom
2629− , "size" .= sSize
2630− , "track_scores" .= sTrackSortScores
2631− , "fields" .= sFields
2632− , "_source" .= sSource]
2633−
488+ deriving (Eq, Show)
2634489
2635490instance ToJSON Source where
2636491 toJSON NoSource = toJSON False
2637492 toJSON (SourcePatterns patterns) = toJSON patterns
2638− 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)
2639497
2640498instance ToJSON PatternOrPatterns where
2641499 toJSON (PopPattern pattern) = toJSON pattern
2642500 toJSON (PopPatterns patterns) = toJSON patterns
2643501
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
504+
2644505instance ToJSON Include where
2645506 toJSON (Include patterns) = toJSON patterns
2646507
2647508instance ToJSON Exclude where
2648509 toJSON (Exclude patterns) = toJSON patterns
2649510
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
512+
2650513instance ToJSON Pattern where
2651514 toJSON (Pattern pattern) = toJSON pattern
2652515
2653−
2654−instance ToJSON FieldHighlight where
2655− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
2656− object [ fName .= fSettings ]
2657− toJSON (FieldHighlight (FieldName fName) Nothing) =
2658− object [ fName .= emptyObject ]
2659−
2660−instance ToJSON Highlights where
2661− toJSON (Highlights global fields) =
2662− omitNulls (("fields" .= fields)
2663− : highlightSettingsPairs global)
2664−
2665−instance ToJSON HighlightSettings where
2666− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
2667−
2668−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
2669−highlightSettingsPairs Nothing = []
2670−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
2671−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
2672−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
2673−
2674−
2675−plainHighPairs :: Maybe PlainHighlight -> [Pair]
2676−plainHighPairs Nothing = []
2677−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
2678− [ "type" .= String "plain"]
2679− ++ commonHighlightPairs plCom
2680− ++ nonPostingsToPairs plNonPost
2681−
2682−postHighPairs :: Maybe PostingsHighlight -> [Pair]
2683−postHighPairs Nothing = []
2684−postHighPairs (Just (PostingsHighlight pCom)) =
2685− ("type" .= String "postings")
2686− : commonHighlightPairs pCom
2687−
2688−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
2689−fastVectorHighPairs Nothing = []
2690−fastVectorHighPairs (Just
2691− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
2692− fvBoundMaxScan fvFragOff fvMatchedFields
2693− fvPhraseLim)) =
2694− [ "type" .= String "fvh"
2695− , "boundary_chars" .= fvBoundChars
2696− , "boundary_max_scan" .= fvBoundMaxScan
2697− , "fragment_offset" .= fvFragOff
2698− , "matched_fields" .= fvMatchedFields
2699− , "phraseLimit" .= fvPhraseLim]
2700− ++ commonHighlightPairs fvCom
2701− ++ nonPostingsToPairs fvNonPostSettings
2702−
2703−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
2704−commonHighlightPairs Nothing = []
2705−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
2706− chNoMatchSize chHighlightQuery
2707− chRequireFieldMatch)) =
2708− [ "order" .= chScore
2709− , "force_source" .= chForceSource
2710− , "encoder" .= chEncoder
2711− , "no_match_size" .= chNoMatchSize
2712− , "highlight_query" .= chHighlightQuery
2713− , "require_fieldMatch" .= chRequireFieldMatch]
2714− ++ highlightTagToPairs chTag
2715−
2716−
2717−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
2718−nonPostingsToPairs Nothing = []
2719−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
2720− [ "fragment_size" .= npFragSize
2721− , "number_of_fragments" .= npNumOfFrags]
2722−
2723−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
2724−parseNEJSON [] = fail "Expected non-empty list"
2725−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
2726−
2727−
2728−instance ToJSON HighlightEncoder where
2729− toJSON DefaultEncoder = String "default"
2730− toJSON HTMLEncoder = String "html"
2731−
2732−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
2733−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
2734−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
2735− , "post_tags" .= post]
2736−highlightTagToPairs Nothing = []
2737−
2738−instance ToJSON SortSpec where
2739− toJSON (DefaultSortSpec
2740− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
2741− dsSortMode dsMissingSort dsNestedFilter)) =
2742− object [dsSortFieldName .= omitNulls base] where
2743− base = [ "order" .= dsSortOrder
2744− , "ignore_unmapped" .= dsIgnoreUnmapped
2745− , "mode" .= dsSortMode
2746− , "missing" .= dsMissingSort
2747− , "nested_filter" .= dsNestedFilter ]
2748−
2749− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
2750− object [ "unit" .= units
2751− , field .= gdsLatLon
2752− , "order" .= gdsSortOrder ]
2753−
2754−
2755−instance ToJSON SortOrder where
2756− toJSON Ascending = String "asc"
2757− toJSON Descending = String "desc"
2758−
2759−
2760−instance ToJSON SortMode where
2761− toJSON SortMin = String "min"
2762− toJSON SortMax = String "max"
2763− toJSON SortSum = String "sum"
2764− toJSON SortAvg = String "avg"
2765−
2766−
2767−instance ToJSON Missing where
2768− toJSON LastMissing = String "_last"
2769− toJSON FirstMissing = String "_first"
2770− toJSON (CustomMissing txt) = String txt
2771−
2772−
2773−instance ToJSON ScoreType where
2774− toJSON ScoreTypeMax = "max"
2775− toJSON ScoreTypeAvg = "avg"
2776− toJSON ScoreTypeSum = "sum"
2777− toJSON ScoreTypeNone = "none"
2778−
2779−instance FromJSON ScoreType where
2780− parseJSON = withText "ScoreType" parse
2781− where parse "max" = pure ScoreTypeMax
2782− parse "avg" = pure ScoreTypeAvg
2783− parse "sum" = pure ScoreTypeSum
2784− parse "non" = pure ScoreTypeNone
2785− parse t = fail ("Unexpected ScoreType: " <> show t)
2786−
2787−instance ToJSON Distance where
2788− toJSON (Distance dCoefficient dUnit) =
2789− String boltedTogether where
2790− coefText = showText dCoefficient
2791− (String unitText) = toJSON dUnit
2792− boltedTogether = mappend coefText unitText
2793−
2794−instance FromJSON Distance where
2795− parseJSON = withText "Distance" parse
2796− where parse t = Distance <$> parseCoeff nT
2797− <*> parseJSON (String unitT)
2798− where (nT, unitT) = T.span isNumber t
2799− parseCoeff "" = fail "Empty string cannot be parsed as number"
2800− parseCoeff s = return (read (T.unpack s))
2801−
2802−instance ToJSON DistanceUnit where
2803− toJSON Miles = String "mi"
2804− toJSON Yards = String "yd"
2805− toJSON Feet = String "ft"
2806− toJSON Inches = String "in"
2807− toJSON Kilometers = String "km"
2808− toJSON Meters = String "m"
2809− toJSON Centimeters = String "cm"
2810− toJSON Millimeters = String "mm"
2811− toJSON NauticalMiles = String "nmi"
2812−
2813−
2814−instance FromJSON DistanceUnit where
2815− parseJSON = withText "DistanceUnit" parse
2816− where parse "mi" = pure Miles
2817− parse "yd" = pure Yards
2818− parse "ft" = pure Feet
2819− parse "in" = pure Inches
2820− parse "km" = pure Kilometers
2821− parse "m" = pure Meters
2822− parse "cm" = pure Centimeters
2823− parse "mm" = pure Millimeters
2824− parse "nmi" = pure NauticalMiles
2825− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
2826−
2827−instance ToJSON DistanceType where
2828− toJSON Arc = String "arc"
2829− toJSON SloppyArc = String "sloppy_arc"
2830− toJSON Plane = String "plane"
2831−
2832−instance FromJSON DistanceType where
2833− parseJSON = withText "DistanceType" parse
2834− where parse "arc" = pure Arc
2835− parse "sloppy_arc" = pure SloppyArc
2836− parse "plane" = pure Plane
2837− parse t = fail ("Unrecognized DistanceType: " <> show t)
2838−
2839−
2840−instance ToJSON OptimizeBbox where
2841− toJSON NoOptimizeBbox = String "none"
2842− toJSON (OptimizeGeoFilterType gft) = toJSON gft
2843−
2844−instance FromJSON OptimizeBbox where
2845− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
2846− <|> parseOptimize v
2847− where parseNoOptimize "none" = pure NoOptimizeBbox
2848− parseNoOptimize _ = mzero
2849− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
2850−
2851−instance ToJSON GeoBoundingBoxConstraint where
2852− toJSON (GeoBoundingBoxConstraint
2853− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
2854− object [gbbcGeoBBField .= gbbcConstraintBox
2855− , "_cache" .= cache
2856− , "type" .= type']
2857−
2858−instance FromJSON GeoBoundingBoxConstraint where
2859− parseJSON = withObject "GeoBoundingBoxConstraint" parse
2860− where parse o = flip fieldTagged o $ \fn o' ->
2861− GeoBoundingBoxConstraint fn
2862− <$> parseJSON (Object o')
2863− <*> o .:? "cache" .!= defaultCache
2864− <*> o .: "type"
2865−
2866−instance ToJSON GeoFilterType where
2867− toJSON GeoFilterMemory = String "memory"
2868− toJSON GeoFilterIndexed = String "indexed"
2869−
2870−instance FromJSON GeoFilterType where
2871− parseJSON = withText "GeoFilterType" parse
2872− where parse "memory" = pure GeoFilterMemory
2873− parse "indexed" = pure GeoFilterIndexed
2874− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
2875−
2876−instance ToJSON GeoBoundingBox where
2877− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
2878− object ["top_left" .= gbbTopLeft
2879− , "bottom_right" .= gbbBottomRight]
2880−
2881−instance FromJSON GeoBoundingBox where
2882− parseJSON = withObject "GeoBoundingBox" parse
2883− where parse o = GeoBoundingBox
2884− <$> o .: "top_left"
2885− <*> o .: "bottom_right"
2886−
2887−instance ToJSON LatLon where
2888− toJSON (LatLon lLat lLon) =
2889− object ["lat" .= lLat
2890− , "lon" .= lLon]
2891−
2892−instance FromJSON LatLon where
2893− parseJSON = withObject "LatLon" parse
2894− where parse o = LatLon <$> o .: "lat"
2895− <*> o .: "lon"
2896−
2897−-- index for smaller ranges, fielddata for longer ranges
2898−instance ToJSON RangeExecution where
2899− toJSON RangeExecutionIndex = "index"
2900− toJSON RangeExecutionFielddata = "fielddata"
2901−
2902−
2903−instance FromJSON RangeExecution where
2904− parseJSON = withText "RangeExecution" parse
2905− where parse "index" = pure RangeExecutionIndex
2906− parse "fielddata" = pure RangeExecutionFielddata
2907− parse t = error ("Unrecognized RangeExecution " <> show t)
2908−
2909−instance ToJSON RegexpFlags where
2910− toJSON AllRegexpFlags = String "ALL"
2911− toJSON NoRegexpFlags = String "NONE"
2912− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
2913− where flagStrs = map flagStr . nub $ h:fs
2914− flagStr AnyString = "ANYSTRING"
2915− flagStr Automaton = "AUTOMATON"
2916− flagStr Complement = "COMPLEMENT"
2917− flagStr Empty = "EMPTY"
2918− flagStr Intersection = "INTERSECTION"
2919− flagStr Interval = "INTERVAL"
2920−
2921−instance FromJSON RegexpFlags where
2922− parseJSON = withText "RegexpFlags" parse
2923− where parse "ALL" = pure AllRegexpFlags
2924− parse "NONE" = pure NoRegexpFlags
2925− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
2926−
2927−instance FromJSON RegexpFlag where
2928− parseJSON = withText "RegexpFlag" parse
2929− where parse "ANYSTRING" = pure AnyString
2930− parse "AUTOMATON" = pure Automaton
2931− parse "COMPLEMENT" = pure Complement
2932− parse "EMPTY" = pure Empty
2933− parse "INTERSECTION" = pure Intersection
2934− parse "INTERVAL" = pure Interval
2935− parse f = fail ("Unknown RegexpFlag: " <> show f)
2936−
2937−instance ToJSON Term where
2938− toJSON (Term field value) = object ["term" .= object
2939− [field .= value]]
2940−
2941−instance FromJSON Term where
2942− parseJSON = withObject "Term" parse
2943− where parse o = do termObj <- o .: "term"
2944− case HM.toList termObj of
2945− [(fn, v)] -> Term fn <$> parseJSON v
2946− _ -> fail "Expected object with 1 field-named key"
2947−
2948−instance ToJSON BoolMatch where
2949− toJSON (MustMatch term cache) = object ["must" .= term,
2950− "_cache" .= cache]
2951− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
2952− "_cache" .= cache]
2953− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
2954− "_cache" .= cache]
2955−
2956−instance FromJSON BoolMatch where
2957− parseJSON = withObject "BoolMatch" parse
2958− where parse o = mustMatch `taggedWith` "must"
2959− <|> mustNotMatch `taggedWith` "must_not"
2960− <|> shouldMatch `taggedWith` "should"
2961− where taggedWith parser k = parser =<< o .: k
2962− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
2963− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
2964− 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)
2965528
2966529instance (FromJSON a) => FromJSON (SearchResult a) where
2967530 parseJSON (Object v) = SearchResult <$>
@@ -2970,52 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
2970533 v .: "_shards" <*>
2971534 v .: "hits" <*>
2972535 v .:? "aggregations" <*>
2973− v .:? "_scroll_id"
2974− parseJSON _ = empty
2975−
2976−instance (FromJSON a) => FromJSON (SearchHits a) where
2977− parseJSON (Object v) = SearchHits <$>
2978− v .: "total" <*>
2979− v .: "max_score" <*>
2980− v .: "hits"
536+ v .:? "_scroll_id" <*>
537+ v .:? "suggest"
2981538 parseJSON _ = empty
2982539
2983−instance (FromJSON a) => FromJSON (Hit a) where
2984− parseJSON (Object v) = Hit <$>
2985− v .: "_index" <*>
2986− v .: "_type" <*>
2987− v .: "_id" <*>
2988− v .: "_score" <*>
2989− v .:? "_source" <*>
2990− v .:? "highlight"
2991− parseJSON _ = empty
2992−
2993−instance FromJSON ShardResult where
2994− parseJSON (Object v) = ShardResult <$>
2995− v .: "total" <*>
2996− v .: "successful" <*>
2997− v .: "failed"
2998− parseJSON _ = empty
2999−
3000−
3001−instance FromJSON DocVersion where
3002− parseJSON v = do
3003− i <- parseJSON v
3004− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3005−
3006−instance Bounded DocVersion where
3007− minBound = DocVersion 1
3008− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3009−
3010−instance Enum DocVersion where
3011− succ x
3012− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3013− | otherwise = succError "DocVersion"
3014− pred x
3015− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3016− | otherwise = predError "DocVersion"
3017− toEnum i =
3018− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3019− fromEnum = docVersionNumber
3020− enumFrom = boundedEnumFrom
3021− enumFromThen = boundedEnumFromThen
540+newtype ScrollId =
541+ ScrollId Text
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)