@@ -1,10 +1,8 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveGeneric #-}
31{-# LANGUAGE FlexibleContexts #-}
42{-# LANGUAGE FlexibleInstances #-}
53{-# LANGUAGE GeneralizedNewtypeDeriving #-}
64{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE NoMonomorphismRestriction #-}
5+{-# LANGUAGE NamedFieldPuns #-}
86{-# LANGUAGE OverloadedStrings #-}
97{-# LANGUAGE RecordWildCards #-}
108{-# LANGUAGE UndecidableInstances #-}
@@ -12,11 +10,11 @@
1210-------------------------------------------------------------------------------
1311-- |
1412-- Module : Database.Bloodhound.Types
15−-- Copyright : (C) 2014 Chris Allen
13+-- Copyright : (C) 2014, 2018 Chris Allen
1614-- License : BSD-style (see the file LICENSE)
1715-- Maintainer : Chris Allen <cma@bitemyapp.com
1816-- Stability : provisional
19−-- Portability : DeriveGeneric, RecordWildCards
17+-- Portability : RecordWildCards
2018--
2119-- Data types for describing actions and data structures performed to interact
2220-- with Elasticsearch. The two main buckets your queries against Elasticsearch
@@ -44,10 +42,15 @@ module Database.Bloodhound.Types
4442 , mkTermsAggregation
4543 , mkTermsScriptAggregation
4644 , mkDateHistogram
45+ , mkCardinalityAggregation
4746 , mkDocVersion
47+ , mkStatsAggregation
48+ , mkExtendedStatsAggregation
4849 , docVersionNumber
50+ , toMissing
4951 , toTerms
5052 , toDateHistogram
53+ , toTopHits
5154 , omitNulls
5255 , BH(..)
5356 , runBH
@@ -58,6 +61,9 @@ module Database.Bloodhound.Types
5861 , mkBHEnv
5962 , MonadBH(..)
6063 , Version(..)
64+ , VersionNumber(..)
65+ , MaybeNA(..)
66+ , BuildHash(..)
6167 , Status(..)
6268 , Existence(..)
6369 , NullValue(..)
@@ -65,8 +71,12 @@ module Database.Bloodhound.Types
6571 , UpdatableIndexSetting(..)
6672 , IndexSettingsSummary(..)
6773 , AllocationPolicy(..)
74+ , Compression(..)
6875 , ReplicaBounds(..)
6976 , Bytes(..)
77+ , gigabytes
78+ , megabytes
79+ , kilobytes
7080 , FSType(..)
7181 , InitialShardCount(..)
7282 , NodeAttrFilter(..)
@@ -110,8 +120,8 @@ module Database.Bloodhound.Types
110120 , Pattern(..)
111121 , ShardResult(..)
112122 , Hit(..)
123+ , HitFields(..)
113124 , Filter(..)
114− , Seminearring(..)
115125 , BoolMatch(..)
116126 , Term(..)
117127 , GeoPoint(..)
@@ -138,8 +148,22 @@ module Database.Bloodhound.Types
138148 , RegexpFlags(..)
139149 , RegexpFlag(..)
140150 , FieldName(..)
151+ , ScriptFields(..)
152+ , ScriptFieldName
153+ , ScriptFieldValue
141154 , Script(..)
155+ , ScriptLanguage(..)
156+ , ScriptInline(..)
157+ , ScriptId(..)
158+ , ScriptParams(..)
159+ , ScriptParamName
160+ , ScriptParamValue
142161 , IndexName(..)
162+ , IndexSelection(..)
163+ , NodeSelection(..)
164+ , NodeSelector(..)
165+ , ForceMergeIndexSettings(..)
166+ , defaultForceMergeIndexSettings
143167 , TemplateName(..)
144168 , TemplatePattern(..)
145169 , MappingName(..)
@@ -163,8 +187,19 @@ module Database.Bloodhound.Types
163187 , BoolQuery(..)
164188 , BoostingQuery(..)
165189 , 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(..)
166202 , DisMaxQuery(..)
167− , FilteredQuery(..)
168203 , FuzzyLikeThisQuery(..)
169204 , FuzzyLikeFieldQuery(..)
170205 , FuzzyQuery(..)
@@ -180,10 +215,16 @@ module Database.Bloodhound.Types
180215 , RangeQuery(..)
181216 , RegexpQuery(..)
182217 , QueryString(..)
218+ , TemplateQueryInline(..)
219+ , TemplateQueryKeyValuePairs(..)
220+ , WildcardQuery(..)
183221 , BooleanOperator(..)
184222 , ZeroTermsQuery(..)
185223 , CutoffFrequency(..)
186224 , Analyzer(..)
225+ , Tokenizer(..)
226+ , TokenFilter(..)
227+ , CharFilter(..)
187228 , MaxExpansions(..)
188229 , Lenient(..)
189230 , MatchQueryType(..)
@@ -230,16 +271,108 @@ module Database.Bloodhound.Types
230271 , CollectionMode(..)
231272 , TermOrder(..)
232273 , 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 (..)
233363
234364 , Aggregation(..)
235365 , Aggregations
236366 , AggregationResults
367+ , BucketValue(..)
237368 , Bucket(..)
238369 , BucketAggregation(..)
239370 , TermsAggregation(..)
240371 , MissingAggregation(..)
241372 , ValueCountAggregation(..)
242373 , FilterAggregation(..)
374+ , CardinalityAggregation(..)
375+ , MaxAggregation(..)
243376 , DateHistogramAggregation(..)
244377 , DateRangeAggregation(..)
245378 , DateRangeAggRange(..)
@@ -247,6 +380,9 @@ module Database.Bloodhound.Types
247380 , DateMathAnchor(..)
248381 , DateMathModifier(..)
249382 , DateMathUnit(..)
383+ , TopHitsAggregation(..)
384+ , StatisticsAggregation(..)
385+ , SearchAfterKey
250386
251387 , Highlights(..)
252388 , FieldHighlight(..)
@@ -260,646 +396,36 @@ module Database.Bloodhound.Types
260396 , HighlightTag(..)
261397 , HitHighlight
262398
399+ , MissingResult(..)
263400 , TermsResult(..)
264401 , DateHistogramResult(..)
265402 , DateRangeResult(..)
403+ , TopHitResult(..)
266404
267405 , EsUsername(..)
268406 , EsPassword(..)
269− ) where
270407
271−import Control.Applicative
272−import Control.Monad.Catch
273−import Control.Monad.Except
274−import Control.Monad.Reader
275−import Control.Monad.State
276−import Control.Monad.Writer
277−import Data.Aeson
278−import Data.Aeson.Types (Pair, Parser, emptyObject,
279− parseMaybe)
280−import qualified Data.ByteString.Lazy.Char8 as L
281−import Data.Char
282−import Data.Hashable (Hashable)
283−import qualified Data.HashMap.Strict as HM
284−import Data.List (foldl', nub)
285−import Data.List.NonEmpty (NonEmpty (..), toList)
286−import qualified Data.Map.Strict as M
287−import Data.Maybe
288−import Data.Text (Text)
289−import qualified Data.Text as T
290−import Data.Time.Calendar
291−import Data.Time.Clock (NominalDiffTime, UTCTime)
292−import Data.Time.Clock.POSIX
293−import qualified Data.Traversable as DT
294−import Data.Typeable (Typeable)
295−import qualified Data.Vector as V
296−import GHC.Enum
297−import GHC.Generics (Generic)
298−import Network.HTTP.Client
299−import qualified Network.HTTP.Types.Method as NHTM
300−
301−import Database.Bloodhound.Types.Class
302−import Database.Bloodhound.Types.Internal
303−
304−-- $setup
305−-- >>> :set -XOverloadedStrings
306−-- >>> import Database.Bloodhound
307−-- >>> let testServer = (Server "http://localhost:9200")
308−-- >>> let testIndex = IndexName "twitter"
309−-- >>> let testMapping = MappingName "tweet"
310−-- >>> let defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
311−
312−-- defaultIndexSettings is exported by Database.Bloodhound as well
313−-- no trailing slashes in servers, library handles building the path.
314−
315−-- | Create a 'BHEnv' with all optional fields defaulted. HTTP hook
316−-- will be a noop. You can use the exported fields to customize it further, e.g.:
317−--
318−-- >> (mkBHEnv myServer myManager) { bhRequestHook = customHook }
319−mkBHEnv :: Server -> Manager -> BHEnv
320−mkBHEnv s m = BHEnv s m return
321−
322−newtype BH m a = BH {
323− unBH :: ReaderT BHEnv m a
324− } deriving ( Functor
325− , Applicative
326− , Monad
327− , MonadIO
328− , MonadState s
329− , MonadWriter w
330− , MonadError e
331− , Alternative
332− , MonadPlus
333− , MonadFix
334− , MonadThrow
335− , MonadCatch
336− , MonadMask)
337−
338−instance MonadTrans BH where
339− lift = BH . lift
340−
341−instance (MonadReader r m) => MonadReader r (BH m) where
342− ask = lift ask
343− local f (BH (ReaderT m)) = BH $ ReaderT $ \r ->
344− local f (m r)
345−
346−instance (Functor m, Applicative m, MonadIO m) => MonadBH (BH m) where
347− getBHEnv = BH getBHEnv
348−
349−runBH :: BHEnv -> BH m a -> m a
350−runBH e f = runReaderT (unBH f) e
351−
352−{-| 'Version' is embedded in 'Status' -}
353−data Version = Version { number :: Text
354− , build_hash :: Text
355− , build_timestamp :: UTCTime
356− , build_snapshot :: Bool
357− , lucene_version :: Text } deriving (Eq, Show, Generic, Typeable)
358−
359−{-| 'Status' is a data type for describing the JSON body returned by
360− Elasticsearch when you query its status. This was deprecated in 1.2.0.
361−
362− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-status.html#indices-status>
363−-}
364−
365−data Status = Status { ok :: Maybe Bool
366− , status :: Int
367− , name :: Text
368− , version :: Version
369− , tagline :: Text } deriving (Eq, Show, Generic)
370−
371−{-| 'IndexSettings' is used to configure the shards and replicas when you create
372− an Elasticsearch Index.
373−
374− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
375−-}
376−
377−data IndexSettings =
378− IndexSettings { indexShards :: ShardCount
379− , indexReplicas :: ReplicaCount } deriving (Eq, Show, Generic, Typeable)
380−
381−{-| 'defaultIndexSettings' is an 'IndexSettings' with 3 shards and 2 replicas. -}
382−defaultIndexSettings :: IndexSettings
383−defaultIndexSettings = IndexSettings (ShardCount 3) (ReplicaCount 2)
384−
385−{-| 'UpdatableIndexSetting' are settings which may be updated after an index is created.
386−
387− <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html>
388−-}
389−data UpdatableIndexSetting = NumberOfReplicas ReplicaCount
390− -- ^ The number of replicas each shard has.
391− | AutoExpandReplicas ReplicaBounds
392− | BlocksReadOnly Bool
393− -- ^ Set to True to have the index read only. False to allow writes and metadata changes.
394− | BlocksRead Bool
395− -- ^ Set to True to disable read operations against the index.
396− | BlocksWrite Bool
397− -- ^ Set to True to disable write operations against the index.
398− | BlocksMetaData Bool
399− -- ^ Set to True to disable metadata operations against the index.
400− | RefreshInterval NominalDiffTime
401− -- ^ The async refresh interval of a shard
402− | IndexConcurrency Int
403− | FailOnMergeFailure Bool
404− | TranslogFlushThresholdOps Int
405− -- ^ When to flush on operations.
406− | TranslogFlushThresholdSize Bytes
407− -- ^ When to flush based on translog (bytes) size.
408− | TranslogFlushThresholdPeriod NominalDiffTime
409− -- ^ When to flush based on a period of not flushing.
410− | TranslogDisableFlush Bool
411− -- ^ Disables flushing. Note, should be set for a short interval and then enabled.
412− | CacheFilterMaxSize (Maybe Bytes)
413− -- ^ The maximum size of filter cache (per segment in shard).
414− | CacheFilterExpire (Maybe NominalDiffTime)
415− -- ^ The expire after access time for filter cache.
416− | GatewaySnapshotInterval NominalDiffTime
417− -- ^ The gateway snapshot interval (only applies to shared gateways).
418− | RoutingAllocationInclude (NonEmpty NodeAttrFilter)
419− -- ^ A node matching any rule will be allowed to host shards from the index.
420− | RoutingAllocationExclude (NonEmpty NodeAttrFilter)
421− -- ^ A node matching any rule will NOT be allowed to host shards from the index.
422− | RoutingAllocationRequire (NonEmpty NodeAttrFilter)
423− -- ^ Only nodes matching all rules will be allowed to host shards from the index.
424− | RoutingAllocationEnable AllocationPolicy
425− -- ^ Enables shard allocation for a specific index.
426− | RoutingAllocationShardsPerNode ShardCount
427− -- ^ Controls the total number of shards (replicas and primaries) allowed to be allocated on a single node.
428− | RecoveryInitialShards InitialShardCount
429− -- ^ When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster.
430− | GCDeletes NominalDiffTime
431− | TTLDisablePurge Bool
432− -- ^ Disables temporarily the purge of expired docs.
433− | TranslogFSType FSType
434− | IndexCompoundFormat CompoundFormat
435− | IndexCompoundOnFlush Bool
436− | WarmerEnabled Bool
437− deriving (Eq, Show, Generic, Typeable)
438−
439−data AllocationPolicy = AllocAll
440− -- ^ Allows shard allocation for all shards.
441− | AllocPrimaries
442− -- ^ Allows shard allocation only for primary shards.
443− | AllocNewPrimaries
444− -- ^ Allows shard allocation only for primary shards for new indices.
445− | AllocNone
446− -- ^ No shard allocation is allowed
447− deriving (Eq, Show, Generic, Typeable)
448−
449−data ReplicaBounds = ReplicasBounded Int Int
450− | ReplicasLowerBounded Int
451− | ReplicasUnbounded
452− deriving (Eq, Show, Generic, Typeable)
453−
454−newtype Bytes = Bytes Int deriving (Eq, Show, Generic, Typeable, Ord, ToJSON, FromJSON)
455−
456−data FSType = FSSimple
457− | FSBuffered deriving (Eq, Show, Generic, Typeable, Ord)
458−
459−data InitialShardCount = QuorumShards
460− | QuorumMinus1Shards
461− | FullShards
462− | FullMinus1Shards
463− | ExplicitShards Int
464− deriving (Eq, Show, Generic, Typeable)
465−
466−data NodeAttrFilter = NodeAttrFilter { nodeAttrFilterName :: NodeAttrName
467− , nodeAttrFilterValues :: NonEmpty Text}
468− deriving (Eq, Show, Generic, Ord)
469−
470−newtype NodeAttrName = NodeAttrName Text deriving (Eq, Show, Ord, Generic, Typeable)
471−
472−data CompoundFormat = CompoundFileFormat Bool
473− | MergeSegmentVsTotalIndex Double
474− -- ^ percentage between 0 and 1 where 0 is false, 1 is true
475− deriving (Eq, Show, Generic, Typeable)
476−
477−newtype NominalDiffTimeJSON = NominalDiffTimeJSON { ndtJSON :: NominalDiffTime }
478−
479−data IndexSettingsSummary = IndexSettingsSummary { sSummaryIndexName :: IndexName
480− , sSummaryFixedSettings :: IndexSettings
481− , sSummaryUpdateable :: [UpdatableIndexSetting]}
482− deriving (Eq, Show, Generic, Typeable)
483−
484−{-| 'Reply' and 'Method' are type synonyms from 'Network.HTTP.Types.Method.Method' -}
485−type Reply = Network.HTTP.Client.Response L.ByteString
486−type Method = NHTM.Method
487−
488−{-| 'OpenCloseIndex' is a sum type for opening and closing indices.
489−
490− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
491−-}
492−data OpenCloseIndex = OpenIndex | CloseIndex deriving (Eq, Show, Generic, Typeable)
493−
494−data FieldType = GeoPointType
495− | GeoShapeType
496− | FloatType
497− | IntegerType
498− | LongType
499− | ShortType
500− | ByteType deriving (Eq, Show, Generic, Typeable)
501−
502−data FieldDefinition =
503− FieldDefinition { fieldType :: FieldType } deriving (Eq, Show, Generic, Typeable)
504−
505−{-| An 'IndexTemplate' defines a template that will automatically be
506− applied to new indices created. The templates include both
507− 'IndexSettings' and mappings, and a simple 'TemplatePattern' that
508− controls if the template will be applied to the index created.
509− Specify mappings as follows: @[toJSON TweetMapping, ...]@
510−
511− https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html
512−-}
513−data IndexTemplate =
514− IndexTemplate { templatePattern :: TemplatePattern
515− , templateSettings :: Maybe IndexSettings
516− , templateMappings :: [Value]
517− }
518−
519−data MappingField =
520− MappingField { mappingFieldName :: FieldName
521− , fieldDefinition :: FieldDefinition } deriving (Eq, Show, Generic, Typeable)
522−
523−{-| Support for type reification of 'Mapping's is currently incomplete, for
524− now the mapping API verbiage expects a 'ToJSON'able blob.
525−
526− Indexes have mappings, mappings are schemas for the documents contained in the
527− index. I'd recommend having only one mapping per index, always having a mapping,
528− and keeping different kinds of documents separated if possible.
529−-}
530−data Mapping = Mapping { typeName :: TypeName
531− , mappingFields :: [MappingField] } deriving (Eq, Show, Generic, Typeable)
532−
533−{-| 'BulkOperation' is a sum type for expressing the four kinds of bulk
534− operation index, create, delete, and update. 'BulkIndex' behaves like an
535− "upsert", 'BulkCreate' will fail if a document already exists at the DocId.
536−
537− <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk>
538−-}
539−data BulkOperation =
540− BulkIndex IndexName MappingName DocId Value
541− | BulkCreate IndexName MappingName DocId Value
542− | BulkDelete IndexName MappingName DocId
543− | BulkUpdate IndexName MappingName DocId Value deriving (Eq, Show, Generic, Typeable)
544−
545−{-| 'EsResult' describes the standard wrapper JSON document that you see in
546− successful Elasticsearch lookups or lookups that couldn't find the document.
547−-}
548−data EsResult a = EsResult { _index :: Text
549− , _type :: Text
550− , _id :: Text
551− , foundResult :: Maybe (EsResultFound a)} deriving (Eq, Show, Generic, Typeable)
552−
553−{-| 'EsResultFound' contains the document and its metadata inside of an
554− 'EsResult' when the document was successfully found.
555−-}
556−data EsResultFound a = EsResultFound { _version :: DocVersion
557− , _source :: a } deriving (Eq, Show, Generic, Typeable)
558−
559−{-| 'EsError' is the generic type that will be returned when there was a
560− problem. If you can't parse the expected response, its a good idea to
561− try parsing this.
562−-}
563−data EsError = EsError { errorStatus :: Int
564− , errorMessage :: Text } deriving (Eq, Show, Generic, Typeable)
565−
566−{-| 'EsProtocolException' will be thrown if Bloodhound cannot parse a response
567−returned by the ElasticSearch server. If you encounter this error, please
568−verify that your domain data types and FromJSON instances are working properly
569−(for example, the 'a' of '[Hit a]' in 'SearchResult.searchHits.hits'). If you're
570−sure that your mappings are correct, then this error may be an indication of an
571−incompatibility between Bloodhound and ElasticSearch. Please open a bug report
572−and be sure to include the exception body.
573−-}
574−data EsProtocolException = EsProtocolException { esProtoExBody :: L.ByteString }
575− deriving (Eq, Show, Generic, Typeable)
576−
577−instance Exception EsProtocolException
578−
579−data IndexAlias = IndexAlias { srcIndex :: IndexName
580− , indexAlias :: IndexAliasName } deriving (Eq, Show, Generic, Typeable)
581−
582−newtype IndexAliasName = IndexAliasName { indexAliasName :: IndexName } deriving (Eq, Show, Generic, ToJSON)
583−
584−data IndexAliasAction = AddAlias IndexAlias IndexAliasCreate
585− | RemoveAlias IndexAlias deriving (Show, Eq, Generic, Typeable)
586−
587−data IndexAliasCreate = IndexAliasCreate { aliasCreateRouting :: Maybe AliasRouting
588− , aliasCreateFilter :: Maybe Filter}
589− deriving (Show, Eq, Generic, Typeable)
590−
591−data AliasRouting = AllAliasRouting RoutingValue
592− | GranularAliasRouting (Maybe SearchAliasRouting) (Maybe IndexAliasRouting)
593− deriving (Show, Eq, Generic, Typeable)
594−
595−newtype SearchAliasRouting = SearchAliasRouting (NonEmpty RoutingValue) deriving (Show, Eq, Generic, Typeable)
596−
597−newtype IndexAliasRouting = IndexAliasRouting RoutingValue deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
598−
599−newtype RoutingValue = RoutingValue { routingValue :: Text } deriving (Show, Eq, Generic, ToJSON, FromJSON, Typeable)
600−
601−newtype IndexAliasesSummary = IndexAliasesSummary { indexAliasesSummary :: [IndexAliasSummary] } deriving (Show, Eq, Generic, Typeable)
602−
603−{-| 'IndexAliasSummary' is a summary of an index alias configured for a server. -}
604−data IndexAliasSummary = IndexAliasSummary { indexAliasSummaryAlias :: IndexAlias
605− , indexAliasSummaryCreate :: IndexAliasCreate} deriving (Show, Eq, Generic, Typeable)
606−
607−{-| 'DocVersion' is an integer version number for a document between 1
608−and 9.2e+18 used for <<https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html optimistic concurrency control>>.
609−-}
610−newtype DocVersion = DocVersion {
611− docVersionNumber :: Int
612− } deriving (Eq, Show, Generic, Ord, ToJSON)
613−
614−-- | Smart constructor for in-range doc version
615−mkDocVersion :: Int -> Maybe DocVersion
616−mkDocVersion i
617− | i >= (docVersionNumber minBound) && i <= (docVersionNumber maxBound) =
618− Just $ DocVersion i
619− | otherwise = Nothing
620−
621−
622−{-| 'ExternalDocVersion' is a convenience wrapper if your code uses its
623−own version numbers instead of ones from ES.
624−-}
625−newtype ExternalDocVersion = ExternalDocVersion DocVersion
626− deriving (Eq, Show, Generic, Ord, Bounded, Enum, ToJSON)
627−
628−{-| 'VersionControl' is specified when indexing documents as a
629−optimistic concurrency control.
630−-}
631−data VersionControl = NoVersionControl
632− -- ^ Don't send a version. This is a pure overwrite.
633− | InternalVersion DocVersion
634− -- ^ Use the default ES versioning scheme. Only
635− -- index the document if the version is the same
636− -- as the one specified. Only applicable to
637− -- updates, as you should be getting Version from
638− -- a search result.
639− | ExternalGT ExternalDocVersion
640− -- ^ Use your own version numbering. Only index
641− -- the document if the version is strictly higher
642− -- OR the document doesn't exist. The given
643− -- version will be used as the new version number
644− -- for the stored document. N.B. All updates must
645− -- increment this number, meaning there is some
646− -- global, external ordering of updates.
647− | ExternalGTE ExternalDocVersion
648− -- ^ Use your own version numbering. Only index
649− -- the document if the version is equal or higher
650− -- than the stored version. Will succeed if there
651− -- is no existing document. The given version will
652− -- be used as the new version number for the
653− -- stored document. Use with care, as this could
654− -- result in data loss.
655− | ForceVersion ExternalDocVersion
656− -- ^ The document will always be indexed and the
657− -- given version will be the new version. This is
658− -- typically used for correcting errors. Use with
659− -- care, as this could result in data loss.
660− deriving (Show, Eq, Generic, Ord)
661−
662−{-| 'DocumentParent' is used to specify a parent document.
663−-}
664−newtype DocumentParent = DocumentParent DocId
665− deriving (Eq, Show, Generic, Typeable)
666−
667−{-| 'IndexDocumentSettings' are special settings supplied when indexing
668−a document. For the best backwards compatiblity when new fields are
669−added, you should probably prefer to start with 'defaultIndexDocumentSettings'
670−-}
671−data IndexDocumentSettings =
672− IndexDocumentSettings { idsVersionControl :: VersionControl
673− , idsParent :: Maybe DocumentParent
674− } deriving (Eq, Show, Generic, Typeable)
675−
676−{-| Reasonable default settings. Chooses no version control and no parent.
677−-}
678−defaultIndexDocumentSettings :: IndexDocumentSettings
679−defaultIndexDocumentSettings = IndexDocumentSettings NoVersionControl Nothing
680−
681−{-| 'Sort' is a synonym for a list of 'SortSpec's. Sort behavior is order
682− dependent with later sorts acting as tie-breakers for earlier sorts.
683−-}
684−type Sort = [SortSpec]
685−
686−{-| The two main kinds of 'SortSpec' are 'DefaultSortSpec' and
687− 'GeoDistanceSortSpec'. The latter takes a 'SortOrder', 'GeoPoint', and
688− 'DistanceUnit' to express "nearness" to a single geographical point as a
689− sort specification.
690−
691−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
692−-}
693−data SortSpec = DefaultSortSpec DefaultSort
694− | GeoDistanceSortSpec SortOrder GeoPoint DistanceUnit deriving (Eq, Show, Generic, Typeable)
695−
696−{-| 'DefaultSort' is usually the kind of 'SortSpec' you'll want. There's a
697− 'mkSort' convenience function for when you want to specify only the most
698− common parameters.
699−
700−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
701−-}
702−data DefaultSort =
703− DefaultSort { sortFieldName :: FieldName
704− , sortOrder :: SortOrder
705− -- default False
706− , ignoreUnmapped :: Bool
707− , sortMode :: Maybe SortMode
708− , missingSort :: Maybe Missing
709− , nestedFilter :: Maybe Filter } deriving (Eq, Show, Generic, Typeable)
710−
711−{-| 'SortOrder' is 'Ascending' or 'Descending', as you might expect. These get
712− encoded into "asc" or "desc" when turned into JSON.
713−
714−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort>
715−-}
716−data SortOrder = Ascending
717− | Descending deriving (Eq, Show, Generic, Typeable)
718−
719−{-| 'Missing' prescribes how to handle missing fields. A missing field can be
720− sorted last, first, or using a custom value as a substitute.
721−
722−<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values>
723−-}
724−data Missing = LastMissing
725− | FirstMissing
726− | CustomMissing Text deriving (Eq, Show, Generic, Typeable)
727−
728−{-| 'SortMode' prescribes how to handle sorting array/multi-valued fields.
729−
730−http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_mode_option
731−-}
732−data SortMode = SortMin
733− | SortMax
734− | SortSum
735− | SortAvg deriving (Eq, Show, Generic, Typeable)
736−
737−{-| 'mkSort' defaults everything but the 'FieldName' and the 'SortOrder' so
738− that you can concisely describe the usual kind of 'SortSpec's you want.
739−-}
740−mkSort :: FieldName -> SortOrder -> DefaultSort
741−mkSort fieldName sOrder = DefaultSort fieldName sOrder False Nothing Nothing Nothing
742−
743−{-| 'Cache' is for telling ES whether it should cache a 'Filter' not.
744− 'Query's cannot be cached.
745−-}
746−type Cache = Bool -- caching on/off
747−defaultCache :: Cache
748−defaultCache = False
749−
750−{-| 'PrefixValue' is used in 'PrefixQuery' as the main query component.
751−-}
752−type PrefixValue = Text
753−
754−{-| 'BooleanOperator' is the usual And/Or operators with an ES compatible
755− JSON encoding baked in. Used all over the place.
756−-}
757−data BooleanOperator = And | Or deriving (Eq, Show, Generic, Typeable)
758−
759−{-| 'ShardCount' is part of 'IndexSettings'
760−-}
761−newtype ShardCount = ShardCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
762−
763−{-| 'ReplicaCount' is part of 'IndexSettings'
764−-}
765−newtype ReplicaCount = ReplicaCount Int deriving (Eq, Show, Generic, ToJSON, Typeable)
766−
767−{-| 'IndexName' is used to describe which index to query/create/delete
768−-}
769−newtype IndexName = IndexName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
770−
771−{-| 'TemplateName' is used to describe which template to query/create/delete
772−-}
773−newtype TemplateName = TemplateName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
774−
775−{-| 'TemplatePattern' represents a pattern which is matched against index names
776−-}
777−newtype TemplatePattern = TemplatePattern Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
778−
779−{-| 'MappingName' is part of mappings which are how ES describes and schematizes
780− the data in the indices.
781−-}
782−newtype MappingName = MappingName Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
783−
784−{-| 'DocId' is a generic wrapper value for expressing unique Document IDs.
785− Can be set by the user or created by ES itself. Often used in client
786− functions for poking at specific documents.
787−-}
788−newtype DocId = DocId Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
789−
790−{-| 'QueryString' is used to wrap query text bodies, be they human written or not.
791−-}
792−newtype QueryString = QueryString Text deriving (Eq, Generic, Show, ToJSON, FromJSON, Typeable)
793−
794−{-| 'FieldName' is used all over the place wherever a specific field within
795− a document needs to be specified, usually in 'Query's or 'Filter's.
796−-}
797−newtype FieldName = FieldName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
798−
799−
800−{-| 'Script' is often used in place of 'FieldName' to specify more
801−complex ways of extracting a value from a document.
802−-}
803−newtype Script = Script { scriptText :: Text } deriving (Eq, Show, Generic, Typeable)
804−
805−{-| 'CacheName' is used in 'RegexpFilter' for describing the
806− 'CacheKey' keyed caching behavior.
807−-}
808−newtype CacheName = CacheName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
809−
810−{-| 'CacheKey' is used in 'RegexpFilter' to key regex caching.
811−-}
812−newtype CacheKey =
813− CacheKey Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
814−newtype Existence =
815− Existence Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
816−newtype NullValue =
817− NullValue Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
818−newtype CutoffFrequency =
819− CutoffFrequency Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
820−newtype Analyzer =
821− Analyzer Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
822−newtype MaxExpansions =
823− MaxExpansions Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
824−
825−{-| 'Lenient', if set to true, will cause format based failures to be
826− ignored. I don't know what the bloody default is, Elasticsearch
827− documentation didn't say what it was. Let me know if you figure it out.
828−-}
829−newtype Lenient =
830− Lenient Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
831−newtype Tiebreaker =
832− Tiebreaker Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
833−newtype Boost =
834− Boost Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
835−newtype BoostTerms =
836− BoostTerms Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
837−
838−{-| 'MinimumMatch' controls how many should clauses in the bool query should
839− match. Can be an absolute value (2) or a percentage (30%) or a
840− combination of both.
841−-}
842−newtype MinimumMatch =
843− MinimumMatch Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
844−newtype DisableCoord =
845− DisableCoord Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
846−newtype IgnoreTermFrequency =
847− IgnoreTermFrequency Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
848−newtype MinimumTermFrequency =
849− MinimumTermFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
850−newtype MaxQueryTerms =
851− MaxQueryTerms Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
852−newtype Fuzziness =
853− Fuzziness Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
854−
855−{-| 'PrefixLength' is the prefix length used in queries, defaults to 0. -}
856−newtype PrefixLength =
857− PrefixLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
858−newtype TypeName =
859− TypeName Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
860−newtype PercentMatch =
861− PercentMatch Double deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
862−newtype StopWord =
863− StopWord Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
864−newtype QueryPath =
865− QueryPath Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
866−
867−{-| Allowing a wildcard at the beginning of a word (eg "*ing") is particularly
868− heavy, because all terms in the index need to be examined, just in case
869− they match. Leading wildcards can be disabled by setting
870− 'AllowLeadingWildcard' to false. -}
871−newtype AllowLeadingWildcard =
872− AllowLeadingWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
873−newtype LowercaseExpanded =
874− LowercaseExpanded Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
875−newtype EnablePositionIncrements =
876− EnablePositionIncrements Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
877−
878−{-| By default, wildcard terms in a query are not analyzed.
879− Setting 'AnalyzeWildcard' to true enables best-effort analysis.
880−-}
881−newtype AnalyzeWildcard = AnalyzeWildcard Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
882−
883−{-| 'GeneratePhraseQueries' defaults to false.
884−-}
885−newtype GeneratePhraseQueries =
886− GeneratePhraseQueries Bool deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
887−
888−{-| 'Locale' is used for string conversions - defaults to ROOT.
889−-}
890−newtype Locale = Locale Text deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
891−newtype MaxWordLength = MaxWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
892−newtype MinWordLength = MinWordLength Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
893−
894−{-| 'PhraseSlop' sets the default slop for phrases, 0 means exact
895− phrase matches. Default is 0.
896−-}
897−newtype PhraseSlop = PhraseSlop Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
898−newtype MinDocFrequency = MinDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
899−newtype MaxDocFrequency = MaxDocFrequency Int deriving (Eq, Show, Generic, ToJSON, FromJSON, Typeable)
900−
901−-- | Newtype wrapper to parse ES's concerning tendency to in some APIs return a floating point number of milliseconds since epoch ಠ_ಠ
902−newtype POSIXMS = POSIXMS { posixMS :: UTCTime }
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
903429
904430{-| 'unpackId' is a silly convenience function that gets used once.
905431-}
@@ -907,8 +433,6 @@ unpackId :: DocId -> Text
907433unpackId (DocId docId) = docId
908434
909435type TrackSortScores = Bool
910−newtype From = From Int deriving (Eq, Show, Generic, ToJSON)
911−newtype Size = Size Int deriving (Eq, Show, Generic, ToJSON)
912436
913437data Search = Search { queryBody :: Maybe Query
914438 , filterBody :: Maybe Filter
@@ -920,537 +444,74 @@ data Search = Search { queryBody :: Maybe Query
920444 , from :: From
921445 , size :: Size
922446 , searchType :: SearchType
447+ , searchAfterKey :: Maybe SearchAfterKey
923448 , fields :: Maybe [FieldName]
924− , source :: Maybe Source } deriving (Eq, Show, Generic, Typeable)
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] [] []
925479
926480data SearchType = SearchTypeQueryThenFetch
927481 | SearchTypeDfsQueryThenFetch
928− | SearchTypeCount
929− | SearchTypeScan
930− | SearchTypeQueryAndFetch
931− | SearchTypeDfsQueryAndFetch
932− deriving (Eq, Show, Generic, Typeable)
482+ deriving (Eq, Show)
933483
934484data Source =
935485 NoSource
936486 | SourcePatterns PatternOrPatterns
937487 | SourceIncludeExclude Include Exclude
938− deriving (Show, Eq, Generic, Typeable)
939−
940−data PatternOrPatterns = PopPattern Pattern
941− | PopPatterns [Pattern] deriving (Eq, Show, Generic, Typeable)
942−
943−data Include = Include [Pattern] deriving (Eq, Show, Generic, Typeable)
944−data Exclude = Exclude [Pattern] deriving (Eq, Show, Generic, Typeable)
945−
946−newtype Pattern = Pattern Text deriving (Eq, Show, Generic, Typeable)
947−
948−data Highlights = Highlights { globalsettings :: Maybe HighlightSettings
949− , highlightFields :: [FieldHighlight]
950− } deriving (Show, Eq, Generic, Typeable)
951−
952−data FieldHighlight = FieldHighlight FieldName (Maybe HighlightSettings)
953− deriving (Show, Eq, Generic, Typeable)
954−
955−
956−data HighlightSettings = Plain PlainHighlight
957− | Postings PostingsHighlight
958− | FastVector FastVectorHighlight
959− deriving (Show, Eq, Generic, Typeable)
960−data PlainHighlight =
961− PlainHighlight { plainCommon :: Maybe CommonHighlight
962− , plainNonPost :: Maybe NonPostings } deriving (Show, Eq, Generic, Typeable)
963−
964− -- This requires that index_options are set to 'offset' in the mapping.
965−data PostingsHighlight = PostingsHighlight (Maybe CommonHighlight) deriving (Show, Eq, Generic, Typeable)
966−
967−-- This requires that term_vector is set to 'with_positions_offsets' in the mapping.
968−data FastVectorHighlight =
969− FastVectorHighlight { fvCommon :: Maybe CommonHighlight
970− , fvNonPostSettings :: Maybe NonPostings
971− , boundaryChars :: Maybe Text
972− , boundaryMaxScan :: Maybe Int
973− , fragmentOffset :: Maybe Int
974− , matchedFields :: [Text]
975− , phraseLimit :: Maybe Int
976− } deriving (Show, Eq, Generic, Typeable)
977−
978−data CommonHighlight =
979− CommonHighlight { order :: Maybe Text
980− , forceSource :: Maybe Bool
981− , tag :: Maybe HighlightTag
982− , encoder :: Maybe HighlightEncoder
983− , noMatchSize :: Maybe Int
984− , highlightQuery :: Maybe Query
985− , requireFieldMatch :: Maybe Bool
986− } deriving (Show, Eq, Generic, Typeable)
987−
988−-- Settings that are only applicable to FastVector and Plain highlighters.
989−data NonPostings =
990− NonPostings { fragmentSize :: Maybe Int
991− , numberOfFragments :: Maybe Int} deriving (Show, Eq, Generic, Typeable)
992−
993−data HighlightEncoder = DefaultEncoder
994− | HTMLEncoder
995− deriving (Show, Eq, Generic, Typeable)
996−
997−-- NOTE: Should the tags use some kind of HTML type, rather than Text?
998−data HighlightTag = TagSchema Text
999− | CustomTags ([Text], [Text]) -- Only uses more than the first value in the lists if fvh
1000− deriving (Show, Eq, Generic, Typeable)
1001−
1002−
1003−data Query =
1004− TermQuery Term (Maybe Boost)
1005− | TermsQuery Text (NonEmpty Text)
1006− | QueryMatchQuery MatchQuery
1007− | QueryMultiMatchQuery MultiMatchQuery
1008− | QueryBoolQuery BoolQuery
1009− | QueryBoostingQuery BoostingQuery
1010− | QueryCommonTermsQuery CommonTermsQuery
1011− | ConstantScoreFilter Filter Boost
1012− | ConstantScoreQuery Query Boost
1013− | QueryDisMaxQuery DisMaxQuery
1014− | QueryFilteredQuery FilteredQuery
1015− | QueryFuzzyLikeThisQuery FuzzyLikeThisQuery
1016− | QueryFuzzyLikeFieldQuery FuzzyLikeFieldQuery
1017− | QueryFuzzyQuery FuzzyQuery
1018− | QueryHasChildQuery HasChildQuery
1019− | QueryHasParentQuery HasParentQuery
1020− | IdsQuery MappingName [DocId]
1021− | QueryIndicesQuery IndicesQuery
1022− | MatchAllQuery (Maybe Boost)
1023− | QueryMoreLikeThisQuery MoreLikeThisQuery
1024− | QueryMoreLikeThisFieldQuery MoreLikeThisFieldQuery
1025− | QueryNestedQuery NestedQuery
1026− | QueryPrefixQuery PrefixQuery
1027− | QueryQueryStringQuery QueryStringQuery
1028− | QuerySimpleQueryStringQuery SimpleQueryStringQuery
1029− | QueryRangeQuery RangeQuery
1030− | QueryRegexpQuery RegexpQuery
1031− deriving (Eq, Show, Generic, Typeable)
1032−
1033−data RegexpQuery =
1034− RegexpQuery { regexpQueryField :: FieldName
1035− , regexpQuery :: Regexp
1036− , regexpQueryFlags :: RegexpFlags
1037− , regexpQueryBoost :: Maybe Boost
1038− } deriving (Eq, Show, Generic, Typeable)
1039−
1040−data RangeQuery =
1041− RangeQuery { rangeQueryField :: FieldName
1042− , rangeQueryRange :: RangeValue
1043− , rangeQueryBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1044−
1045−mkRangeQuery :: FieldName -> RangeValue -> RangeQuery
1046−mkRangeQuery f r = RangeQuery f r (Boost 1.0)
1047−
1048−data SimpleQueryStringQuery =
1049− SimpleQueryStringQuery
1050− { simpleQueryStringQuery :: QueryString
1051− , simpleQueryStringField :: Maybe FieldOrFields
1052− , simpleQueryStringOperator :: Maybe BooleanOperator
1053− , simpleQueryStringAnalyzer :: Maybe Analyzer
1054− , simpleQueryStringFlags :: Maybe (NonEmpty SimpleQueryFlag)
1055− , simpleQueryStringLowercaseExpanded :: Maybe LowercaseExpanded
1056− , simpleQueryStringLocale :: Maybe Locale
1057− } deriving (Eq, Show, Generic, Typeable)
1058−
1059−data SimpleQueryFlag =
1060− SimpleQueryAll
1061− | SimpleQueryNone
1062− | SimpleQueryAnd
1063− | SimpleQueryOr
1064− | SimpleQueryPrefix
1065− | SimpleQueryPhrase
1066− | SimpleQueryPrecedence
1067− | SimpleQueryEscape
1068− | SimpleQueryWhitespace
1069− | SimpleQueryFuzzy
1070− | SimpleQueryNear
1071− | SimpleQuerySlop deriving (Eq, Show, Generic, Typeable)
1072−
1073−-- use_dis_max and tie_breaker when fields are plural?
1074−data QueryStringQuery =
1075− QueryStringQuery
1076− { queryStringQuery :: QueryString
1077− , queryStringDefaultField :: Maybe FieldName
1078− , queryStringOperator :: Maybe BooleanOperator
1079− , queryStringAnalyzer :: Maybe Analyzer
1080− , queryStringAllowLeadingWildcard :: Maybe AllowLeadingWildcard
1081− , queryStringLowercaseExpanded :: Maybe LowercaseExpanded
1082− , queryStringEnablePositionIncrements :: Maybe EnablePositionIncrements
1083− , queryStringFuzzyMaxExpansions :: Maybe MaxExpansions
1084− , queryStringFuzziness :: Maybe Fuzziness
1085− , queryStringFuzzyPrefixLength :: Maybe PrefixLength
1086− , queryStringPhraseSlop :: Maybe PhraseSlop
1087− , queryStringBoost :: Maybe Boost
1088− , queryStringAnalyzeWildcard :: Maybe AnalyzeWildcard
1089− , queryStringGeneratePhraseQueries :: Maybe GeneratePhraseQueries
1090− , queryStringMinimumShouldMatch :: Maybe MinimumMatch
1091− , queryStringLenient :: Maybe Lenient
1092− , queryStringLocale :: Maybe Locale
1093− } deriving (Eq, Show, Generic, Typeable)
1094−
1095−mkQueryStringQuery :: QueryString -> QueryStringQuery
1096−mkQueryStringQuery qs =
1097− QueryStringQuery qs Nothing Nothing
1098− Nothing Nothing Nothing Nothing
1099− Nothing Nothing Nothing Nothing
1100− Nothing Nothing Nothing Nothing
1101− Nothing Nothing
1102−
1103−data FieldOrFields = FofField FieldName
1104− | FofFields (NonEmpty FieldName) deriving (Eq, Show, Generic, Typeable)
1105−
1106−data PrefixQuery =
1107− PrefixQuery
1108− { prefixQueryField :: FieldName
1109− , prefixQueryPrefixValue :: Text
1110− , prefixQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1111−
1112−data NestedQuery =
1113− NestedQuery
1114− { nestedQueryPath :: QueryPath
1115− , nestedQueryScoreType :: ScoreType
1116− , nestedQuery :: Query } deriving (Eq, Show, Generic, Typeable)
1117−
1118−data MoreLikeThisFieldQuery =
1119− MoreLikeThisFieldQuery
1120− { moreLikeThisFieldText :: Text
1121− , moreLikeThisFieldFields :: FieldName
1122− -- default 0.3 (30%)
1123− , moreLikeThisFieldPercentMatch :: Maybe PercentMatch
1124− , moreLikeThisFieldMinimumTermFreq :: Maybe MinimumTermFrequency
1125− , moreLikeThisFieldMaxQueryTerms :: Maybe MaxQueryTerms
1126− , moreLikeThisFieldStopWords :: Maybe (NonEmpty StopWord)
1127− , moreLikeThisFieldMinDocFrequency :: Maybe MinDocFrequency
1128− , moreLikeThisFieldMaxDocFrequency :: Maybe MaxDocFrequency
1129− , moreLikeThisFieldMinWordLength :: Maybe MinWordLength
1130− , moreLikeThisFieldMaxWordLength :: Maybe MaxWordLength
1131− , moreLikeThisFieldBoostTerms :: Maybe BoostTerms
1132− , moreLikeThisFieldBoost :: Maybe Boost
1133− , moreLikeThisFieldAnalyzer :: Maybe Analyzer
1134− } deriving (Eq, Show, Generic, Typeable)
1135−
1136−data MoreLikeThisQuery =
1137− MoreLikeThisQuery
1138− { moreLikeThisText :: Text
1139− , moreLikeThisFields :: Maybe (NonEmpty FieldName)
1140− -- default 0.3 (30%)
1141− , moreLikeThisPercentMatch :: Maybe PercentMatch
1142− , moreLikeThisMinimumTermFreq :: Maybe MinimumTermFrequency
1143− , moreLikeThisMaxQueryTerms :: Maybe MaxQueryTerms
1144− , moreLikeThisStopWords :: Maybe (NonEmpty StopWord)
1145− , moreLikeThisMinDocFrequency :: Maybe MinDocFrequency
1146− , moreLikeThisMaxDocFrequency :: Maybe MaxDocFrequency
1147− , moreLikeThisMinWordLength :: Maybe MinWordLength
1148− , moreLikeThisMaxWordLength :: Maybe MaxWordLength
1149− , moreLikeThisBoostTerms :: Maybe BoostTerms
1150− , moreLikeThisBoost :: Maybe Boost
1151− , moreLikeThisAnalyzer :: Maybe Analyzer
1152− } deriving (Eq, Show, Generic, Typeable)
1153−
1154−data IndicesQuery =
1155− IndicesQuery
1156− { indicesQueryIndices :: [IndexName]
1157− , indicesQuery :: Query
1158− -- default "all"
1159− , indicesQueryNoMatch :: Maybe Query } deriving (Eq, Show, Generic, Typeable)
1160−
1161−data HasParentQuery =
1162− HasParentQuery
1163− { hasParentQueryType :: TypeName
1164− , hasParentQuery :: Query
1165− , hasParentQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1166−
1167−data HasChildQuery =
1168− HasChildQuery
1169− { hasChildQueryType :: TypeName
1170− , hasChildQuery :: Query
1171− , hasChildQueryScoreType :: Maybe ScoreType } deriving (Eq, Show, Generic, Typeable)
1172−
1173−data ScoreType =
1174− ScoreTypeMax
1175− | ScoreTypeSum
1176− | ScoreTypeAvg
1177− | ScoreTypeNone deriving (Eq, Show, Generic, Typeable)
1178−
1179−data FuzzyQuery =
1180− FuzzyQuery { fuzzyQueryField :: FieldName
1181− , fuzzyQueryValue :: Text
1182− , fuzzyQueryPrefixLength :: PrefixLength
1183− , fuzzyQueryMaxExpansions :: MaxExpansions
1184− , fuzzyQueryFuzziness :: Fuzziness
1185− , fuzzyQueryBoost :: Maybe Boost
1186− } deriving (Eq, Show, Generic, Typeable)
1187−
1188−data FuzzyLikeFieldQuery =
1189− FuzzyLikeFieldQuery
1190− { fuzzyLikeField :: FieldName
1191− -- anaphora is good for the soul.
1192− , fuzzyLikeFieldText :: Text
1193− , fuzzyLikeFieldMaxQueryTerms :: MaxQueryTerms
1194− , fuzzyLikeFieldIgnoreTermFrequency :: IgnoreTermFrequency
1195− , fuzzyLikeFieldFuzziness :: Fuzziness
1196− , fuzzyLikeFieldPrefixLength :: PrefixLength
1197− , fuzzyLikeFieldBoost :: Boost
1198− , fuzzyLikeFieldAnalyzer :: Maybe Analyzer
1199− } deriving (Eq, Show, Generic, Typeable)
1200−
1201−data FuzzyLikeThisQuery =
1202− FuzzyLikeThisQuery
1203− { fuzzyLikeFields :: [FieldName]
1204− , fuzzyLikeText :: Text
1205− , fuzzyLikeMaxQueryTerms :: MaxQueryTerms
1206− , fuzzyLikeIgnoreTermFrequency :: IgnoreTermFrequency
1207− , fuzzyLikeFuzziness :: Fuzziness
1208− , fuzzyLikePrefixLength :: PrefixLength
1209− , fuzzyLikeBoost :: Boost
1210− , fuzzyLikeAnalyzer :: Maybe Analyzer
1211− } deriving (Eq, Show, Generic, Typeable)
1212−
1213−data FilteredQuery =
1214− FilteredQuery
1215− { filteredQuery :: Query
1216− , filteredFilter :: Filter } deriving (Eq, Show, Generic, Typeable)
1217−
1218−data DisMaxQuery =
1219− DisMaxQuery { disMaxQueries :: [Query]
1220− -- default 0.0
1221− , disMaxTiebreaker :: Tiebreaker
1222− , disMaxBoost :: Maybe Boost
1223− } deriving (Eq, Show, Generic, Typeable)
1224−
1225−data MatchQuery =
1226− MatchQuery { matchQueryField :: FieldName
1227− , matchQueryQueryString :: QueryString
1228− , matchQueryOperator :: BooleanOperator
1229− , matchQueryZeroTerms :: ZeroTermsQuery
1230− , matchQueryCutoffFrequency :: Maybe CutoffFrequency
1231− , matchQueryMatchType :: Maybe MatchQueryType
1232− , matchQueryAnalyzer :: Maybe Analyzer
1233− , matchQueryMaxExpansions :: Maybe MaxExpansions
1234− , matchQueryLenient :: Maybe Lenient
1235− , matchQueryBoost :: Maybe Boost } deriving (Eq, Show, Generic, Typeable)
1236−
1237−{-| 'mkMatchQuery' is a convenience function that defaults the less common parameters,
1238− enabling you to provide only the 'FieldName' and 'QueryString' to make a 'MatchQuery'
1239−-}
1240−mkMatchQuery :: FieldName -> QueryString -> MatchQuery
1241−mkMatchQuery field query = MatchQuery field query Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1242−
1243−data MatchQueryType =
1244− MatchPhrase
1245− | MatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1246−
1247−data MultiMatchQuery =
1248− MultiMatchQuery { multiMatchQueryFields :: [FieldName]
1249− , multiMatchQueryString :: QueryString
1250− , multiMatchQueryOperator :: BooleanOperator
1251− , multiMatchQueryZeroTerms :: ZeroTermsQuery
1252− , multiMatchQueryTiebreaker :: Maybe Tiebreaker
1253− , multiMatchQueryType :: Maybe MultiMatchQueryType
1254− , multiMatchQueryCutoffFrequency :: Maybe CutoffFrequency
1255− , multiMatchQueryAnalyzer :: Maybe Analyzer
1256− , multiMatchQueryMaxExpansions :: Maybe MaxExpansions
1257− , multiMatchQueryLenient :: Maybe Lenient } deriving (Eq, Show, Generic, Typeable)
488+ deriving (Eq, Show)
1258489
1259−{-| 'mkMultiMatchQuery' is a convenience function that defaults the less common parameters,
1260− enabling you to provide only the list of 'FieldName's and 'QueryString' to
1261− make a 'MultiMatchQuery'.
1262−-}
1263−
1264−mkMultiMatchQuery :: [FieldName] -> QueryString -> MultiMatchQuery
1265−mkMultiMatchQuery matchFields query =
1266− MultiMatchQuery matchFields query
1267− Or ZeroTermsNone Nothing Nothing Nothing Nothing Nothing Nothing
1268−
1269−data MultiMatchQueryType =
1270− MultiMatchBestFields
1271− | MultiMatchMostFields
1272− | MultiMatchCrossFields
1273− | MultiMatchPhrase
1274− | MultiMatchPhrasePrefix deriving (Eq, Show, Generic, Typeable)
1275−
1276−data BoolQuery =
1277− BoolQuery { boolQueryMustMatch :: [Query]
1278− , boolQueryMustNotMatch :: [Query]
1279− , boolQueryShouldMatch :: [Query]
1280− , boolQueryMinimumShouldMatch :: Maybe MinimumMatch
1281− , boolQueryBoost :: Maybe Boost
1282− , boolQueryDisableCoord :: Maybe DisableCoord
1283− } deriving (Eq, Show, Generic, Typeable)
1284−
1285−mkBoolQuery :: [Query] -> [Query] -> [Query] -> BoolQuery
1286−mkBoolQuery must mustNot should =
1287− BoolQuery must mustNot should Nothing Nothing Nothing
1288−
1289−data BoostingQuery =
1290− BoostingQuery { positiveQuery :: Query
1291− , negativeQuery :: Query
1292− , negativeBoost :: Boost } deriving (Eq, Show, Generic, Typeable)
1293−
1294−data CommonTermsQuery =
1295− CommonTermsQuery { commonField :: FieldName
1296− , commonQuery :: QueryString
1297− , commonCutoffFrequency :: CutoffFrequency
1298− , commonLowFreqOperator :: BooleanOperator
1299− , commonHighFreqOperator :: BooleanOperator
1300− , commonMinimumShouldMatch :: Maybe CommonMinimumMatch
1301− , commonBoost :: Maybe Boost
1302− , commonAnalyzer :: Maybe Analyzer
1303− , commonDisableCoord :: Maybe DisableCoord
1304− } deriving (Eq, Show, Generic, Typeable)
1305−
1306−data CommonMinimumMatch =
1307− CommonMinimumMatchHighLow MinimumMatchHighLow
1308− | CommonMinimumMatch MinimumMatch
1309− deriving (Eq, Show, Generic, Typeable)
1310−
1311−data MinimumMatchHighLow =
1312− MinimumMatchHighLow { lowFreq :: MinimumMatch
1313− , highFreq :: MinimumMatch } deriving (Eq, Show, Generic, Typeable)
1314−
1315−data Filter = AndFilter [Filter] Cache
1316− | OrFilter [Filter] Cache
1317− | NotFilter Filter Cache
1318− | IdentityFilter
1319− | BoolFilter BoolMatch
1320− | ExistsFilter FieldName -- always cached
1321− | GeoBoundingBoxFilter GeoBoundingBoxConstraint
1322− | GeoDistanceFilter GeoPoint Distance DistanceType OptimizeBbox Cache
1323− | GeoDistanceRangeFilter GeoPoint DistanceRange
1324− | GeoPolygonFilter FieldName [LatLon]
1325− | IdsFilter MappingName [DocId]
1326− | LimitFilter Int
1327− | MissingFilter FieldName Existence NullValue
1328− | PrefixFilter FieldName PrefixValue Cache
1329− | QueryFilter Query Cache
1330− | RangeFilter FieldName RangeValue RangeExecution Cache
1331− | RegexpFilter FieldName Regexp RegexpFlags CacheName Cache CacheKey
1332− | TermFilter Term Cache
1333− deriving (Eq, Show, Generic, Typeable)
1334−
1335−data ZeroTermsQuery = ZeroTermsNone
1336− | ZeroTermsAll deriving (Eq, Show, Generic, Typeable)
1337−
1338−data RangeExecution = RangeExecutionIndex
1339− | RangeExecutionFielddata deriving (Eq, Show, Generic, Typeable)
1340−
1341−newtype Regexp = Regexp Text deriving (Eq, Show, Generic, Typeable, FromJSON)
1342−
1343−data RegexpFlags = AllRegexpFlags
1344− | NoRegexpFlags
1345− | SomeRegexpFlags (NonEmpty RegexpFlag) deriving (Eq, Show, Generic, Typeable)
1346−
1347−data RegexpFlag = AnyString
1348− | Automaton
1349− | Complement
1350− | Empty
1351− | Intersection
1352− | Interval deriving (Eq, Show, Generic, Typeable)
1353−
1354−newtype LessThan = LessThan Double deriving (Eq, Show, Generic, Typeable)
1355−newtype LessThanEq = LessThanEq Double deriving (Eq, Show, Generic, Typeable)
1356−newtype GreaterThan = GreaterThan Double deriving (Eq, Show, Generic, Typeable)
1357−newtype GreaterThanEq = GreaterThanEq Double deriving (Eq, Show, Generic, Typeable)
1358−
1359−newtype LessThanD = LessThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1360−newtype LessThanEqD = LessThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1361−newtype GreaterThanD = GreaterThanD UTCTime deriving (Eq, Show, Generic, Typeable)
1362−newtype GreaterThanEqD = GreaterThanEqD UTCTime deriving (Eq, Show, Generic, Typeable)
1363−
1364−data RangeValue = RangeDateLte LessThanEqD
1365− | RangeDateLt LessThanD
1366− | RangeDateGte GreaterThanEqD
1367− | RangeDateGt GreaterThanD
1368− | RangeDateGtLt GreaterThanD LessThanD
1369− | RangeDateGteLte GreaterThanEqD LessThanEqD
1370− | RangeDateGteLt GreaterThanEqD LessThanD
1371− | RangeDateGtLte GreaterThanD LessThanEqD
1372− | RangeDoubleLte LessThanEq
1373− | RangeDoubleLt LessThan
1374− | RangeDoubleGte GreaterThanEq
1375− | RangeDoubleGt GreaterThan
1376− | RangeDoubleGtLt GreaterThan LessThan
1377− | RangeDoubleGteLte GreaterThanEq LessThanEq
1378− | RangeDoubleGteLt GreaterThanEq LessThan
1379− | RangeDoubleGtLte GreaterThan LessThanEq
1380− deriving (Eq, Show, Generic, Typeable)
1381−
1382−rangeValueToPair :: RangeValue -> [Pair]
1383−rangeValueToPair rv = case rv of
1384− RangeDateLte (LessThanEqD t) -> ["lte" .= t]
1385− RangeDateGte (GreaterThanEqD t) -> ["gte" .= t]
1386− RangeDateLt (LessThanD t) -> ["lt" .= t]
1387− RangeDateGt (GreaterThanD t) -> ["gt" .= t]
1388− RangeDateGteLte (GreaterThanEqD l) (LessThanEqD g) -> ["gte" .= l, "lte" .= g]
1389− RangeDateGtLte (GreaterThanD l) (LessThanEqD g) -> ["gt" .= l, "lte" .= g]
1390− RangeDateGteLt (GreaterThanEqD l) (LessThanD g) -> ["gte" .= l, "lt" .= g]
1391− RangeDateGtLt (GreaterThanD l) (LessThanD g) -> ["gt" .= l, "lt" .= g]
1392− RangeDoubleLte (LessThanEq t) -> ["lte" .= t]
1393− RangeDoubleGte (GreaterThanEq t) -> ["gte" .= t]
1394− RangeDoubleLt (LessThan t) -> ["lt" .= t]
1395− RangeDoubleGt (GreaterThan t) -> ["gt" .= t]
1396− RangeDoubleGteLte (GreaterThanEq l) (LessThanEq g) -> ["gte" .= l, "lte" .= g]
1397− RangeDoubleGtLte (GreaterThan l) (LessThanEq g) -> ["gt" .= l, "lte" .= g]
1398− RangeDoubleGteLt (GreaterThanEq l) (LessThan g) -> ["gte" .= l, "lt" .= g]
1399− RangeDoubleGtLt (GreaterThan l) (LessThan g) -> ["gt" .= l, "lt" .= g]
1400−
1401−data Term = Term { termField :: Text
1402− , termValue :: Text } deriving (Eq, Show, Generic, Typeable)
1403−
1404−data BoolMatch = MustMatch Term Cache
1405− | MustNotMatch Term Cache
1406− | ShouldMatch [Term] Cache deriving (Eq, Show, Generic, Typeable)
1407−
1408−-- "memory" or "indexed"
1409−data GeoFilterType = GeoFilterMemory
1410− | GeoFilterIndexed deriving (Eq, Show, Generic, Typeable)
1411−
1412−data LatLon = LatLon { lat :: Double
1413− , lon :: Double } deriving (Eq, Show, Generic, Typeable)
1414−
1415−data GeoBoundingBox =
1416− GeoBoundingBox { topLeft :: LatLon
1417− , bottomRight :: LatLon } deriving (Eq, Show, Generic, Typeable)
490+instance ToJSON Source where
491+ toJSON NoSource = toJSON False
492+ toJSON (SourcePatterns patterns) = toJSON patterns
493+ toJSON (SourceIncludeExclude incl excl) = object [ "includes" .= incl, "excludes" .= excl ]
1418494
1419−data GeoBoundingBoxConstraint =
1420− GeoBoundingBoxConstraint { geoBBField :: FieldName
1421− , constraintBox :: GeoBoundingBox
1422− , bbConstraintcache :: Cache
1423− , geoType :: GeoFilterType
1424− } deriving (Eq, Show, Generic, Typeable)
495+data PatternOrPatterns = PopPattern Pattern
496+ | PopPatterns [Pattern] deriving (Eq, Read, Show)
1425497
1426−data GeoPoint =
1427− GeoPoint { geoField :: FieldName
1428− , latLon :: LatLon} deriving (Eq, Show, Generic, Typeable)
498+instance ToJSON PatternOrPatterns where
499+ toJSON (PopPattern pattern) = toJSON pattern
500+ toJSON (PopPatterns patterns) = toJSON patterns
1429501
1430−data DistanceUnit = Miles
1431− | Yards
1432− | Feet
1433− | Inches
1434− | Kilometers
1435− | Meters
1436− | Centimeters
1437− | Millimeters
1438− | NauticalMiles deriving (Eq, Show, Generic, Typeable)
502+data Include = Include [Pattern] deriving (Eq, Read, Show)
503+data Exclude = Exclude [Pattern] deriving (Eq, Read, Show)
1439504
1440−data DistanceType = Arc
1441− | SloppyArc -- doesn't exist <1.0
1442− | Plane deriving (Eq, Show, Generic, Typeable)
505+instance ToJSON Include where
506+ toJSON (Include patterns) = toJSON patterns
1443507
1444−data OptimizeBbox = OptimizeGeoFilterType GeoFilterType
1445− | NoOptimizeBbox deriving (Eq, Show, Generic, Typeable)
508+instance ToJSON Exclude where
509+ toJSON (Exclude patterns) = toJSON patterns
1446510
1447−data Distance =
1448− Distance { coefficient :: Double
1449− , unit :: DistanceUnit } deriving (Eq, Show, Generic, Typeable)
511+newtype Pattern = Pattern Text deriving (Eq, Read, Show)
1450512
1451−data DistanceRange =
1452− DistanceRange { distanceFrom :: Distance
1453− , distanceTo :: Distance } deriving (Eq, Show, Generic, Typeable)
513+instance ToJSON Pattern where
514+ toJSON (Pattern pattern) = toJSON pattern
1454515
1455516data SearchResult a =
1456517 SearchResult { took :: Int
@@ -1458,2024 +519,12 @@ data SearchResult a =
1458519 , shards :: ShardResult
1459520 , searchHits :: SearchHits a
1460521 , aggregations :: Maybe AggregationResults
1461− , scrollId :: Maybe ScrollId } deriving (Eq, Show, Generic, Typeable)
1462−
1463−newtype ScrollId = ScrollId Text deriving (Eq, Show, Generic, Ord, ToJSON, FromJSON)
1464−
1465−type Score = Maybe Double
1466−
1467−data SearchHits a =
1468− SearchHits { hitsTotal :: Int
1469− , maxScore :: Score
1470− , hits :: [Hit a] } deriving (Eq, Show, Generic, Typeable)
1471−
1472−
1473−instance Monoid (SearchHits a) where
1474− mempty = SearchHits 0 Nothing mempty
1475− mappend (SearchHits ta ma ha) (SearchHits tb mb hb) =
1476− SearchHits (ta + tb) (max ma mb) (ha <> hb)
1477−
1478−
1479−data Hit a =
1480− Hit { hitIndex :: IndexName
1481− , hitType :: MappingName
1482− , hitDocId :: DocId
1483− , hitScore :: Score
1484− , hitSource :: Maybe a
1485− , hitHighlight :: Maybe HitHighlight } deriving (Eq, Show, Generic, Typeable)
1486−
1487−data ShardResult =
1488− ShardResult { shardTotal :: Int
1489− , shardsSuccessful :: Int
1490− , shardsFailed :: Int } deriving (Eq, Show, Generic, Typeable)
1491−
1492−type HitHighlight = M.Map Text [Text]
1493−
1494−showText :: Show a => a -> Text
1495−showText = T.pack . show
1496−
1497−readMay :: Read a => String -> Maybe a
1498−readMay s = case reads s of
1499− (a, ""):_ -> Just a
1500− _ -> Nothing
1501−
1502−parseReadText :: Read a => Text -> Parser a
1503−parseReadText = maybe mzero return . readMay . T.unpack
1504−
1505−type Aggregations = M.Map Text Aggregation
1506−
1507−emptyAggregations :: Aggregations
1508−emptyAggregations = M.empty
1509−
1510−mkAggregations :: Text -> Aggregation -> Aggregations
1511−mkAggregations name aggregation = M.insert name aggregation emptyAggregations
1512−
1513−data TermOrder = TermOrder{ termSortField :: Text
1514− , termSortOrder :: SortOrder } deriving (Eq, Show, Generic, Typeable)
1515−
1516−data TermInclusion = TermInclusion Text
1517− | TermPattern Text Text deriving (Eq, Show, Generic, Typeable)
1518−
1519−data CollectionMode = BreadthFirst
1520− | DepthFirst deriving (Eq, Show, Generic, Typeable)
1521−
1522−data ExecutionHint = Ordinals
1523− | GlobalOrdinals
1524− | GlobalOrdinalsHash
1525− | GlobalOrdinalsLowCardinality
1526− | Map deriving (Eq, Show, Generic, Typeable)
1527−
1528−data TimeInterval = Weeks
1529− | Days
1530− | Hours
1531− | Minutes
1532− | Seconds deriving (Eq)
1533−
1534−data Interval = Year
1535− | Quarter
1536− | Month
1537− | Week
1538− | Day
1539− | Hour
1540− | Minute
1541− | Second
1542− | FractionalInterval Float TimeInterval deriving (Eq, Show, Generic, Typeable)
1543−
1544−data Aggregation = TermsAgg TermsAggregation
1545− | DateHistogramAgg DateHistogramAggregation
1546− | ValueCountAgg ValueCountAggregation
1547− | FilterAgg FilterAggregation
1548− | DateRangeAgg DateRangeAggregation
1549− | MissingAgg MissingAggregation deriving (Eq, Show, Generic, Typeable)
1550−
1551−data MissingAggregation = MissingAggregation
1552− { maField :: Text
1553− } deriving (Eq, Show, Generic, Typeable)
1554−
1555−data TermsAggregation = TermsAggregation { term :: Either Text Text
1556− , termInclude :: Maybe TermInclusion
1557− , termExclude :: Maybe TermInclusion
1558− , termOrder :: Maybe TermOrder
1559− , termMinDocCount :: Maybe Int
1560− , termSize :: Maybe Int
1561− , termShardSize :: Maybe Int
1562− , termCollectMode :: Maybe CollectionMode
1563− , termExecutionHint :: Maybe ExecutionHint
1564− , termAggs :: Maybe Aggregations
1565− } deriving (Eq, Show, Generic, Typeable)
1566−
1567−data DateHistogramAggregation = DateHistogramAggregation { dateField :: FieldName
1568− , dateInterval :: Interval
1569− , dateFormat :: Maybe Text
1570− -- pre and post deprecated in 1.5
1571− , datePreZone :: Maybe Text
1572− , datePostZone :: Maybe Text
1573− , datePreOffset :: Maybe Text
1574− , datePostOffset :: Maybe Text
1575− , dateAggs :: Maybe Aggregations
1576− } deriving (Eq, Show, Generic, Typeable)
1577−
1578−
1579−data DateRangeAggregation = DateRangeAggregation { draField :: FieldName
1580− , draFormat :: Maybe Text
1581− , draRanges :: NonEmpty DateRangeAggRange
1582− } deriving (Eq, Show, Generic, Typeable)
1583−
1584−data DateRangeAggRange = DateRangeFrom DateMathExpr
1585− | DateRangeTo DateMathExpr
1586− | DateRangeFromAndTo DateMathExpr DateMathExpr deriving (Eq, Show, Generic, Typeable)
1587−
1588−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math> for more information.
1589−data DateMathExpr = DateMathExpr DateMathAnchor [DateMathModifier] deriving (Eq, Show, Generic, Typeable)
1590−
1591−
1592−-- | Starting point for a date range. This along with the 'DateMathModifiers' gets you the date ES will start from.
1593−data DateMathAnchor = DMNow
1594− | DMDate Day deriving (Eq, Show, Generic, Typeable)
1595−
1596−data DateMathModifier = AddTime Int DateMathUnit
1597− | SubtractTime Int DateMathUnit
1598− | RoundDownTo DateMathUnit deriving (Eq, Show, Generic, Typeable)
1599−
1600−data DateMathUnit = DMYear
1601− | DMMonth
1602− | DMWeek
1603− | DMDay
1604− | DMHour
1605− | DMMinute
1606− | DMSecond deriving (Eq, Show, Generic, Typeable)
1607−
1608−-- | See <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html> for more information.
1609−data ValueCountAggregation = FieldValueCount FieldName
1610− | ScriptValueCount Script deriving (Eq, Show, Generic, Typeable)
1611−
1612−-- | 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.
1613−data FilterAggregation = FilterAggregation { faFilter :: Filter
1614− , faAggs :: Maybe Aggregations} deriving (Eq, Show, Generic, Typeable)
1615−
1616−mkTermsAggregation :: Text -> TermsAggregation
1617−mkTermsAggregation t = TermsAggregation (Left t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1618−
1619−mkTermsScriptAggregation :: Text -> TermsAggregation
1620−mkTermsScriptAggregation t = TermsAggregation (Right t) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
1621−
1622−mkDateHistogram :: FieldName -> Interval -> DateHistogramAggregation
1623−mkDateHistogram t i = DateHistogramAggregation t i Nothing Nothing Nothing Nothing Nothing Nothing
1624−
1625−instance ToJSON Version where
1626− toJSON Version {..} = object ["number" .= number
1627− ,"build_hash" .= build_hash
1628− ,"build_timestamp" .= build_timestamp
1629− ,"build_snapshot" .= build_snapshot
1630− ,"lucene_version" .= lucene_version]
1631−
1632−instance FromJSON Version where
1633− parseJSON = withObject "Version" parse
1634− where parse o = Version
1635− <$> o .: "number"
1636− <*> o .: "build_hash"
1637− <*> o .: "build_timestamp"
1638− <*> o .: "build_snapshot"
1639− <*> o .: "lucene_version"
1640−
1641−instance ToJSON TermOrder where
1642− toJSON (TermOrder termSortField termSortOrder) = object [termSortField .= termSortOrder]
1643−
1644−instance ToJSON TermInclusion where
1645− toJSON (TermInclusion x) = toJSON x
1646− toJSON (TermPattern pattern flags) = omitNulls [ "pattern" .= pattern,
1647− "flags" .= flags]
1648−
1649−instance ToJSON CollectionMode where
1650− toJSON BreadthFirst = "breadth_first"
1651− toJSON DepthFirst = "depth_first"
1652−
1653−instance ToJSON ExecutionHint where
1654− toJSON Ordinals = "ordinals"
1655− toJSON GlobalOrdinals = "global_ordinals"
1656− toJSON GlobalOrdinalsHash = "global_ordinals_hash"
1657− toJSON GlobalOrdinalsLowCardinality = "global_ordinals_low_cardinality"
1658− toJSON Map = "map"
1659−
1660−instance ToJSON Interval where
1661− toJSON Year = "year"
1662− toJSON Quarter = "quarter"
1663− toJSON Month = "month"
1664− toJSON Week = "week"
1665− toJSON Day = "day"
1666− toJSON Hour = "hour"
1667− toJSON Minute = "minute"
1668− toJSON Second = "second"
1669− toJSON (FractionalInterval fraction interval) = toJSON $ show fraction ++ show interval
1670−
1671−instance Show TimeInterval where
1672− show Weeks = "w"
1673− show Days = "d"
1674− show Hours = "h"
1675− show Minutes = "m"
1676− show Seconds = "s"
1677−
1678−instance ToJSON Aggregation where
1679− toJSON (TermsAgg (TermsAggregation term include exclude order minDocCount size shardSize collectMode executionHint termAggs)) =
1680− omitNulls ["terms" .= omitNulls [ toJSON' term,
1681− "include" .= include,
1682− "exclude" .= exclude,
1683− "order" .= order,
1684− "min_doc_count" .= minDocCount,
1685− "size" .= size,
1686− "shard_size" .= shardSize,
1687− "collect_mode" .= collectMode,
1688− "execution_hint" .= executionHint
1689− ],
1690− "aggs" .= termAggs ]
1691− where
1692− toJSON' x = case x of { Left y -> "field" .= y; Right y -> "script" .= y }
1693−
1694− toJSON (DateHistogramAgg (DateHistogramAggregation field interval format preZone postZone preOffset postOffset dateHistoAggs)) =
1695− omitNulls ["date_histogram" .= omitNulls [ "field" .= field,
1696− "interval" .= interval,
1697− "format" .= format,
1698− "pre_zone" .= preZone,
1699− "post_zone" .= postZone,
1700− "pre_offset" .= preOffset,
1701− "post_offset" .= postOffset
1702− ],
1703− "aggs" .= dateHistoAggs ]
1704− toJSON (ValueCountAgg a) = object ["value_count" .= v]
1705− where v = case a of
1706− (FieldValueCount (FieldName n)) -> object ["field" .= n]
1707− (ScriptValueCount (Script s)) -> object ["script" .= s]
1708− toJSON (FilterAgg (FilterAggregation filt ags)) =
1709− omitNulls [ "filter" .= filt
1710− , "aggs" .= ags]
1711− toJSON (DateRangeAgg a) = object [ "date_range" .= a
1712− ]
1713− toJSON (MissingAgg (MissingAggregation{..})) =
1714− object ["missing" .= object ["field" .= maField]]
1715−
1716−instance ToJSON DateRangeAggregation where
1717− toJSON DateRangeAggregation {..} =
1718− omitNulls [ "field" .= draField
1719− , "format" .= draFormat
1720− , "ranges" .= toList draRanges
1721− ]
1722−
1723−instance ToJSON DateRangeAggRange where
1724− toJSON (DateRangeFrom e) = object [ "from" .= e ]
1725− toJSON (DateRangeTo e) = object [ "to" .= e ]
1726− toJSON (DateRangeFromAndTo f t) = object [ "from" .= f, "to" .= t ]
1727−
1728−instance ToJSON DateMathExpr where
1729− toJSON (DateMathExpr a mods) = String (fmtA a <> mconcat (fmtMod <$> mods))
1730− where fmtA DMNow = "now"
1731− fmtA (DMDate date) = case toGregorian date of
1732− (y,m,d) -> showText y <> "-" <>
1733− showText m <> "-" <>
1734− showText d <> "||"
1735− fmtMod (AddTime n u) = "+" <> showText n <> fmtU u
1736− fmtMod (SubtractTime n u) = "-" <> showText n <> fmtU u
1737− fmtMod (RoundDownTo u) = "/" <> fmtU u
1738− fmtU DMYear = "y"
1739− fmtU DMMonth = "M"
1740− fmtU DMWeek = "w"
1741− fmtU DMDay = "d"
1742− fmtU DMHour = "h"
1743− fmtU DMMinute = "m"
1744− fmtU DMSecond = "s"
1745−
1746−
1747−type AggregationResults = M.Map Text Value
1748−
1749−class BucketAggregation a where
1750− key :: a -> Text
1751− docCount :: a -> Int
1752− aggs :: a -> Maybe AggregationResults
1753−
1754−
1755−data Bucket a = Bucket { buckets :: [a]} deriving (Show)
1756−
1757−data TermsResult = TermsResult { termKey :: Text
1758− , termsDocCount :: Int
1759− , termsAggs :: Maybe AggregationResults } deriving (Show)
1760−
1761−data DateHistogramResult = DateHistogramResult { dateKey :: Int
1762− , dateKeyStr :: Maybe Text
1763− , dateDocCount :: Int
1764− , dateHistogramAggs :: Maybe AggregationResults } deriving (Show)
1765−
1766−data DateRangeResult = DateRangeResult { dateRangeKey :: Text
1767− , dateRangeFrom :: Maybe UTCTime
1768− , dateRangeFromAsString :: Maybe Text
1769− , dateRangeTo :: Maybe UTCTime
1770− , dateRangeToAsString :: Maybe Text
1771− , dateRangeDocCount :: Int
1772− , dateRangeAggs :: Maybe AggregationResults } deriving (Show, Eq, Generic, Typeable)
1773−
1774−toTerms :: Text -> AggregationResults -> Maybe (Bucket TermsResult)
1775−toTerms t a = M.lookup t a >>= deserialize
1776− where deserialize = parseMaybe parseJSON
1777−
1778−toDateHistogram :: Text -> AggregationResults -> Maybe (Bucket DateHistogramResult)
1779−toDateHistogram t a = M.lookup t a >>= deserialize
1780− where deserialize = parseMaybe parseJSON
1781−
1782−instance BucketAggregation TermsResult where
1783− key = termKey
1784− docCount = termsDocCount
1785− aggs = termsAggs
1786−
1787−instance BucketAggregation DateHistogramResult where
1788− key = showText . dateKey
1789− docCount = dateDocCount
1790− aggs = dateHistogramAggs
1791−
1792−instance BucketAggregation DateRangeResult where
1793− key = dateRangeKey
1794− docCount = dateRangeDocCount
1795− aggs = dateRangeAggs
1796−
1797−instance (FromJSON a, BucketAggregation a) => FromJSON (Bucket a) where
1798− parseJSON (Object v) = Bucket <$>
1799− v .: "buckets"
1800− parseJSON _ = mempty
1801−
1802−instance FromJSON TermsResult where
1803− parseJSON (Object v) = TermsResult <$>
1804− v .: "key" <*>
1805− v .: "doc_count" <*>
1806− v .:? "aggregations"
1807− parseJSON _ = mempty
1808−
1809−instance FromJSON DateHistogramResult where
1810− parseJSON (Object v) = DateHistogramResult <$>
1811− v .: "key" <*>
1812− v .:? "key_as_string" <*>
1813− v .: "doc_count" <*>
1814− v .:? "aggregations"
1815− parseJSON _ = mempty
1816−
1817−instance FromJSON DateRangeResult where
1818− parseJSON = withObject "DateRangeResult" parse
1819− where parse v = DateRangeResult <$>
1820− v .: "key" <*>
1821− (fmap posixMS <$> v .:? "from") <*>
1822− v .:? "from_as_string" <*>
1823− (fmap posixMS <$> v .:? "to") <*>
1824− v .:? "to_as_string" <*>
1825− v .: "doc_count" <*>
1826− v .:? "aggregations"
1827−
1828−instance FromJSON POSIXMS where
1829− parseJSON = withScientific "POSIXMS" (return . parse)
1830− where parse n = let n' = truncate n :: Integer
1831− in POSIXMS (posixSecondsToUTCTime (fromInteger (n' `div` 1000)))
1832−
1833−instance Monoid Filter where
1834− mempty = IdentityFilter
1835− mappend a b = AndFilter [a, b] defaultCache
1836−
1837−instance Seminearring Filter where
1838− a <||> b = OrFilter [a, b] defaultCache
1839−
1840−instance ToJSON Filter where
1841− toJSON (AndFilter filters cache) =
1842− object ["and" .=
1843− object [ "filters" .= fmap toJSON filters
1844− , "_cache" .= cache]]
1845−
1846− toJSON (OrFilter filters cache) =
1847− object ["or" .=
1848− object [ "filters" .= fmap toJSON filters
1849− , "_cache" .= cache]]
1850−
1851− toJSON (NotFilter notFilter cache) =
1852− object ["not" .=
1853− object ["filter" .= notFilter
1854− , "_cache" .= cache]]
1855−
1856− toJSON (IdentityFilter) =
1857− object ["match_all" .= object []]
1858−
1859− toJSON (TermFilter (Term termFilterField termFilterValue) cache) =
1860− object ["term" .= object base]
1861− where base = [termFilterField .= termFilterValue,
1862− "_cache" .= cache]
1863−
1864− toJSON (ExistsFilter (FieldName fieldName)) =
1865− object ["exists" .= object
1866− ["field" .= fieldName]]
1867−
1868− toJSON (BoolFilter boolMatch) =
1869− object ["bool" .= boolMatch]
1870−
1871− toJSON (GeoBoundingBoxFilter bbConstraint) =
1872− object ["geo_bounding_box" .= bbConstraint]
1873−
1874− toJSON (GeoDistanceFilter (GeoPoint (FieldName distanceGeoField) geoDistLatLon)
1875− distance distanceType optimizeBbox cache) =
1876− object ["geo_distance" .=
1877− object ["distance" .= distance
1878− , "distance_type" .= distanceType
1879− , "optimize_bbox" .= optimizeBbox
1880− , distanceGeoField .= geoDistLatLon
1881− , "_cache" .= cache]]
1882−
1883− toJSON (GeoDistanceRangeFilter (GeoPoint (FieldName gddrField) drLatLon)
1884− (DistanceRange geoDistRangeDistFrom drDistanceTo)) =
1885− object ["geo_distance_range" .=
1886− object ["from" .= geoDistRangeDistFrom
1887− , "to" .= drDistanceTo
1888− , gddrField .= drLatLon]]
1889−
1890− toJSON (GeoPolygonFilter (FieldName geoPolygonFilterField) latLons) =
1891− object ["geo_polygon" .=
1892− object [geoPolygonFilterField .=
1893− object ["points" .= fmap toJSON latLons]]]
1894−
1895− toJSON (IdsFilter (MappingName mappingName) values) =
1896− object ["ids" .=
1897− object ["type" .= mappingName
1898− , "values" .= fmap unpackId values]]
1899−
1900− toJSON (LimitFilter limit) =
1901− object ["limit" .= object ["value" .= limit]]
1902−
1903− toJSON (MissingFilter (FieldName fieldName) (Existence existence) (NullValue nullValue)) =
1904− object ["missing" .=
1905− object ["field" .= fieldName
1906− , "existence" .= existence
1907− , "null_value" .= nullValue]]
1908−
1909− toJSON (PrefixFilter (FieldName fieldName) fieldValue cache) =
1910− object ["prefix" .=
1911− object [fieldName .= fieldValue
1912− , "_cache" .= cache]]
1913−
1914− toJSON (QueryFilter query False) =
1915− object ["query" .= toJSON query ]
1916− toJSON (QueryFilter query True) =
1917− object ["fquery" .=
1918− object [ "query" .= toJSON query
1919− , "_cache" .= True ]]
1920−
1921− toJSON (RangeFilter (FieldName fieldName) rangeValue rangeExecution cache) =
1922− object ["range" .=
1923− object [ fieldName .= object (rangeValueToPair rangeValue)
1924− , "execution" .= rangeExecution
1925− , "_cache" .= cache]]
1926−
1927− toJSON (RegexpFilter (FieldName fieldName)
1928− (Regexp regexText) flags (CacheName cacheName) cache (CacheKey cacheKey)) =
1929− object ["regexp" .=
1930− object [fieldName .=
1931− object ["value" .= regexText
1932− , "flags" .= flags]
1933− , "_name" .= cacheName
1934− , "_cache" .= cache
1935− , "_cache_key" .= cacheKey]]
1936−
1937−instance FromJSON Filter where
1938− parseJSON = withObject "Filter" parse
1939− where parse o = andFilter `taggedWith` "and"
1940− <|> orFilter `taggedWith` "or"
1941− <|> notFilter `taggedWith` "not"
1942− <|> identityFilter `taggedWith` "match_all"
1943− <|> boolFilter `taggedWith` "bool"
1944− <|> existsFilter `taggedWith` "exists"
1945− <|> geoBoundingBoxFilter `taggedWith` "geo_bounding_box"
1946− <|> geoDistanceFilter `taggedWith` "geo_distance"
1947− <|> geoDistanceRangeFilter `taggedWith` "geo_distance_range"
1948− <|> geoPolygonFilter `taggedWith` "geo_polygon"
1949− <|> idsFilter `taggedWith` "ids"
1950− <|> limitFilter `taggedWith` "limit"
1951− <|> missingFilter `taggedWith` "missing"
1952− <|> prefixFilter `taggedWith` "prefix"
1953− <|> queryFilter `taggedWith` "query"
1954− <|> fqueryFilter `taggedWith` "fquery"
1955− <|> rangeFilter `taggedWith` "range"
1956− <|> regexpFilter `taggedWith` "regexp"
1957− <|> termFilter `taggedWith` "term"
1958− where taggedWith parser k = parser =<< o .: k
1959− andFilter o = AndFilter <$> o .: "filters"
1960− <*> o .:? "_cache" .!= defaultCache
1961− orFilter o = OrFilter <$> o .: "filters"
1962− <*> o .:? "_cache" .!= defaultCache
1963− notFilter o = NotFilter <$> o .: "filter"
1964− <*> o .: "_cache" .!= defaultCache
1965− identityFilter :: Object -> Parser Filter
1966− identityFilter m
1967− | HM.null m = pure IdentityFilter
1968− | otherwise = fail ("Identityfilter expected empty object but got " <> show m)
1969− boolFilter = pure . BoolFilter
1970− existsFilter o = ExistsFilter <$> o .: "field"
1971− geoBoundingBoxFilter = pure . GeoBoundingBoxFilter
1972− geoDistanceFilter o = do
1973− case HM.toList (deleteSeveral ["distance", "distance_type", "optimize_bbox", "_cache"] o) of
1974− [(fn, v)] -> do
1975− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1976− GeoDistanceFilter gp <$> o .: "distance"
1977− <*> o .: "distance_type"
1978− <*> o .: "optimize_bbox"
1979− <*> o .:? "_cache" .!= defaultCache
1980− _ -> fail "Could not find GeoDistanceFilter field name"
1981− geoDistanceRangeFilter o = do
1982− case HM.toList (deleteSeveral ["from", "to"] o) of
1983− [(fn, v)] -> do
1984− gp <- GeoPoint (FieldName fn) <$> parseJSON v
1985− rng <- DistanceRange <$> o .: "from" <*> o .: "to"
1986− return (GeoDistanceRangeFilter gp rng)
1987− _ -> fail "Could not find GeoDistanceRangeFilter field name"
1988− geoPolygonFilter = fieldTagged $ \fn o -> GeoPolygonFilter fn <$> o .: "points"
1989− idsFilter o = IdsFilter <$> o .: "type"
1990− <*> o .: "values"
1991− limitFilter o = LimitFilter <$> o .: "value"
1992− missingFilter o = MissingFilter <$> o .: "field"
1993− <*> o .: "existence"
1994− <*> o .: "null_value"
1995− prefixFilter o = case HM.toList (HM.delete "_cache" o) of
1996− [(fn, String v)] -> PrefixFilter (FieldName fn) v <$> o .:? "_cache" .!= defaultCache
1997− _ -> fail "Could not parse PrefixFilter"
1998−
1999− queryFilter q = pure (QueryFilter q False)
2000− fqueryFilter o = QueryFilter <$> o .: "query" <*> pure True
2001− rangeFilter o = case HM.toList (deleteSeveral ["execution", "_cache"] o) of
2002− [(fn, v)] -> RangeFilter (FieldName fn)
2003− <$> parseJSON v
2004− <*> o .: "execution"
2005− <*> o .:? "_cache" .!= defaultCache
2006− _ -> fail "Could not find field name for RangeFilter"
2007− regexpFilter o = case HM.toList (deleteSeveral ["_name", "_cache", "_cache_key"] o) of
2008− [(fn, Object o')] -> RegexpFilter (FieldName fn)
2009− <$> o' .: "value"
2010− <*> o' .: "flags"
2011− <*> o .: "_name"
2012− <*> o .:? "_cache" .!= defaultCache
2013− <*> o .: "_cache_key"
2014− _ -> fail "Could not find field name for RegexpFilter"
2015− termFilter o = case HM.toList (HM.delete "_cache" o) of
2016− [(termField, String termVal)] -> TermFilter (Term termField termVal)
2017− <$> o .:? "_cache" .!= defaultCache
2018− _ -> fail "Could not find term field for TermFilter"
2019−
2020−fieldTagged :: Monad m => (FieldName -> Object -> m a) -> Object -> m a
2021−fieldTagged f o = case HM.toList o of
2022− [(k, Object o')] -> f (FieldName k) o'
2023− _ -> fail "Expected object with 1 field-named key"
2024−
2025−instance ToJSON GeoPoint where
2026− toJSON (GeoPoint (FieldName geoPointField) geoPointLatLon) =
2027− object [ geoPointField .= geoPointLatLon ]
2028−
2029−
2030−instance ToJSON Query where
2031− toJSON (TermQuery (Term termQueryField termQueryValue) boost) =
2032− object [ "term" .=
2033− object [termQueryField .= object merged]]
2034− where
2035− base = [ "value" .= termQueryValue ]
2036− boosted = maybe [] (return . ("boost" .=)) boost
2037− merged = mappend base boosted
2038−
2039− toJSON (TermsQuery fieldName terms) =
2040− object [ "terms" .= object conjoined ]
2041− where conjoined = [fieldName .= terms]
2042− toJSON (IdsQuery idsQueryMappingName docIds) =
2043− object [ "ids" .= object conjoined ]
2044− where conjoined = [ "type" .= idsQueryMappingName
2045− , "values" .= fmap toJSON docIds ]
2046−
2047− toJSON (QueryQueryStringQuery qQueryStringQuery) =
2048− object [ "query_string" .= qQueryStringQuery ]
2049−
2050− toJSON (QueryMatchQuery matchQuery) =
2051− object [ "match" .= matchQuery ]
2052−
2053− toJSON (QueryMultiMatchQuery multiMatchQuery) =
2054− toJSON multiMatchQuery
2055−
2056− toJSON (QueryBoolQuery boolQuery) =
2057− object [ "bool" .= boolQuery ]
2058−
2059− toJSON (QueryBoostingQuery boostingQuery) =
2060− object [ "boosting" .= boostingQuery ]
2061−
2062− toJSON (QueryCommonTermsQuery commonTermsQuery) =
2063− object [ "common" .= commonTermsQuery ]
2064−
2065− toJSON (ConstantScoreFilter csFilter boost) =
2066− object ["constant_score" .= object ["filter" .= csFilter
2067− , "boost" .= boost]]
2068−
2069− toJSON (ConstantScoreQuery query boost) =
2070− object ["constant_score" .= object ["query" .= query
2071− , "boost" .= boost]]
2072−
2073− toJSON (QueryDisMaxQuery disMaxQuery) =
2074− object [ "dis_max" .= disMaxQuery ]
2075−
2076− toJSON (QueryFilteredQuery qFilteredQuery) =
2077− object [ "filtered" .= qFilteredQuery ]
2078−
2079− toJSON (QueryFuzzyLikeThisQuery fuzzyQuery) =
2080− object [ "fuzzy_like_this" .= fuzzyQuery ]
2081−
2082− toJSON (QueryFuzzyLikeFieldQuery fuzzyFieldQuery) =
2083− object [ "fuzzy_like_this_field" .= fuzzyFieldQuery ]
2084−
2085− toJSON (QueryFuzzyQuery fuzzyQuery) =
2086− object [ "fuzzy" .= fuzzyQuery ]
2087−
2088− toJSON (QueryHasChildQuery childQuery) =
2089− object [ "has_child" .= childQuery ]
2090−
2091− toJSON (QueryHasParentQuery parentQuery) =
2092− object [ "has_parent" .= parentQuery ]
2093−
2094− toJSON (QueryIndicesQuery qIndicesQuery) =
2095− object [ "indices" .= qIndicesQuery ]
2096−
2097− toJSON (MatchAllQuery boost) =
2098− object [ "match_all" .= omitNulls [ "boost" .= boost ] ]
2099−
2100− toJSON (QueryMoreLikeThisQuery query) =
2101− object [ "more_like_this" .= query ]
2102−
2103− toJSON (QueryMoreLikeThisFieldQuery query) =
2104− object [ "more_like_this_field" .= query ]
2105−
2106− toJSON (QueryNestedQuery query) =
2107− object [ "nested" .= query ]
2108−
2109− toJSON (QueryPrefixQuery query) =
2110− object [ "prefix" .= query ]
2111−
2112− toJSON (QueryRangeQuery query) =
2113− object [ "range" .= query ]
2114−
2115− toJSON (QueryRegexpQuery query) =
2116− object [ "regexp" .= query ]
2117−
2118− toJSON (QuerySimpleQueryStringQuery query) =
2119− object [ "simple_query_string" .= query ]
2120−
2121−instance FromJSON Query where
2122− parseJSON v = withObject "Query" parse v
2123− where parse o = termQuery `taggedWith` "term"
2124− <|> termsQuery `taggedWith` "terms"
2125− <|> idsQuery `taggedWith` "ids"
2126− <|> queryQueryStringQuery `taggedWith` "query_string"
2127− <|> queryMatchQuery `taggedWith` "match"
2128− <|> queryMultiMatchQuery
2129− <|> queryBoolQuery `taggedWith` "bool"
2130− <|> queryBoostingQuery `taggedWith` "boosting"
2131− <|> queryCommonTermsQuery `taggedWith` "common"
2132− <|> constantScoreFilter `taggedWith` "constant_score"
2133− <|> constantScoreQuery `taggedWith` "constant_score"
2134− <|> queryDisMaxQuery `taggedWith` "dis_max"
2135− <|> queryFilteredQuery `taggedWith` "filtered"
2136− <|> queryFuzzyLikeThisQuery `taggedWith` "fuzzy_like_this"
2137− <|> queryFuzzyLikeFieldQuery `taggedWith` "fuzzy_like_this_field"
2138− <|> queryFuzzyQuery `taggedWith` "fuzzy"
2139− <|> queryHasChildQuery `taggedWith` "has_child"
2140− <|> queryHasParentQuery `taggedWith` "has_parent"
2141− <|> queryIndicesQuery `taggedWith` "indices"
2142− <|> matchAllQuery `taggedWith` "match_all"
2143− <|> queryMoreLikeThisQuery `taggedWith` "more_like_this"
2144− <|> queryMoreLikeThisFieldQuery `taggedWith` "more_like_this_field"
2145− <|> queryNestedQuery `taggedWith` "nested"
2146− <|> queryPrefixQuery `taggedWith` "prefix"
2147− <|> queryRangeQuery `taggedWith` "range"
2148− <|> queryRegexpQuery `taggedWith` "regexp"
2149− <|> querySimpleQueryStringQuery `taggedWith` "simple_query_string"
2150− where taggedWith parser k = parser =<< o .: k
2151− termQuery = fieldTagged $ \(FieldName fn) o ->
2152− TermQuery <$> (Term fn <$> o .: "value") <*> o .:? "boost"
2153− termsQuery o = case HM.toList o of
2154− [(fn, vs)] -> do vals <- parseJSON vs
2155− case vals of
2156− x:xs -> return (TermsQuery fn (x :| xs))
2157− _ -> fail "Expected non empty list of values"
2158− _ -> fail "Expected object with 1 field-named key"
2159− idsQuery o = IdsQuery <$> o .: "type"
2160− <*> o .: "values"
2161− queryQueryStringQuery = pure . QueryQueryStringQuery
2162− queryMatchQuery = pure . QueryMatchQuery
2163− queryMultiMatchQuery = QueryMultiMatchQuery <$> parseJSON v
2164− queryBoolQuery = pure . QueryBoolQuery
2165− queryBoostingQuery = pure . QueryBoostingQuery
2166− queryCommonTermsQuery = pure . QueryCommonTermsQuery
2167− constantScoreFilter o = case HM.lookup "filter" o of
2168− Just x -> ConstantScoreFilter <$> parseJSON x
2169− <*> o .: "boost"
2170− _ -> fail "Does not appear to be a ConstantScoreFilter"
2171− constantScoreQuery o = case HM.lookup "query" o of
2172− Just x -> ConstantScoreQuery <$> parseJSON x
2173− <*> o .: "boost"
2174− _ -> fail "Does not appear to be a ConstantScoreQuery"
2175− queryDisMaxQuery = pure . QueryDisMaxQuery
2176− queryFilteredQuery = pure . QueryFilteredQuery
2177− queryFuzzyLikeThisQuery = pure . QueryFuzzyLikeThisQuery
2178− queryFuzzyLikeFieldQuery = pure . QueryFuzzyLikeFieldQuery
2179− queryFuzzyQuery = pure . QueryFuzzyQuery
2180− queryHasChildQuery = pure . QueryHasChildQuery
2181− queryHasParentQuery = pure . QueryHasParentQuery
2182− queryIndicesQuery = pure . QueryIndicesQuery
2183− matchAllQuery o = MatchAllQuery <$> o .:? "boost"
2184− queryMoreLikeThisQuery = pure . QueryMoreLikeThisQuery
2185− queryMoreLikeThisFieldQuery = pure . QueryMoreLikeThisFieldQuery
2186− queryNestedQuery = pure . QueryNestedQuery
2187− queryPrefixQuery = pure . QueryPrefixQuery
2188− queryRangeQuery = pure . QueryRangeQuery
2189− queryRegexpQuery = pure . QueryRegexpQuery
2190− querySimpleQueryStringQuery = pure . QuerySimpleQueryStringQuery
2191−
2192−
2193−omitNulls :: [(Text, Value)] -> Value
2194−omitNulls = object . filter notNull where
2195− notNull (_, Null) = False
2196− notNull (_, Array a) = (not . V.null) a
2197− notNull _ = True
2198−
2199−
2200−instance ToJSON SimpleQueryStringQuery where
2201− toJSON SimpleQueryStringQuery {..} =
2202− omitNulls (base ++ maybeAdd)
2203− where base = [ "query" .= simpleQueryStringQuery ]
2204− maybeAdd = [ "fields" .= simpleQueryStringField
2205− , "default_operator" .= simpleQueryStringOperator
2206− , "analyzer" .= simpleQueryStringAnalyzer
2207− , "flags" .= simpleQueryStringFlags
2208− , "lowercase_expanded_terms" .= simpleQueryStringLowercaseExpanded
2209− , "locale" .= simpleQueryStringLocale ]
2210−
2211−instance FromJSON SimpleQueryStringQuery where
2212− parseJSON = withObject "SimpleQueryStringQuery" parse
2213− where parse o = SimpleQueryStringQuery <$> o .: "query"
2214− <*> o .:? "fields"
2215− <*> o .:? "default_operator"
2216− <*> o .:? "analyzer"
2217− <*> (parseFlags <$> o .:? "flags")
2218− <*> o .:? "lowercase_expanded_terms"
2219− <*> o .:? "locale"
2220− parseFlags (Just (x:xs)) = Just (x :| xs)
2221− parseFlags _ = Nothing
2222−
2223−instance ToJSON FieldOrFields where
2224− toJSON (FofField fieldName) =
2225− toJSON fieldName
2226− toJSON (FofFields fieldNames) =
2227− toJSON fieldNames
2228−
2229−instance FromJSON FieldOrFields where
2230− parseJSON v = FofField <$> parseJSON v
2231− <|> FofFields <$> (parseNEJSON =<< parseJSON v)
2232−
2233−instance ToJSON SimpleQueryFlag where
2234− toJSON SimpleQueryAll = "ALL"
2235− toJSON SimpleQueryNone = "NONE"
2236− toJSON SimpleQueryAnd = "AND"
2237− toJSON SimpleQueryOr = "OR"
2238− toJSON SimpleQueryPrefix = "PREFIX"
2239− toJSON SimpleQueryPhrase = "PHRASE"
2240− toJSON SimpleQueryPrecedence = "PRECEDENCE"
2241− toJSON SimpleQueryEscape = "ESCAPE"
2242− toJSON SimpleQueryWhitespace = "WHITESPACE"
2243− toJSON SimpleQueryFuzzy = "FUZZY"
2244− toJSON SimpleQueryNear = "NEAR"
2245− toJSON SimpleQuerySlop = "SLOP"
2246−
2247−instance FromJSON SimpleQueryFlag where
2248− parseJSON = withText "SimpleQueryFlag" parse
2249− where parse "ALL" = pure SimpleQueryAll
2250− parse "NONE" = pure SimpleQueryNone
2251− parse "AND" = pure SimpleQueryAnd
2252− parse "OR" = pure SimpleQueryOr
2253− parse "PREFIX" = pure SimpleQueryPrefix
2254− parse "PHRASE" = pure SimpleQueryPhrase
2255− parse "PRECEDENCE" = pure SimpleQueryPrecedence
2256− parse "ESCAPE" = pure SimpleQueryEscape
2257− parse "WHITESPACE" = pure SimpleQueryWhitespace
2258− parse "FUZZY" = pure SimpleQueryFuzzy
2259− parse "NEAR" = pure SimpleQueryNear
2260− parse "SLOP" = pure SimpleQuerySlop
2261− parse f = fail ("Unexpected SimpleQueryFlag: " <> show f)
2262−
2263−instance ToJSON RegexpQuery where
2264− toJSON (RegexpQuery (FieldName rqQueryField)
2265− (Regexp regexpQueryQuery) rqQueryFlags
2266− rqQueryBoost) =
2267− object [ rqQueryField .= omitNulls base ]
2268− where base = [ "value" .= regexpQueryQuery
2269− , "flags" .= rqQueryFlags
2270− , "boost" .= rqQueryBoost ]
2271−
2272−instance FromJSON RegexpQuery where
2273− parseJSON = withObject "RegexpQuery" parse
2274− where parse = fieldTagged $ \fn o ->
2275− RegexpQuery fn
2276− <$> o .: "value"
2277− <*> o .: "flags"
2278− <*> o .:? "boost"
2279−
2280−instance ToJSON QueryStringQuery where
2281− toJSON (QueryStringQuery qsQueryString
2282− qsDefaultField qsOperator
2283− qsAnalyzer qsAllowWildcard
2284− qsLowercaseExpanded qsEnablePositionIncrements
2285− qsFuzzyMaxExpansions qsFuzziness
2286− qsFuzzyPrefixLength qsPhraseSlop
2287− qsBoost qsAnalyzeWildcard
2288− qsGeneratePhraseQueries qsMinimumShouldMatch
2289− qsLenient qsLocale) =
2290− omitNulls base
2291− where
2292− base = [ "query" .= qsQueryString
2293− , "default_field" .= qsDefaultField
2294− , "default_operator" .= qsOperator
2295− , "analyzer" .= qsAnalyzer
2296− , "allow_leading_wildcard" .= qsAllowWildcard
2297− , "lowercase_expanded_terms" .= qsLowercaseExpanded
2298− , "enable_position_increments" .= qsEnablePositionIncrements
2299− , "fuzzy_max_expansions" .= qsFuzzyMaxExpansions
2300− , "fuzziness" .= qsFuzziness
2301− , "fuzzy_prefix_length" .= qsFuzzyPrefixLength
2302− , "phrase_slop" .= qsPhraseSlop
2303− , "boost" .= qsBoost
2304− , "analyze_wildcard" .= qsAnalyzeWildcard
2305− , "auto_generate_phrase_queries" .= qsGeneratePhraseQueries
2306− , "minimum_should_match" .= qsMinimumShouldMatch
2307− , "lenient" .= qsLenient
2308− , "locale" .= qsLocale ]
2309−
2310−instance FromJSON QueryStringQuery where
2311− parseJSON = withObject "QueryStringQuery" parse
2312− where parse o = QueryStringQuery
2313− <$> o .: "query"
2314− <*> o .:? "default_field"
2315− <*> o .:? "default_operator"
2316− <*> o .:? "analyzer"
2317− <*> o .:? "allow_leading_wildcard"
2318− <*> o .:? "lowercase_expanded_terms"
2319− <*> o .:? "enable_position_increments"
2320− <*> o .:? "fuzzy_max_expansions"
2321− <*> o .:? "fuzziness"
2322− <*> o .:? "fuzzy_prefix_length"
2323− <*> o .:? "phrase_slop"
2324− <*> o .:? "boost"
2325− <*> o .:? "analyze_wildcard"
2326− <*> o .:? "auto_generate_phrase_queries"
2327− <*> o .:? "minimum_should_match"
2328− <*> o .:? "lenient"
2329− <*> o .:? "locale"
2330−
2331−instance ToJSON RangeQuery where
2332− toJSON (RangeQuery (FieldName fieldName) range boost) =
2333− object [ fieldName .= object conjoined ]
2334− where conjoined = [ "boost" .= boost ] ++ (rangeValueToPair range)
2335−
2336−instance FromJSON RangeQuery where
2337− parseJSON = withObject "RangeQuery" parse
2338− where parse = fieldTagged $ \fn o ->
2339− RangeQuery fn
2340− <$> parseJSON (Object o)
2341− <*> o .: "boost"
2342−
2343−instance FromJSON RangeValue where
2344− parseJSON = withObject "RangeValue" parse
2345− where parse o = parseDate o
2346− <|> parseDouble o
2347− parseDate o = do lt <- o .:? "lt"
2348− lte <- o .:? "lte"
2349− gt <- o .:? "gt"
2350− gte <- o .:? "gte"
2351− case (lt, lte, gt, gte) of
2352− (Just a, _, Just b, _) -> return (RangeDateGtLt (GreaterThanD b) (LessThanD a))
2353− (Just a, _, _, Just b)-> return (RangeDateGteLt (GreaterThanEqD b) (LessThanD a))
2354− (_, Just a, Just b, _)-> return (RangeDateGtLte (GreaterThanD b) (LessThanEqD a))
2355− (_, Just a, _, Just b)-> return (RangeDateGteLte (GreaterThanEqD b) (LessThanEqD a))
2356− (_, _, Just a, _)-> return (RangeDateGt (GreaterThanD a))
2357− (Just a, _, _, _)-> return (RangeDateLt (LessThanD a))
2358− (_, _, _, Just a)-> return (RangeDateGte (GreaterThanEqD a))
2359− (_, Just a, _, _)-> return (RangeDateLte (LessThanEqD a))
2360− (Nothing, Nothing, Nothing, Nothing) -> mzero
2361− parseDouble o = do lt <- o .:? "lt"
2362− lte <- o .:? "lte"
2363− gt <- o .:? "gt"
2364− gte <- o .:? "gte"
2365− case (lt, lte, gt, gte) of
2366− (Just a, _, Just b, _) -> return (RangeDoubleGtLt (GreaterThan b) (LessThan a))
2367− (Just a, _, _, Just b)-> return (RangeDoubleGteLt (GreaterThanEq b) (LessThan a))
2368− (_, Just a, Just b, _)-> return (RangeDoubleGtLte (GreaterThan b) (LessThanEq a))
2369− (_, Just a, _, Just b)-> return (RangeDoubleGteLte (GreaterThanEq b) (LessThanEq a))
2370− (_, _, Just a, _)-> return (RangeDoubleGt (GreaterThan a))
2371− (Just a, _, _, _)-> return (RangeDoubleLt (LessThan a))
2372− (_, _, _, Just a)-> return (RangeDoubleGte (GreaterThanEq a))
2373− (_, Just a, _, _)-> return (RangeDoubleLte (LessThanEq a))
2374− (Nothing, Nothing, Nothing, Nothing) -> mzero
2375−
2376−instance ToJSON PrefixQuery where
2377− toJSON (PrefixQuery (FieldName fieldName) queryValue boost) =
2378− object [ fieldName .= omitNulls base ]
2379− where base = [ "value" .= queryValue
2380− , "boost" .= boost ]
2381−
2382−instance FromJSON PrefixQuery where
2383− parseJSON = withObject "PrefixQuery" parse
2384− where parse = fieldTagged $ \fn o ->
2385− PrefixQuery fn
2386− <$> o .: "value"
2387− <*> o .:? "boost"
2388−
2389−instance ToJSON NestedQuery where
2390− toJSON (NestedQuery nqPath nqScoreType nqQuery) =
2391− object [ "path" .= nqPath
2392− , "score_mode" .= nqScoreType
2393− , "query" .= nqQuery ]
2394−
2395−instance FromJSON NestedQuery where
2396− parseJSON = withObject "NestedQuery" parse
2397− where parse o = NestedQuery
2398− <$> o .: "path"
2399− <*> o .: "score_mode"
2400− <*> o .: "query"
2401−
2402−instance ToJSON MoreLikeThisFieldQuery where
2403− toJSON (MoreLikeThisFieldQuery text (FieldName fieldName)
2404− percent mtf mqt stopwords mindf maxdf
2405− minwl maxwl boostTerms boost analyzer) =
2406− object [ fieldName .= omitNulls base ]
2407− where base = [ "like_text" .= text
2408− , "percent_terms_to_match" .= percent
2409− , "min_term_freq" .= mtf
2410− , "max_query_terms" .= mqt
2411− , "stop_words" .= stopwords
2412− , "min_doc_freq" .= mindf
2413− , "max_doc_freq" .= maxdf
2414− , "min_word_length" .= minwl
2415− , "max_word_length" .= maxwl
2416− , "boost_terms" .= boostTerms
2417− , "boost" .= boost
2418− , "analyzer" .= analyzer ]
2419−
2420−instance FromJSON MoreLikeThisFieldQuery where
2421− parseJSON = withObject "MoreLikeThisFieldQuery" parse
2422− where parse = fieldTagged $ \fn o ->
2423− MoreLikeThisFieldQuery
2424− <$> o .: "like_text"
2425− <*> pure fn
2426− <*> o .:? "percent_terms_to_match"
2427− <*> o .:? "min_term_freq"
2428− <*> o .:? "max_query_terms"
2429− <*> (optionalNE =<< o .:? "stop_words")
2430− <*> o .:? "min_doc_freq"
2431− <*> o .:? "max_doc_freq"
2432− <*> o .:? "min_word_length"
2433− <*> o .:? "max_word_length"
2434− <*> o .:? "boost_terms"
2435− <*> o .:? "boost"
2436− <*> o .:? "analyzer"
2437− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2438−
2439−instance ToJSON MoreLikeThisQuery where
2440− toJSON (MoreLikeThisQuery text fields percent
2441− mtf mqt stopwords mindf maxdf
2442− minwl maxwl boostTerms boost analyzer) =
2443− omitNulls base
2444− where base = [ "like_text" .= text
2445− , "fields" .= fields
2446− , "percent_terms_to_match" .= percent
2447− , "min_term_freq" .= mtf
2448− , "max_query_terms" .= mqt
2449− , "stop_words" .= stopwords
2450− , "min_doc_freq" .= mindf
2451− , "max_doc_freq" .= maxdf
2452− , "min_word_length" .= minwl
2453− , "max_word_length" .= maxwl
2454− , "boost_terms" .= boostTerms
2455− , "boost" .= boost
2456− , "analyzer" .= analyzer ]
2457−
2458−instance FromJSON MoreLikeThisQuery where
2459− parseJSON = withObject "MoreLikeThisQuery" parse
2460− where parse o = MoreLikeThisQuery
2461− <$> o .: "like_text"
2462− <*> (optionalNE =<< o .:? "fields")
2463− <*> o .:? "percent_terms_to_match"
2464− <*> o .:? "min_term_freq"
2465− <*> o .:? "max_query_terms"
2466− <*> (optionalNE =<< o .:? "stop_words")
2467− <*> o .:? "min_doc_freq"
2468− <*> o .:? "max_doc_freq"
2469− <*> o .:? "min_word_length"
2470− <*> o .:? "max_word_length"
2471− <*> o .:? "boost_terms"
2472− <*> o .:? "boost"
2473− <*> o .:? "analyzer"
2474− optionalNE = maybe (pure Nothing) (fmap Just . parseNEJSON)
2475−
2476−instance ToJSON IndicesQuery where
2477− toJSON (IndicesQuery indices query noMatch) =
2478− omitNulls [ "indices" .= indices
2479− , "no_match_query" .= noMatch
2480− , "query" .= query ]
2481−
2482−instance FromJSON IndicesQuery where
2483− parseJSON = withObject "IndicesQuery" parse
2484− where parse o = IndicesQuery
2485− <$> o .:? "indices" .!= []
2486− <*> o .: "query"
2487− <*> o .:? "no_match_query"
2488−
2489−instance ToJSON HasParentQuery where
2490− toJSON (HasParentQuery queryType query scoreType) =
2491− omitNulls [ "parent_type" .= queryType
2492− , "score_type" .= scoreType
2493− , "query" .= query ]
2494−
2495−instance FromJSON HasParentQuery where
2496− parseJSON = withObject "HasParentQuery" parse
2497− where parse o = HasParentQuery
2498− <$> o .: "parent_type"
2499− <*> o .: "query"
2500− <*> o .:? "score_type"
2501−
2502−instance ToJSON HasChildQuery where
2503− toJSON (HasChildQuery queryType query scoreType) =
2504− omitNulls [ "query" .= query
2505− , "score_type" .= scoreType
2506− , "type" .= queryType ]
2507−
2508−instance FromJSON HasChildQuery where
2509− parseJSON = withObject "HasChildQuery" parse
2510− where parse o = HasChildQuery
2511− <$> o .: "type"
2512− <*> o .: "query"
2513− <*> o .:? "score_type"
2514−
2515−instance ToJSON FuzzyQuery where
2516− toJSON (FuzzyQuery (FieldName fieldName) queryText
2517− prefixLength maxEx fuzziness boost) =
2518− object [ fieldName .= omitNulls base ]
2519− where base = [ "value" .= queryText
2520− , "fuzziness" .= fuzziness
2521− , "prefix_length" .= prefixLength
2522− , "boost" .= boost
2523− , "max_expansions" .= maxEx ]
2524−
2525−instance FromJSON FuzzyQuery where
2526− parseJSON = withObject "FuzzyQuery" parse
2527− where parse = fieldTagged $ \fn o ->
2528− FuzzyQuery fn
2529− <$> o .: "value"
2530− <*> o .: "prefix_length"
2531− <*> o .: "max_expansions"
2532− <*> o .: "fuzziness"
2533− <*> o .:? "boost"
2534−
2535−instance ToJSON FuzzyLikeFieldQuery where
2536− toJSON (FuzzyLikeFieldQuery (FieldName fieldName)
2537− fieldText maxTerms ignoreFreq fuzziness prefixLength
2538− boost analyzer) =
2539− object [ fieldName .=
2540− omitNulls [ "like_text" .= fieldText
2541− , "max_query_terms" .= maxTerms
2542− , "ignore_tf" .= ignoreFreq
2543− , "fuzziness" .= fuzziness
2544− , "prefix_length" .= prefixLength
2545− , "analyzer" .= analyzer
2546− , "boost" .= boost ]]
2547−
2548−instance FromJSON FuzzyLikeFieldQuery where
2549− parseJSON = withObject "FuzzyLikeFieldQuery" parse
2550− where parse = fieldTagged $ \fn o ->
2551− FuzzyLikeFieldQuery fn
2552− <$> o .: "like_text"
2553− <*> o .: "max_query_terms"
2554− <*> o .: "ignore_tf"
2555− <*> o .: "fuzziness"
2556− <*> o .: "prefix_length"
2557− <*> o .: "boost"
2558− <*> o .:? "analyzer"
2559−
2560−instance ToJSON FuzzyLikeThisQuery where
2561− toJSON (FuzzyLikeThisQuery fields text maxTerms
2562− ignoreFreq fuzziness prefixLength boost analyzer) =
2563− omitNulls base
2564− where base = [ "fields" .= fields
2565− , "like_text" .= text
2566− , "max_query_terms" .= maxTerms
2567− , "ignore_tf" .= ignoreFreq
2568− , "fuzziness" .= fuzziness
2569− , "prefix_length" .= prefixLength
2570− , "analyzer" .= analyzer
2571− , "boost" .= boost ]
2572−
2573−instance FromJSON FuzzyLikeThisQuery where
2574− parseJSON = withObject "FuzzyLikeThisQuery" parse
2575− where parse o = FuzzyLikeThisQuery
2576− <$> o .:? "fields" .!= []
2577− <*> o .: "like_text"
2578− <*> o .: "max_query_terms"
2579− <*> o .: "ignore_tf"
2580− <*> o .: "fuzziness"
2581− <*> o .: "prefix_length"
2582− <*> o .: "boost"
2583− <*> o .:? "analyzer"
2584−
2585−instance ToJSON FilteredQuery where
2586− toJSON (FilteredQuery query fFilter) =
2587− object [ "query" .= query
2588− , "filter" .= fFilter ]
2589−
2590−instance FromJSON FilteredQuery where
2591− parseJSON = withObject "FilteredQuery" parse
2592− where parse o = FilteredQuery
2593− <$> o .: "query"
2594− <*> o .: "filter"
2595−
2596−instance ToJSON DisMaxQuery where
2597− toJSON (DisMaxQuery queries tiebreaker boost) =
2598− omitNulls base
2599− where base = [ "queries" .= queries
2600− , "boost" .= boost
2601− , "tie_breaker" .= tiebreaker ]
2602−
2603−instance FromJSON DisMaxQuery where
2604− parseJSON = withObject "DisMaxQuery" parse
2605− where parse o = DisMaxQuery
2606− <$> o .:? "queries" .!= []
2607− <*> o .: "tie_breaker"
2608− <*> o .:? "boost"
2609−
2610−instance ToJSON CommonTermsQuery where
2611− toJSON (CommonTermsQuery (FieldName fieldName)
2612− (QueryString query) cf lfo hfo msm
2613− boost analyzer disableCoord) =
2614− object [fieldName .= omitNulls base ]
2615− where base = [ "query" .= query
2616− , "cutoff_frequency" .= cf
2617− , "low_freq_operator" .= lfo
2618− , "minimum_should_match" .= msm
2619− , "boost" .= boost
2620− , "analyzer" .= analyzer
2621− , "disable_coord" .= disableCoord
2622− , "high_freq_operator" .= hfo ]
2623−
2624−instance FromJSON CommonTermsQuery where
2625− parseJSON = withObject "CommonTermsQuery" parse
2626− where parse = fieldTagged $ \fn o ->
2627− CommonTermsQuery fn
2628− <$> o .: "query"
2629− <*> o .: "cutoff_frequency"
2630− <*> o .: "low_freq_operator"
2631− <*> o .: "high_freq_operator"
2632− <*> o .:? "minimum_should_match"
2633− <*> o .:? "boost"
2634− <*> o .:? "analyzer"
2635− <*> o .:? "disable_coord"
2636−
2637−instance ToJSON CommonMinimumMatch where
2638− toJSON (CommonMinimumMatch mm) = toJSON mm
2639− toJSON (CommonMinimumMatchHighLow (MinimumMatchHighLow lowF highF)) =
2640− object [ "low_freq" .= lowF
2641− , "high_freq" .= highF ]
2642−
2643−instance FromJSON CommonMinimumMatch where
2644− parseJSON v = parseMinimum v
2645− <|> parseMinimumHighLow v
2646− where parseMinimum = fmap CommonMinimumMatch . parseJSON
2647− parseMinimumHighLow = fmap CommonMinimumMatchHighLow . withObject "CommonMinimumMatchHighLow" (\o ->
2648− MinimumMatchHighLow
2649− <$> o .: "low_freq"
2650− <*> o .: "high_freq")
2651−
2652−
2653−instance ToJSON BoostingQuery where
2654− toJSON (BoostingQuery bqPositiveQuery bqNegativeQuery bqNegativeBoost) =
2655− object [ "positive" .= bqPositiveQuery
2656− , "negative" .= bqNegativeQuery
2657− , "negative_boost" .= bqNegativeBoost ]
2658−
2659−instance FromJSON BoostingQuery where
2660− parseJSON = withObject "BoostingQuery" parse
2661− where parse o = BoostingQuery
2662− <$> o .: "positive"
2663− <*> o .: "negative"
2664− <*> o .: "negative_boost"
2665−
2666−instance ToJSON BoolQuery where
2667− toJSON (BoolQuery mustM notM shouldM bqMin boost disableCoord) =
2668− omitNulls base
2669− where base = [ "must" .= mustM
2670− , "must_not" .= notM
2671− , "should" .= shouldM
2672− , "minimum_should_match" .= bqMin
2673− , "boost" .= boost
2674− , "disable_coord" .= disableCoord ]
2675−
2676−instance FromJSON BoolQuery where
2677− parseJSON = withObject "BoolQuery" parse
2678− where parse o = BoolQuery
2679− <$> o .:? "must" .!= []
2680− <*> o .:? "must_not" .!= []
2681− <*> o .:? "should" .!= []
2682− <*> o .:? "minimum_should_match"
2683− <*> o .:? "boost"
2684− <*> o .:? "disable_coord"
2685−
2686−instance ToJSON MatchQuery where
2687− toJSON (MatchQuery (FieldName fieldName)
2688− (QueryString mqQueryString) booleanOperator
2689− zeroTermsQuery cutoffFrequency matchQueryType
2690− analyzer maxExpansions lenient boost) =
2691− object [ fieldName .= omitNulls base ]
2692− where base = [ "query" .= mqQueryString
2693− , "operator" .= booleanOperator
2694− , "zero_terms_query" .= zeroTermsQuery
2695− , "cutoff_frequency" .= cutoffFrequency
2696− , "type" .= matchQueryType
2697− , "analyzer" .= analyzer
2698− , "max_expansions" .= maxExpansions
2699− , "lenient" .= lenient
2700− , "boost" .= boost ]
2701−
2702−instance FromJSON MatchQuery where
2703− parseJSON = withObject "MatchQuery" parse
2704− where parse = fieldTagged $ \fn o ->
2705− MatchQuery fn
2706− <$> o .: "query"
2707− <*> o .: "operator"
2708− <*> o .: "zero_terms_query"
2709− <*> o .:? "cutoff_frequency"
2710− <*> o .:? "type"
2711− <*> o .:? "analyzer"
2712− <*> o .:? "max_expansions"
2713− <*> o .:? "lenient"
2714− <*> o .:? "boost"
2715−
2716−instance ToJSON MultiMatchQuery where
2717− toJSON (MultiMatchQuery fields (QueryString query) boolOp
2718− ztQ tb mmqt cf analyzer maxEx lenient) =
2719− object ["multi_match" .= omitNulls base]
2720− where base = [ "fields" .= fmap toJSON fields
2721− , "query" .= query
2722− , "operator" .= boolOp
2723− , "zero_terms_query" .= ztQ
2724− , "tiebreaker" .= tb
2725− , "type" .= mmqt
2726− , "cutoff_frequency" .= cf
2727− , "analyzer" .= analyzer
2728− , "max_expansions" .= maxEx
2729− , "lenient" .= lenient ]
2730−
2731−instance FromJSON MultiMatchQuery where
2732− parseJSON = withObject "MultiMatchQuery" parse
2733− where parse raw = do o <- raw .: "multi_match"
2734− MultiMatchQuery
2735− <$> o .:? "fields" .!= []
2736− <*> o .: "query"
2737− <*> o .: "operator"
2738− <*> o .: "zero_terms_query"
2739− <*> o .:? "tiebreaker"
2740− <*> o .:? "type"
2741− <*> o .:? "cutoff_frequency"
2742− <*> o .:? "analyzer"
2743− <*> o .:? "max_expansions"
2744− <*> o .:? "lenient"
2745−
2746−instance ToJSON MultiMatchQueryType where
2747− toJSON MultiMatchBestFields = "best_fields"
2748− toJSON MultiMatchMostFields = "most_fields"
2749− toJSON MultiMatchCrossFields = "cross_fields"
2750− toJSON MultiMatchPhrase = "phrase"
2751− toJSON MultiMatchPhrasePrefix = "phrase_prefix"
2752−
2753−instance FromJSON MultiMatchQueryType where
2754− parseJSON = withText "MultiMatchPhrasePrefix" parse
2755− where parse "best_fields" = pure MultiMatchBestFields
2756− parse "most_fields" = pure MultiMatchMostFields
2757− parse "cross_fields" = pure MultiMatchCrossFields
2758− parse "phrase" = pure MultiMatchPhrase
2759− parse "phrase_prefix" = pure MultiMatchPhrasePrefix
2760− parse t = fail ("Unexpected MultiMatchPhrasePrefix: " <> show t)
2761−
2762−instance ToJSON BooleanOperator where
2763− toJSON And = String "and"
2764− toJSON Or = String "or"
2765−
2766−instance FromJSON BooleanOperator where
2767− parseJSON = withText "BooleanOperator" parse
2768− where parse "and" = pure And
2769− parse "or" = pure Or
2770− parse o = fail ("Unexpected BooleanOperator: " <> show o)
2771−
2772−instance ToJSON ZeroTermsQuery where
2773− toJSON ZeroTermsNone = String "none"
2774− toJSON ZeroTermsAll = String "all"
2775−
2776−instance FromJSON ZeroTermsQuery where
2777− parseJSON = withText "ZeroTermsQuery" parse
2778− where parse "none" = pure ZeroTermsNone
2779− parse "all" = pure ZeroTermsAll
2780− parse q = fail ("Unexpected ZeroTermsQuery: " <> show q)
2781−
2782−instance ToJSON MatchQueryType where
2783− toJSON MatchPhrase = "phrase"
2784− toJSON MatchPhrasePrefix = "phrase_prefix"
2785−
2786−instance FromJSON MatchQueryType where
2787− parseJSON = withText "MatchQueryType" parse
2788− where parse "phrase" = pure MatchPhrase
2789− parse "phrase_prefix" = pure MatchPhrasePrefix
2790− parse t = fail ("Unexpected MatchQueryType: " <> show t)
2791−
2792−instance FromJSON Status where
2793− parseJSON (Object v) = Status <$>
2794− v .:? "ok" <*>
2795− v .: "status" <*>
2796− v .: "name" <*>
2797− v .: "version" <*>
2798− v .: "tagline"
2799− parseJSON _ = empty
2800−
2801−
2802−instance ToJSON IndexSettings where
2803− toJSON (IndexSettings s r) = object ["settings" .=
2804− object ["index" .=
2805− object ["number_of_shards" .= s, "number_of_replicas" .= r]
2806− ]
2807− ]
2808−
2809−instance FromJSON IndexSettings where
2810− parseJSON = withObject "IndexSettings" parse
2811− where parse o = do s <- o .: "settings"
2812− i <- s .: "index"
2813− IndexSettings <$> i .: "number_of_shards"
2814− <*> i .: "number_of_replicas"
2815−
2816−instance ToJSON UpdatableIndexSetting where
2817− toJSON (NumberOfReplicas x) = oPath ("index" :| ["number_of_replicas"]) x
2818− toJSON (AutoExpandReplicas x) = oPath ("index" :| ["auto_expand_replicas"]) x
2819− toJSON (RefreshInterval x) = oPath ("index" :| ["refresh_interval"]) (NominalDiffTimeJSON x)
2820− toJSON (IndexConcurrency x) = oPath ("index" :| ["concurrency"]) x
2821− toJSON (FailOnMergeFailure x) = oPath ("index" :| ["fail_on_merge_failure"]) x
2822− toJSON (TranslogFlushThresholdOps x) = oPath ("index" :| ["translog", "flush_threshold_ops"]) x
2823− toJSON (TranslogFlushThresholdSize x) = oPath ("index" :| ["translog", "flush_threshold_size"]) x
2824− toJSON (TranslogFlushThresholdPeriod x) = oPath ("index" :| ["translog", "flush_threshold_period"]) (NominalDiffTimeJSON x)
2825− toJSON (TranslogDisableFlush x) = oPath ("index" :| ["translog", "disable_flush"]) x
2826− toJSON (CacheFilterMaxSize x) = oPath ("index" :| ["cache", "filter", "max_size"]) x
2827− toJSON (CacheFilterExpire x) = oPath ("index" :| ["cache", "filter", "expire"]) (NominalDiffTimeJSON <$> x)
2828− toJSON (GatewaySnapshotInterval x) = oPath ("index" :| ["gateway", "snapshot_interval"]) (NominalDiffTimeJSON x)
2829− toJSON (RoutingAllocationInclude fs) = oPath ("index" :| ["routing", "allocation", "include"]) (attrFilterJSON fs)
2830− toJSON (RoutingAllocationExclude fs) = oPath ("index" :| ["routing", "allocation", "exclude"]) (attrFilterJSON fs)
2831− toJSON (RoutingAllocationRequire fs) = oPath ("index" :| ["routing", "allocation", "require"]) (attrFilterJSON fs)
2832− toJSON (RoutingAllocationEnable x) = oPath ("index" :| ["routing", "allocation", "enable"]) x
2833− toJSON (RoutingAllocationShardsPerNode x) = oPath ("index" :| ["routing", "allocation", "total_shards_per_node"]) x
2834− toJSON (RecoveryInitialShards x) = oPath ("index" :| ["recovery", "initial_shards"]) x
2835− toJSON (GCDeletes x) = oPath ("index" :| ["gc_deletes"]) (NominalDiffTimeJSON x)
2836− toJSON (TTLDisablePurge x) = oPath ("index" :| ["ttl", "disable_purge"]) x
2837− toJSON (TranslogFSType x) = oPath ("index" :| ["translog", "fs", "type"]) x
2838− toJSON (IndexCompoundFormat x) = oPath ("index" :| ["compound_format"]) x
2839− toJSON (IndexCompoundOnFlush x) = oPath ("index" :| ["compound_on_flush"]) x
2840− toJSON (WarmerEnabled x) = oPath ("index" :| ["warmer", "enabled"]) x
2841− toJSON (BlocksReadOnly x) = oPath ("blocks" :| ["read_only"]) x
2842− toJSON (BlocksRead x) = oPath ("blocks" :| ["read"]) x
2843− toJSON (BlocksWrite x) = oPath ("blocks" :| ["write"]) x
2844− toJSON (BlocksMetaData x) = oPath ("blocks" :| ["metadata"]) x
2845−
2846−instance FromJSON UpdatableIndexSetting where
2847− parseJSON = withObject "UpdatableIndexSetting" parse
2848− where parse o = numberOfReplicas `taggedAt` ["index", "number_of_replicas"]
2849− <|> autoExpandReplicas `taggedAt` ["index", "auto_expand_replicas"]
2850− <|> refreshInterval `taggedAt` ["index", "refresh_interval"]
2851− <|> indexConcurrency `taggedAt` ["index", "concurrency"]
2852− <|> failOnMergeFailure `taggedAt` ["index", "fail_on_merge_failure"]
2853− <|> translogFlushThresholdOps `taggedAt` ["index", "translog", "flush_threshold_ops"]
2854− <|> translogFlushThresholdSize `taggedAt` ["index", "translog", "flush_threshold_size"]
2855− <|> translogFlushThresholdPeriod `taggedAt` ["index", "translog", "flush_threshold_period"]
2856− <|> translogDisableFlush `taggedAt` ["index", "translog", "disable_flush"]
2857− <|> cacheFilterMaxSize `taggedAt` ["index", "cache", "filter", "max_size"]
2858− <|> cacheFilterExpire `taggedAt` ["index", "cache", "filter", "expire"]
2859− <|> gatewaySnapshotInterval `taggedAt` ["index", "gateway", "snapshot_interval"]
2860− <|> routingAllocationInclude `taggedAt` ["index", "routing", "allocation", "include"]
2861− <|> routingAllocationExclude `taggedAt` ["index", "routing", "allocation", "exclude"]
2862− <|> routingAllocationRequire `taggedAt` ["index", "routing", "allocation", "require"]
2863− <|> routingAllocationEnable `taggedAt` ["index", "routing", "allocation", "enable"]
2864− <|> routingAllocationShardsPerNode `taggedAt` ["index", "routing", "allocation", "total_shards_per_node"]
2865− <|> recoveryInitialShards `taggedAt` ["index", "recovery", "initial_shards"]
2866− <|> gcDeletes `taggedAt` ["index", "gc_deletes"]
2867− <|> ttlDisablePurge `taggedAt` ["index", "ttl", "disable_purge"]
2868− <|> translogFSType `taggedAt` ["index", "translog", "fs", "type"]
2869− <|> compoundFormat `taggedAt` ["index", "compound_format"]
2870− <|> compoundOnFlush `taggedAt` ["index", "compound_on_flush"]
2871− <|> warmerEnabled `taggedAt` ["index", "warmer", "enabled"]
2872− <|> blocksReadOnly `taggedAt` ["blocks", "read_only"]
2873− <|> blocksRead `taggedAt` ["blocks", "read"]
2874− <|> blocksWrite `taggedAt` ["blocks", "write"]
2875− <|> blocksMetaData `taggedAt` ["blocks", "metadata"]
2876− where taggedAt f ks = taggedAt' f (Object o) ks
2877− taggedAt' f v [] = f =<< (parseJSON v <|> (parseJSON =<< unStringlyTypeJSON v))
2878− taggedAt' f v (k:ks) = withObject "Object" (\o -> do v' <- o .: k
2879− taggedAt' f v' ks) v
2880− numberOfReplicas = pure . NumberOfReplicas
2881− autoExpandReplicas = pure . AutoExpandReplicas
2882− refreshInterval = pure . RefreshInterval . ndtJSON
2883− indexConcurrency = pure . IndexConcurrency
2884− failOnMergeFailure = pure . FailOnMergeFailure
2885− translogFlushThresholdOps = pure . TranslogFlushThresholdOps
2886− translogFlushThresholdSize = pure . TranslogFlushThresholdSize
2887− translogFlushThresholdPeriod = pure . TranslogFlushThresholdPeriod . ndtJSON
2888− translogDisableFlush = pure . TranslogDisableFlush
2889− cacheFilterMaxSize = pure . CacheFilterMaxSize
2890− cacheFilterExpire = pure . CacheFilterExpire . fmap ndtJSON
2891− gatewaySnapshotInterval = pure . GatewaySnapshotInterval . ndtJSON
2892− routingAllocationInclude = fmap RoutingAllocationInclude . parseAttrFilter
2893− routingAllocationExclude = fmap RoutingAllocationExclude . parseAttrFilter
2894− routingAllocationRequire = fmap RoutingAllocationRequire . parseAttrFilter
2895− routingAllocationEnable = pure . RoutingAllocationEnable
2896− routingAllocationShardsPerNode = pure . RoutingAllocationShardsPerNode
2897− recoveryInitialShards = pure . RecoveryInitialShards
2898− gcDeletes = pure . GCDeletes . ndtJSON
2899− ttlDisablePurge = pure . TTLDisablePurge
2900− translogFSType = pure . TranslogFSType
2901− compoundFormat = pure . IndexCompoundFormat
2902− compoundOnFlush = pure . IndexCompoundOnFlush
2903− warmerEnabled = pure . WarmerEnabled
2904− blocksReadOnly = pure . BlocksReadOnly
2905− blocksRead = pure . BlocksRead
2906− blocksWrite = pure . BlocksWrite
2907− blocksMetaData = pure . BlocksMetaData
2908−
2909−instance FromJSON IndexSettingsSummary where
2910− parseJSON = withObject "IndexSettingsSummary" parse
2911− where parse o = case HM.toList o of
2912− [(ixn, v@(Object o'))] -> IndexSettingsSummary (IndexName ixn)
2913− <$> parseJSON v
2914− <*> (fmap (filter (not . redundant)) . parseSettings =<< o' .: "settings")
2915− _ -> fail "Expected single-key object with index name"
2916− redundant (NumberOfReplicas _) = True
2917− redundant _ = False
2918−
2919−-- | For some reason in the settings API, all leaf values get returned
2920−-- as strings. This function attepmts to recover from this for all
2921−-- non-recursive JSON types. If nothing can be done or the same value
2922−-- would be return, it returns 'mzero'
2923−unStringlyTypeJSON :: MonadPlus m => Value -> m Value
2924−unStringlyTypeJSON (String "true") = return (Bool True)
2925−unStringlyTypeJSON (String "false") = return (Bool False)
2926−unStringlyTypeJSON (String "null") = return Null
2927−unStringlyTypeJSON (String t) = case readMay (T.unpack t) of
2928− Just n -> return (Number n)
2929− Nothing -> mzero
2930−unStringlyTypeJSON _ = mzero
2931−
2932−
2933−parseSettings :: Object -> Parser [UpdatableIndexSetting]
2934−parseSettings o = do
2935− o' <- o .: "index"
2936− -- slice the index object into singleton hashmaps and try to parse each
2937− parses <- forM (HM.toList o') $ \(k, v) -> do
2938− -- blocks are now nested into the "index" key, which is not how they're serialized
2939− let atRoot = Object (HM.singleton k v)
2940− let atIndex = Object (HM.singleton "index" atRoot)
2941− optional (parseJSON atRoot <|> parseJSON atIndex)
2942− return (catMaybes parses)
2943−
2944−oPath :: ToJSON a => NonEmpty Text -> a -> Value
2945−oPath (k :| []) v = object [k .= v]
2946−oPath (k:| (h:t)) v = object [k .= oPath (h :| t) v]
2947−
2948−attrFilterJSON :: NonEmpty NodeAttrFilter -> Value
2949−attrFilterJSON fs = object [ n .= T.intercalate "," (toList vs)
2950− | NodeAttrFilter (NodeAttrName n) vs <- toList fs]
2951−
2952−parseAttrFilter :: Value -> Parser (NonEmpty NodeAttrFilter)
2953−parseAttrFilter = withObject "NonEmpty NodeAttrFilter" parse
2954− where parse o = case HM.toList o of
2955− [] -> fail "Expected non-empty list of NodeAttrFilters"
2956− x:xs -> DT.mapM (uncurry parse') (x :| xs)
2957− parse' n = withText "Text" $ \t ->
2958− case T.splitOn "," t of
2959− fv:fvs -> return (NodeAttrFilter (NodeAttrName n) (fv :| fvs))
2960− [] -> fail "Expected non-empty list of filter values"
2961−
2962−instance ToJSON ReplicaBounds where
2963− toJSON (ReplicasBounded a b) = String (showText a <> "-" <> showText b)
2964− toJSON (ReplicasLowerBounded a) = String (showText a <> "-all")
2965− toJSON ReplicasUnbounded = Bool False
2966−
2967−instance FromJSON ReplicaBounds where
2968− parseJSON v = withText "ReplicaBounds" parseText v
2969− <|> withBool "ReplicaBounds" parseBool v
2970− where parseText t = case T.splitOn "-" t of
2971− [a, "all"] -> ReplicasLowerBounded <$> parseReadText a
2972− [a, b] -> ReplicasBounded <$> parseReadText a
2973− <*> parseReadText b
2974− _ -> fail ("Could not parse ReplicaBounds: " <> show t)
2975− parseBool False = pure ReplicasUnbounded
2976− parseBool _ = fail "ReplicasUnbounded cannot be represented with True"
2977−
2978−instance ToJSON AllocationPolicy where
2979− toJSON AllocAll = String "all"
2980− toJSON AllocPrimaries = String "primaries"
2981− toJSON AllocNewPrimaries = String "new_primaries"
2982− toJSON AllocNone = String "none"
2983−
2984−instance FromJSON AllocationPolicy where
2985− parseJSON = withText "AllocationPolicy" parse
2986− where parse "all" = pure AllocAll
2987− parse "primaries" = pure AllocPrimaries
2988− parse "new_primaries" = pure AllocNewPrimaries
2989− parse "none" = pure AllocNone
2990− parse t = fail ("Invlaid AllocationPolicy: " <> show t)
2991−
2992−instance ToJSON InitialShardCount where
2993− toJSON QuorumShards = String "quorum"
2994− toJSON QuorumMinus1Shards = String "quorum-1"
2995− toJSON FullShards = String "full"
2996− toJSON FullMinus1Shards = String "full-1"
2997− toJSON (ExplicitShards x) = toJSON x
2998−
2999−instance FromJSON InitialShardCount where
3000− parseJSON v = withText "InitialShardCount" parseText v
3001− <|> ExplicitShards <$> parseJSON v
3002− where parseText "quorum" = pure QuorumShards
3003− parseText "quorum-1" = pure QuorumMinus1Shards
3004− parseText "full" = pure FullShards
3005− parseText "full-1" = pure FullMinus1Shards
3006− parseText _ = mzero
3007−
3008−instance ToJSON FSType where
3009− toJSON FSSimple = "simple"
3010− toJSON FSBuffered = "buffered"
3011−
3012−instance FromJSON FSType where
3013− parseJSON = withText "FSType" parse
3014− where parse "simple" = pure FSSimple
3015− parse "buffered" = pure FSBuffered
3016− parse t = fail ("Invalid FSType: " <> show t)
3017−
3018−instance ToJSON CompoundFormat where
3019− toJSON (CompoundFileFormat x) = Bool x
3020− toJSON (MergeSegmentVsTotalIndex x) = toJSON x
3021−
3022−instance FromJSON CompoundFormat where
3023− parseJSON v = CompoundFileFormat <$> parseJSON v
3024− <|> MergeSegmentVsTotalIndex <$> parseJSON v
3025−
3026−instance ToJSON NominalDiffTimeJSON where
3027− toJSON (NominalDiffTimeJSON t) = String (showText (round t :: Integer) <> "s")
3028−
3029−instance FromJSON NominalDiffTimeJSON where
3030− parseJSON = withText "NominalDiffTime" parse
3031− where parse t = case T.takeEnd 1 t of
3032− "s" -> NominalDiffTimeJSON . fromInteger <$> parseReadText (T.dropEnd 1 t)
3033− _ -> fail "Invalid or missing NominalDiffTime unit (expected s)"
3034−
3035−instance ToJSON IndexTemplate where
3036− toJSON (IndexTemplate p s m) = merge
3037− (object [ "template" .= p
3038− , "mappings" .= foldl' merge (object []) m
3039− ])
3040− (toJSON s)
3041− where
3042− merge (Object o1) (Object o2) = toJSON $ HM.union o1 o2
3043− merge o Null = o
3044− merge _ _ = undefined
3045−
3046−instance (FromJSON a) => FromJSON (EsResult a) where
3047− parseJSON jsonVal@(Object v) = do
3048− found <- v .:? "found" .!= False
3049− fr <- if found
3050− then parseJSON jsonVal
3051− else return Nothing
3052− EsResult <$> v .: "_index" <*>
3053− v .: "_type" <*>
3054− v .: "_id" <*>
3055− pure fr
3056− parseJSON _ = empty
3057−
3058−instance (FromJSON a) => FromJSON (EsResultFound a) where
3059− parseJSON (Object v) = EsResultFound <$>
3060− v .: "_version" <*>
3061− v .: "_source"
3062− parseJSON _ = empty
3063−
3064−instance FromJSON EsError where
3065− parseJSON (Object v) = EsError <$>
3066− v .: "status" <*>
3067− v .: "error"
3068− parseJSON _ = empty
3069−
3070−instance FromJSON IndexAliasesSummary where
3071− parseJSON = withObject "IndexAliasesSummary" parse
3072− where parse o = IndexAliasesSummary . mconcat <$> mapM (uncurry go) (HM.toList o)
3073− go ixn = withObject "index aliases" $ \ia -> do
3074− aliases <- ia .:? "aliases" .!= mempty
3075− forM (HM.toList aliases) $ \(aName, v) -> do
3076− let indexAlias = IndexAlias (IndexName ixn) (IndexAliasName (IndexName aName))
3077− IndexAliasSummary indexAlias <$> parseJSON v
3078−
3079−
3080−instance ToJSON IndexAliasAction where
3081− toJSON (AddAlias ia opts) = object ["add" .= (iaObj <> optsObj)]
3082− where Object iaObj = toJSON ia
3083− Object optsObj = toJSON opts
3084− toJSON (RemoveAlias ia) = object ["remove" .= iaObj]
3085− where Object iaObj = toJSON ia
3086−
3087−instance ToJSON IndexAlias where
3088− toJSON IndexAlias {..} = object ["index" .= srcIndex
3089− , "alias" .= indexAlias
3090− ]
3091−
3092−instance ToJSON IndexAliasCreate where
3093− toJSON IndexAliasCreate {..} = Object (filterObj <> routingObj)
3094− where filterObj = maybe mempty (HM.singleton "filter" . toJSON) aliasCreateFilter
3095− Object routingObj = maybe (Object mempty) toJSON aliasCreateRouting
3096−
3097−instance ToJSON AliasRouting where
3098− toJSON (AllAliasRouting v) = object ["routing" .= v]
3099− toJSON (GranularAliasRouting srch idx) = object (catMaybes prs)
3100− where prs = [("search_routing" .=) <$> srch
3101− ,("index_routing" .=) <$> idx]
3102−
3103−instance FromJSON AliasRouting where
3104− parseJSON = withObject "AliasRouting" parse
3105− where parse o = parseAll o <|> parseGranular o
3106− parseAll o = AllAliasRouting <$> o .: "routing"
3107− parseGranular o = do
3108− sr <- o .:? "search_routing"
3109− ir <- o .:? "index_routing"
3110− if isNothing sr && isNothing ir
3111− then fail "Both search_routing and index_routing can't be blank"
3112− else return (GranularAliasRouting sr ir)
3113−
3114−instance FromJSON IndexAliasCreate where
3115− parseJSON v = withObject "IndexAliasCreate" parse v
3116− where parse o = IndexAliasCreate <$> optional (parseJSON v)
3117− <*> o .:? "filter"
3118−
3119−instance ToJSON SearchAliasRouting where
3120− toJSON (SearchAliasRouting rvs) = toJSON (T.intercalate "," (routingValue <$> toList rvs))
3121−
3122−instance FromJSON SearchAliasRouting where
3123− parseJSON = withText "SearchAliasRouting" parse
3124− where parse t = SearchAliasRouting <$> parseNEJSON (String <$> T.splitOn "," t)
3125−
3126−instance ToJSON Search where
3127− toJSON (Search query sFilter sort searchAggs highlight sTrackSortScores sFrom sSize _ sFields sSource) =
3128− omitNulls [ "query" .= query
3129− , "filter" .= sFilter
3130− , "sort" .= sort
3131− , "aggregations" .= searchAggs
3132− , "highlight" .= highlight
3133− , "from" .= sFrom
3134− , "size" .= sSize
3135− , "track_scores" .= sTrackSortScores
3136− , "fields" .= sFields
3137− , "_source" .= sSource]
3138−
3139−
3140−instance ToJSON Source where
3141− toJSON NoSource = toJSON False
3142− toJSON (SourcePatterns patterns) = toJSON patterns
3143− toJSON (SourceIncludeExclude incl excl) = object [ "include" .= incl, "exclude" .= excl ]
3144−
3145−instance ToJSON PatternOrPatterns where
3146− toJSON (PopPattern pattern) = toJSON pattern
3147− toJSON (PopPatterns patterns) = toJSON patterns
3148−
3149−instance ToJSON Include where
3150− toJSON (Include patterns) = toJSON patterns
3151−
3152−instance ToJSON Exclude where
3153− toJSON (Exclude patterns) = toJSON patterns
3154−
3155−instance ToJSON Pattern where
3156− toJSON (Pattern pattern) = toJSON pattern
3157−
3158−
3159−instance ToJSON FieldHighlight where
3160− toJSON (FieldHighlight (FieldName fName) (Just fSettings)) =
3161− object [ fName .= fSettings ]
3162− toJSON (FieldHighlight (FieldName fName) Nothing) =
3163− object [ fName .= emptyObject ]
3164−
3165−instance ToJSON Highlights where
3166− toJSON (Highlights global fields) =
3167− omitNulls (("fields" .= fields)
3168− : highlightSettingsPairs global)
3169−
3170−instance ToJSON HighlightSettings where
3171− toJSON hs = omitNulls (highlightSettingsPairs (Just hs))
3172−
3173−highlightSettingsPairs :: Maybe HighlightSettings -> [Pair]
3174−highlightSettingsPairs Nothing = []
3175−highlightSettingsPairs (Just (Plain plh)) = plainHighPairs (Just plh)
3176−highlightSettingsPairs (Just (Postings ph)) = postHighPairs (Just ph)
3177−highlightSettingsPairs (Just (FastVector fvh)) = fastVectorHighPairs (Just fvh)
3178−
3179−
3180−plainHighPairs :: Maybe PlainHighlight -> [Pair]
3181−plainHighPairs Nothing = []
3182−plainHighPairs (Just (PlainHighlight plCom plNonPost)) =
3183− [ "type" .= String "plain"]
3184− ++ commonHighlightPairs plCom
3185− ++ nonPostingsToPairs plNonPost
3186−
3187−postHighPairs :: Maybe PostingsHighlight -> [Pair]
3188−postHighPairs Nothing = []
3189−postHighPairs (Just (PostingsHighlight pCom)) =
3190− ("type" .= String "postings")
3191− : commonHighlightPairs pCom
3192−
3193−fastVectorHighPairs :: Maybe FastVectorHighlight -> [Pair]
3194−fastVectorHighPairs Nothing = []
3195−fastVectorHighPairs (Just
3196− (FastVectorHighlight fvCom fvNonPostSettings fvBoundChars
3197− fvBoundMaxScan fvFragOff fvMatchedFields
3198− fvPhraseLim)) =
3199− [ "type" .= String "fvh"
3200− , "boundary_chars" .= fvBoundChars
3201− , "boundary_max_scan" .= fvBoundMaxScan
3202− , "fragment_offset" .= fvFragOff
3203− , "matched_fields" .= fvMatchedFields
3204− , "phraseLimit" .= fvPhraseLim]
3205− ++ commonHighlightPairs fvCom
3206− ++ nonPostingsToPairs fvNonPostSettings
3207−
3208−deleteSeveral :: (Eq k, Hashable k) => [k] -> HM.HashMap k v -> HM.HashMap k v
3209−deleteSeveral ks hm = foldr HM.delete hm ks
3210−
3211−commonHighlightPairs :: Maybe CommonHighlight -> [Pair]
3212−commonHighlightPairs Nothing = []
3213−commonHighlightPairs (Just (CommonHighlight chScore chForceSource chTag chEncoder
3214− chNoMatchSize chHighlightQuery
3215− chRequireFieldMatch)) =
3216− [ "order" .= chScore
3217− , "force_source" .= chForceSource
3218− , "encoder" .= chEncoder
3219− , "no_match_size" .= chNoMatchSize
3220− , "highlight_query" .= chHighlightQuery
3221− , "require_fieldMatch" .= chRequireFieldMatch]
3222− ++ highlightTagToPairs chTag
3223−
3224−
3225−nonPostingsToPairs :: Maybe NonPostings -> [Pair]
3226−nonPostingsToPairs Nothing = []
3227−nonPostingsToPairs (Just (NonPostings npFragSize npNumOfFrags)) =
3228− [ "fragment_size" .= npFragSize
3229− , "number_of_fragments" .= npNumOfFrags]
3230−
3231−parseNEJSON :: (FromJSON a) => [Value] -> Parser (NonEmpty a)
3232−parseNEJSON [] = fail "Expected non-empty list"
3233−parseNEJSON (x:xs) = DT.mapM parseJSON (x :| xs)
3234−
3235−
3236−instance ToJSON HighlightEncoder where
3237− toJSON DefaultEncoder = String "default"
3238− toJSON HTMLEncoder = String "html"
3239−
3240−highlightTagToPairs :: Maybe HighlightTag -> [Pair]
3241−highlightTagToPairs (Just (TagSchema _)) = [ "scheme" .= String "default"]
3242−highlightTagToPairs (Just (CustomTags (pre, post))) = [ "pre_tags" .= pre
3243− , "post_tags" .= post]
3244−highlightTagToPairs Nothing = []
3245−
3246−instance ToJSON SortSpec where
3247− toJSON (DefaultSortSpec
3248− (DefaultSort (FieldName dsSortFieldName) dsSortOrder dsIgnoreUnmapped
3249− dsSortMode dsMissingSort dsNestedFilter)) =
3250− object [dsSortFieldName .= omitNulls base] where
3251− base = [ "order" .= dsSortOrder
3252− , "ignore_unmapped" .= dsIgnoreUnmapped
3253− , "mode" .= dsSortMode
3254− , "missing" .= dsMissingSort
3255− , "nested_filter" .= dsNestedFilter ]
3256−
3257− toJSON (GeoDistanceSortSpec gdsSortOrder (GeoPoint (FieldName field) gdsLatLon) units) =
3258− object [ "unit" .= units
3259− , field .= gdsLatLon
3260− , "order" .= gdsSortOrder ]
3261−
3262−
3263−instance ToJSON SortOrder where
3264− toJSON Ascending = String "asc"
3265− toJSON Descending = String "desc"
3266−
3267−
3268−instance ToJSON SortMode where
3269− toJSON SortMin = String "min"
3270− toJSON SortMax = String "max"
3271− toJSON SortSum = String "sum"
3272− toJSON SortAvg = String "avg"
3273−
3274−
3275−instance ToJSON Missing where
3276− toJSON LastMissing = String "_last"
3277− toJSON FirstMissing = String "_first"
3278− toJSON (CustomMissing txt) = String txt
3279−
3280−
3281−instance ToJSON ScoreType where
3282− toJSON ScoreTypeMax = "max"
3283− toJSON ScoreTypeAvg = "avg"
3284− toJSON ScoreTypeSum = "sum"
3285− toJSON ScoreTypeNone = "none"
3286−
3287−instance FromJSON ScoreType where
3288− parseJSON = withText "ScoreType" parse
3289− where parse "max" = pure ScoreTypeMax
3290− parse "avg" = pure ScoreTypeAvg
3291− parse "sum" = pure ScoreTypeSum
3292− parse "none" = pure ScoreTypeNone
3293− parse t = fail ("Unexpected ScoreType: " <> show t)
3294−
3295−instance ToJSON Distance where
3296− toJSON (Distance dCoefficient dUnit) =
3297− String boltedTogether where
3298− coefText = showText dCoefficient
3299− (String unitText) = toJSON dUnit
3300− boltedTogether = mappend coefText unitText
3301−
3302−instance FromJSON Distance where
3303− parseJSON = withText "Distance" parse
3304− where parse t = Distance <$> parseCoeff nT
3305− <*> parseJSON (String unitT)
3306− where (nT, unitT) = T.span validForNumber t
3307− -- may be a better way to do this
3308− validForNumber '-' = True
3309− validForNumber '.' = True
3310− validForNumber 'e' = True
3311− validForNumber c = isNumber c
3312− parseCoeff "" = fail "Empty string cannot be parsed as number"
3313− parseCoeff s = return (read (T.unpack s))
3314−
3315−instance ToJSON DistanceUnit where
3316− toJSON Miles = String "mi"
3317− toJSON Yards = String "yd"
3318− toJSON Feet = String "ft"
3319− toJSON Inches = String "in"
3320− toJSON Kilometers = String "km"
3321− toJSON Meters = String "m"
3322− toJSON Centimeters = String "cm"
3323− toJSON Millimeters = String "mm"
3324− toJSON NauticalMiles = String "nmi"
3325−
3326−
3327−instance FromJSON DistanceUnit where
3328− parseJSON = withText "DistanceUnit" parse
3329− where parse "mi" = pure Miles
3330− parse "yd" = pure Yards
3331− parse "ft" = pure Feet
3332− parse "in" = pure Inches
3333− parse "km" = pure Kilometers
3334− parse "m" = pure Meters
3335− parse "cm" = pure Centimeters
3336− parse "mm" = pure Millimeters
3337− parse "nmi" = pure NauticalMiles
3338− parse u = fail ("Unrecognized DistanceUnit: " <> show u)
3339−
3340−instance ToJSON DistanceType where
3341− toJSON Arc = String "arc"
3342− toJSON SloppyArc = String "sloppy_arc"
3343− toJSON Plane = String "plane"
3344−
3345−instance FromJSON DistanceType where
3346− parseJSON = withText "DistanceType" parse
3347− where parse "arc" = pure Arc
3348− parse "sloppy_arc" = pure SloppyArc
3349− parse "plane" = pure Plane
3350− parse t = fail ("Unrecognized DistanceType: " <> show t)
3351−
3352−
3353−instance ToJSON OptimizeBbox where
3354− toJSON NoOptimizeBbox = String "none"
3355− toJSON (OptimizeGeoFilterType gft) = toJSON gft
3356−
3357−instance FromJSON OptimizeBbox where
3358− parseJSON v = withText "NoOptimizeBbox" parseNoOptimize v
3359− <|> parseOptimize v
3360− where parseNoOptimize "none" = pure NoOptimizeBbox
3361− parseNoOptimize _ = mzero
3362− parseOptimize = fmap OptimizeGeoFilterType . parseJSON
3363−
3364−instance ToJSON GeoBoundingBoxConstraint where
3365− toJSON (GeoBoundingBoxConstraint
3366− (FieldName gbbcGeoBBField) gbbcConstraintBox cache type') =
3367− object [gbbcGeoBBField .= gbbcConstraintBox
3368− , "_cache" .= cache
3369− , "type" .= type']
3370−
3371−instance FromJSON GeoBoundingBoxConstraint where
3372− parseJSON = withObject "GeoBoundingBoxConstraint" parse
3373− where parse o = case HM.toList (deleteSeveral ["type", "_cache"] o) of
3374− [(fn, v)] -> GeoBoundingBoxConstraint (FieldName fn)
3375− <$> parseJSON v
3376− <*> o .:? "_cache" .!= defaultCache
3377− <*> o .: "type"
3378− _ -> fail "Could not find field name for GeoBoundingBoxConstraint"
3379−
3380−instance ToJSON GeoFilterType where
3381− toJSON GeoFilterMemory = String "memory"
3382− toJSON GeoFilterIndexed = String "indexed"
3383−
3384−instance FromJSON GeoFilterType where
3385− parseJSON = withText "GeoFilterType" parse
3386− where parse "memory" = pure GeoFilterMemory
3387− parse "indexed" = pure GeoFilterIndexed
3388− parse t = fail ("Unrecognized GeoFilterType: " <> show t)
3389−
3390−instance ToJSON GeoBoundingBox where
3391− toJSON (GeoBoundingBox gbbTopLeft gbbBottomRight) =
3392− object ["top_left" .= gbbTopLeft
3393− , "bottom_right" .= gbbBottomRight]
3394−
3395−instance FromJSON GeoBoundingBox where
3396− parseJSON = withObject "GeoBoundingBox" parse
3397− where parse o = GeoBoundingBox
3398− <$> o .: "top_left"
3399− <*> o .: "bottom_right"
3400−
3401−instance ToJSON LatLon where
3402− toJSON (LatLon lLat lLon) =
3403− object ["lat" .= lLat
3404− , "lon" .= lLon]
3405−
3406−instance FromJSON LatLon where
3407− parseJSON = withObject "LatLon" parse
3408− where parse o = LatLon <$> o .: "lat"
3409− <*> o .: "lon"
3410−
3411−-- index for smaller ranges, fielddata for longer ranges
3412−instance ToJSON RangeExecution where
3413− toJSON RangeExecutionIndex = "index"
3414− toJSON RangeExecutionFielddata = "fielddata"
3415−
3416−
3417−instance FromJSON RangeExecution where
3418− parseJSON = withText "RangeExecution" parse
3419− where parse "index" = pure RangeExecutionIndex
3420− parse "fielddata" = pure RangeExecutionFielddata
3421− parse t = error ("Unrecognized RangeExecution " <> show t)
3422−
3423−instance ToJSON RegexpFlags where
3424− toJSON AllRegexpFlags = String "ALL"
3425− toJSON NoRegexpFlags = String "NONE"
3426− toJSON (SomeRegexpFlags (h :| fs)) = String $ T.intercalate "|" flagStrs
3427− where flagStrs = map flagStr . nub $ h:fs
3428− flagStr AnyString = "ANYSTRING"
3429− flagStr Automaton = "AUTOMATON"
3430− flagStr Complement = "COMPLEMENT"
3431− flagStr Empty = "EMPTY"
3432− flagStr Intersection = "INTERSECTION"
3433− flagStr Interval = "INTERVAL"
3434−
3435−instance FromJSON RegexpFlags where
3436− parseJSON = withText "RegexpFlags" parse
3437− where parse "ALL" = pure AllRegexpFlags
3438− parse "NONE" = pure NoRegexpFlags
3439− parse t = SomeRegexpFlags <$> parseNEJSON (String <$> T.splitOn "|" t)
3440−
3441−instance FromJSON RegexpFlag where
3442− parseJSON = withText "RegexpFlag" parse
3443− where parse "ANYSTRING" = pure AnyString
3444− parse "AUTOMATON" = pure Automaton
3445− parse "COMPLEMENT" = pure Complement
3446− parse "EMPTY" = pure Empty
3447− parse "INTERSECTION" = pure Intersection
3448− parse "INTERVAL" = pure Interval
3449− parse f = fail ("Unknown RegexpFlag: " <> show f)
3450−
3451−instance ToJSON Term where
3452− toJSON (Term field value) = object ["term" .= object
3453− [field .= value]]
3454−
3455−instance FromJSON Term where
3456− parseJSON = withObject "Term" parse
3457− where parse o = do termObj <- o .: "term"
3458− case HM.toList termObj of
3459− [(fn, v)] -> Term fn <$> parseJSON v
3460− _ -> fail "Expected object with 1 field-named key"
3461−
3462−instance ToJSON BoolMatch where
3463− toJSON (MustMatch term cache) = object ["must" .= term,
3464− "_cache" .= cache]
3465− toJSON (MustNotMatch term cache) = object ["must_not" .= term,
3466− "_cache" .= cache]
3467− toJSON (ShouldMatch terms cache) = object ["should" .= fmap toJSON terms,
3468− "_cache" .= cache]
3469−
3470−instance FromJSON BoolMatch where
3471− parseJSON = withObject "BoolMatch" parse
3472− where parse o = mustMatch `taggedWith` "must"
3473− <|> mustNotMatch `taggedWith` "must_not"
3474− <|> shouldMatch `taggedWith` "should"
3475− where taggedWith parser k = parser =<< o .: k
3476− mustMatch t = MustMatch t <$> o .:? "_cache" .!= defaultCache
3477− mustNotMatch t = MustNotMatch t <$> o .:? "_cache" .!= defaultCache
3478− shouldMatch t = ShouldMatch t <$> o .:? "_cache" .!= defaultCache
522+ , scrollId :: Maybe ScrollId
523+ -- ^ Only one Suggestion request / response per
524+ -- Search is supported.
525+ , suggest :: Maybe NamedSuggestionResponse
526+ }
527+ deriving (Eq, Show)
3479528
3480529instance (FromJSON a) => FromJSON (SearchResult a) where
3481530 parseJSON (Object v) = SearchResult <$>
@@ -3484,71 +533,10 @@ instance (FromJSON a) => FromJSON (SearchResult a) where
3484533 v .: "_shards" <*>
3485534 v .: "hits" <*>
3486535 v .:? "aggregations" <*>
3487− v .:? "_scroll_id"
536+ v .:? "_scroll_id" <*>
537+ v .:? "suggest"
3488538 parseJSON _ = empty
3489539
3490−instance (FromJSON a) => FromJSON (SearchHits a) where
3491− parseJSON (Object v) = SearchHits <$>
3492− v .: "total" <*>
3493− v .: "max_score" <*>
3494− v .: "hits"
3495− parseJSON _ = empty
3496−
3497−instance (FromJSON a) => FromJSON (Hit a) where
3498− parseJSON (Object v) = Hit <$>
3499− v .: "_index" <*>
3500− v .: "_type" <*>
3501− v .: "_id" <*>
3502− v .: "_score" <*>
3503− v .:? "_source" <*>
3504− v .:? "highlight"
3505− parseJSON _ = empty
3506−
3507−instance FromJSON ShardResult where
3508− parseJSON (Object v) = ShardResult <$>
3509− v .: "total" <*>
3510− v .: "successful" <*>
3511− v .: "failed"
3512− parseJSON _ = empty
3513−
3514−
3515−instance FromJSON DocVersion where
3516− parseJSON v = do
3517− i <- parseJSON v
3518− maybe (fail "DocVersion out of range") return $ mkDocVersion i
3519−
3520−-- This insanity is because ES *sometimes* returns Replica/Shard counts as strings
3521−instance FromJSON ReplicaCount where
3522− parseJSON v = parseAsInt v
3523− <|> parseAsString v
3524− where parseAsInt = fmap ReplicaCount . parseJSON
3525− parseAsString = withText "ReplicaCount" (fmap ReplicaCount . parseReadText)
3526−
3527−instance FromJSON ShardCount where
3528− parseJSON v = parseAsInt v
3529− <|> parseAsString v
3530− where parseAsInt = fmap ShardCount . parseJSON
3531− parseAsString = withText "ShardCount" (fmap ShardCount . parseReadText)
3532−
3533−instance Bounded DocVersion where
3534− minBound = DocVersion 1
3535− maxBound = DocVersion 9200000000000000000 -- 9.2e+18
3536−
3537−instance Enum DocVersion where
3538− succ x
3539− | x /= maxBound = DocVersion (succ $ docVersionNumber x)
3540− | otherwise = succError "DocVersion"
3541− pred x
3542− | x /= minBound = DocVersion (pred $ docVersionNumber x)
3543− | otherwise = predError "DocVersion"
3544− toEnum i =
3545− fromMaybe (error $ show i ++ " out of DocVersion range") $ mkDocVersion i
3546− fromEnum = docVersionNumber
3547− enumFrom = boundedEnumFrom
3548− enumFromThen = boundedEnumFromThen
3549−
3550−-- | Username type used for HTTP Basic authentication. See 'basicAuthHook'.
3551−newtype EsUsername = EsUsername { esUsername :: Text } deriving (Show, Eq)
3552−
3553−-- | Password type used for HTTP Basic authentication. See 'basicAuthHook'.
3554−newtype EsPassword = EsPassword { esPassword :: Text } deriving (Show, Eq)
540+newtype ScrollId =
541+ ScrollId Text
542+ deriving (Eq, Show, Ord, ToJSON, FromJSON)