bloodhound-1.0.0.0: Elasticsearch and OpenSearch client library for Haskell
Copyright(C) 2014 2018 Chris Allen
LicenseBSD-style (see the file LICENSE)
MaintainerChris Allen <cma@bitemyapp.com>
Stabilityprovisional
PortabilityGHC
Safe HaskellNone
LanguageGHC2021

Database.Bloodhound.Common.Client

Description

Client side functions for talking to Elasticsearch servers.

Synopsis

Bloodhound client functions

The examples in this module assume the following code has been run. The :{ and :} will only work in GHCi. You'll only need the data types and typeclass instances for the functions that make use of them.

>>> :set -XOverloadedStrings
>>> :set -XDeriveGeneric
>>> import Database.Bloodhound
>>> import Network.HTTP.Client
>>> let testServer = (Server "http://localhost:9200")
>>> let runBH' = withBH defaultManagerSettings testServer
>>> let testIndex = IndexName "twitter"
>>> let defaultIndexSettings = IndexSettings (ShardCount 1) (ReplicaCount 0)
>>> data TweetMapping = TweetMapping deriving stock (Eq, Show)
>>> _ <- runBH' $ deleteIndex testIndex
>>> _ <- runBH' $ deleteIndex (IndexName "didimakeanindex")
>>> import GHC.Generics
>>> import           Data.Time.Calendar        (Day (..))
>>> import Data.Time.Clock (UTCTime (..), secondsToDiffTime)
>>> :{
instance ToJSON TweetMapping where
         toJSON TweetMapping =
           object ["properties" .=
             object ["location" .=
               object ["type" .= ("geo_point" :: Text)]]]
data Location = Location { lat :: Double
                        , lon :: Double } deriving stock (Eq, Generic, Show)
data Tweet = Tweet { user     :: Text
                   , postDate :: UTCTime
                   , message  :: Text
                   , age      :: Int
                   , location :: Location } deriving stock (Eq, Generic, Show)
exampleTweet = Tweet { user     = "bitemyapp"
                     , postDate = UTCTime
                                  (ModifiedJulianDay 55000)
                                  (secondsToDiffTime 10)
                     , message  = "Use haskell!"
                     , age      = 10000
                     , location = Location 40.12 (-71.34) }
instance ToJSON   Tweet where
 toJSON = genericToJSON defaultOptions
instance FromJSON Tweet where
 parseJSON = genericParseJSON defaultOptions
instance ToJSON   Location where
 toJSON = genericToJSON defaultOptions
instance FromJSON Location where
 parseJSON = genericParseJSON defaultOptions
data BulkTest = BulkTest { name :: Text } deriving stock (Eq, Generic, Show)
instance FromJSON BulkTest where
 parseJSON = genericParseJSON defaultOptions
instance ToJSON BulkTest where
 toJSON = genericToJSON defaultOptions
:}

withBH :: ManagerSettings -> Server -> BH IO a -> IO a Source #

Convenience function that sets up a manager and BHEnv and runs the given set of bloodhound operations. Connections will be pipelined automatically in accordance with the given manager settings in IO. If you've got your own monad transformer stack, you should use runBH directly.

Indices

createIndexOptions :: MonadBH m => CreateIndexOptions -> IndexName -> m Acknowledged Source #

Create an index with the full set of body fields (settings, mappings, aliases) and URI parameters (wait_for_active_shards, master_timeout, timeout) accepted by the create-index endpoint. This is a superset of createIndex / createIndexWith for callers that need more than just settings. See CreateIndexOptions for the shape and defaultCreateIndexOptions for an empty starting point.

Since: 0.26.0.0

data CreateIndexOptions Source #

CreateIndexOptions is the full set of inputs accepted by the PUT /<index> (create-index) endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-create-index.html). It carries both the body (settings, mappings, aliases) and the URI parameters (wait_for_active_shards, master_timeout, timeout).

This is a superset of the legacy createIndex / createIndexWith functions, which only let callers set settings. New code should prefer createIndexOptions together with defaultCreateIndexOptions:

let opts = defaultCreateIndexOptions
      { cioSettings = Just defaultIndexSettings,
        cioMappings = Just (toJSON myMapping),
        cioWaitForActiveShards = Just AllActiveShards
      }
in createIndexOptions opts (IndexName "foo")

For backwards compatibility defaultCreateIndexOptions produces no body and no URI parameters; in particular defaultCreateIndexOptions with cioSettings = Just s emits a byte-for-byte identical request to the legacy createIndex s.

Note: mappings and aliases are deliberately typed as an opaque Value / Object here. They are user-supplied JSON blobs the same way templateMappings is on IndexTemplate — full schema-typed modelling is tracked as a separate epic.

Constructors

CreateIndexOptions 

Fields

data ActiveShardCount Source #

Number of shard copies that must be active before a create-index (or similar) operation returns, sent as the wait_for_active_shards URI parameter. The server accepts the literal string "all" or any positive integer up to number_of_replicas + 1.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-create-index.html#index-create-wait-for-active-shards

Constructors

AllActiveShards

Render as "all": wait for every shard copy to be active.

ActiveShards Word

Render as the decimal string of the given count. Values larger than replicas + 1 are clamped server-side.

Instances

Instances details
FromJSON ActiveShardCount Source #

Parses the wire form produced by ToJSON: "all" (a JSON string) for AllActiveShards, or a JSON number for ActiveShards. The complement of ToJSON, so ActiveShardCount round-trips through JSON.

Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

ToJSON ActiveShardCount Source #

JSON encoding of ActiveShardCount: "all" (a JSON string) for AllActiveShards, and a bare JSON number for ActiveShards. Used by request bodies that carry wait_for_active_shards (e.g. the ES9 downsample endpoint), where the wire form distinguishes the literal string "all" from an integer shard count.

Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Show ActiveShardCount Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Eq ActiveShardCount Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

defaultCreateIndexOptions :: CreateIndexOptions Source #

CreateIndexOptions with every optional field set to Nothing. Renders to no body and no URI params, so the server uses its built-in defaults for everything. Callers wanting the same behaviour as the legacy createIndex defaultIndexSettings should set cioSettings = Just defaultIndexSettings explicitly.

createIndexWith Source #

Arguments

:: MonadBH m 
=> [UpdatableIndexSetting] 
-> Int

shard count

-> IndexName 
-> m Acknowledged 

Create an index, providing it with any number of settings. This is more expressive than createIndex but makes is more verbose for the common case of configuring only the shard count and replica count.

flushIndex :: MonadBH m => IndexName -> m ShardsResult Source #

flushIndex will flush an index given a Server and an IndexName. Returns ShardsResult (the {"_shards": {...}} envelope); reach the inner counts via srShards.

flushIndexWith :: MonadBH m => FlushIndexOptions -> IndexName -> m ShardsResult Source #

flushIndexWith is the fully-parameterised form of flushIndex. Pass defaultFlushIndexOptions to reproduce the legacy behaviour.

data FlushIndexOptions Source #

URI parameters accepted by POST index_flush (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-flush.html). All five documented parameters are modelled: wait_if_ongoing, force, ignore_unavailable, allow_no_indices and expand_wildcards. Every field is optional so defaultFlushIndexOptions renders to no query string — byte-for-byte identical to the legacy parameterless flushIndex.

defaultFlushIndexOptions :: FlushIndexOptions Source #

FlushIndexOptions with every parameter set to Nothing. Produces no query string, so flushIndexWith defaultFlushIndexOptions emits a request identical to flushIndex.

clearIndexCache :: MonadBH m => IndexName -> m ShardsResult Source #

clearIndexCache clears the caches (query, fielddata, request) for a single index. Wraps POST /<index>/_cache/clear.

Returns ShardsResult (the {"_shards": {...}} envelope), like the neighbouring flushIndex and refreshIndex, because the ES/OS response wraps the shard stats in a top-level _shards key. Only ?fielddata, ?query, ?request for selective clearing are not yet exposed.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-clearcache.html and https://docs.opensearch.org/latest/api-reference/index-apis/clear-cache/.

Since: 0.26.0.0

reloadSearchAnalyzers :: MonadBH m => IndexName -> m ReloadSearchAnalyzersResponse Source #

reloadSearchAnalyzers reloads an index's updateable search analyzers (e.g. updateable synonym/synonym_graph filters), picking up changes to the underlying synonym files. Maps to POST /{index}/_reload_search_analyzers.

Equivalent to reloadSearchAnalyzersWith defaultReloadSearchAnalyzersOptions.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-reload-analyzers.html and https://docs.opensearch.org/latest/api-reference/index-apis/reload-search-analyzers/.

Since: 0.26.0.0

data ReloadSearchAnalyzersResponse Source #

Top-level response of POST /{target}/_reload_search_analyzers. The _shards object summarises the per-node reload broadcast (its total may exceed the index shard count, since the reload runs once per node hosting a shard). The reload_details array carries one entry per concrete index whose analyzers were actually reloaded.

Constructors

ReloadSearchAnalyzersResponse 

Fields

  • rsarShards :: ShardResult

    Per-node reload broadcast summary. Reuses the canonical ShardResult / _shards envelope type shared with flushIndex and friends.

  • rsarReloadDetails :: [ReloadDetail]

    One entry per index whose search analyzers were reloaded. Parsed leniently as the empty list when the server omits the key (e.g. when no analyzer was eligible for reload).

data ReloadDetail Source #

One element of the reload_details array. Reports which search analyzers were reloaded for a given index and the node ids on which the reload took effect.

Constructors

ReloadDetail 

Fields

data ReloadSearchAnalyzersOptions Source #

URI parameters accepted by POST /{target}/_reload_search_analyzers. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-reload-analyzers.html. Every field is Maybe; defaultReloadSearchAnalyzersOptions leaves them all Nothing, which emits no query string.

Constructors

ReloadSearchAnalyzersOptions 

Fields

defaultReloadSearchAnalyzersOptions :: ReloadSearchAnalyzersOptions Source #

ReloadSearchAnalyzersOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the parameterless POST /{target}/_reload_search_analyzers.

reloadSearchAnalyzersOptionsParams :: ReloadSearchAnalyzersOptions -> [(Text, Maybe Text)] Source #

Render a ReloadSearchAnalyzersOptions record as a (key, value) list suitable for withQueries. Nothing fields are omitted, so defaultReloadSearchAnalyzersOptions produces an empty list (and therefore no query string).

diskUsage :: MonadBH m => IndexName -> m DiskUsageResponse Source #

diskUsage analyses the disk usage of each field of an index. Maps to POST /{index}/_disk_usage. ES-only feature (technical preview) and resource-intensive; defaultDiskUsageOptions sets the required run_expensive_tasks=true.

Equivalent to diskUsageWith defaultDiskUsageOptions.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-disk-usage.html.

Since: 0.26.0.0

data DiskUsageResponse Source #

Top-level response of POST /{target}/_disk_usage. The response is an object with a _shards summary plus one top-level key per concrete index that was analysed; because index names are not statically known, the per-index payload is collected into a KeyMap.

Constructors

DiskUsageResponse 

Fields

  • durShards :: ShardResult

    Shard-level execution summary (the canonical _shards envelope).

  • durIndices :: KeyMap DiskUsageIndex

    One entry per analysed index, keyed by index name. Built by collecting every top-level key other than _shards; a literal index named _shards would therefore be silently dropped, but ES forbids such names so this is impossible in practice.

data DiskUsageIndex Source #

The per-index payload: human-readable and byte-precise store sizes, an all_fields aggregate breakdown, and a fields map of per-field breakdowns.

Constructors

DiskUsageIndex 

Fields

data DiskUsageFieldBreakdown Source #

Breakdown of the disk usage of a single field (or the all_fields aggregate). Each structural component (stored_fields, doc_values, points, norms, term_vectors) is reported as a human-readable size plus a byte count; inverted_index additionally nests its own {total, total_in_bytes} object. All fields are Maybe because the server omits a component when the field does not use that structure (e.g. doc_values is absent for keyword fields).

data DiskUsageOptions Source #

URI parameters accepted by POST /{target}/_disk_usage. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-disk-usage.html.

Note that run_expensive_tasks is required by the API (the call is rejected without run_expensive_tasks=true); it is therefore a plain Bool rather than Maybe, and defaultDiskUsageOptions sets it to True so that the parameterless diskUsage works out of the box.

Although the ES 7.17 docs list wait_for_active_shards for this endpoint, ES 7.17.25 actually rejects it with 400 contains unrecognized parameter: [wait_for_active_shards], so it is not modelled here. The remaining parameters — flush, ignore_unavailable, allow_no_indices and expand_wildcards — were live-verified accepted against ES 7.17.25.

Constructors

DiskUsageOptions 

Fields

defaultDiskUsageOptions :: DiskUsageOptions Source #

DiskUsageOptions with run_expensive_tasks set to True and every other parameter Nothing. Unlike most default*Options in this module, this does emit a query string (?run_expensive_tasks=true) because the parameter is required by the API.

diskUsageOptionsParams :: DiskUsageOptions -> [(Text, Maybe Text)] Source #

Render a DiskUsageOptions record as a (key, value) list suitable for withQueries. Nothing fields are omitted, but run_expensive_tasks is always rendered (it is required).

fieldUsageStats :: MonadBH m => IndexName -> m FieldUsageStatsResponse Source #

fieldUsageStats reports per-shard, per-field access counts. Maps to GET /{index}/_field_usage_stats. ES-only feature (technical preview).

Equivalent to fieldUsageStatsWith defaultFieldUsageStatsOptions.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/field-usage-stats.html.

Since: 0.26.0.0

data FieldUsageStatsResponse Source #

Top-level response of GET /{index}/_field_usage_stats. As with the disk-usage response, the payload is an object with a _shards summary plus one top-level key per index, collected into a KeyMap.

Constructors

FieldUsageStatsResponse 

Fields

  • fusrShards :: ShardResult
     
  • fusrIndices :: KeyMap FieldUsageStatsIndex

    One entry per index, keyed by index name. Built by collecting every top-level key other than _shards; a literal index named _shards would therefore be silently dropped, but ES forbids such names so this is impossible in practice.

data FieldUsageBreakdown Source #

Per-field (or all_fields) usage breakdown. any counts any kind of use; the remaining fields count use of a specific structure.

data FieldUsageInvertedIndex Source #

The nested inverted_index object inside a FieldUsageBreakdown.

data FieldUsageStatsOptions Source #

URI parameters accepted by GET /{index}/_field_usage_stats. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/field-usage-stats.html. Every field is Maybe; defaultFieldUsageStatsOptions leaves them all Nothing, which emits no query string.

Although the ES 7.17 docs list wait_for_active_shards, master_timeout and timeout for this endpoint, ES 7.17.25 actually rejects all three with 400 contains unrecognized parameters: [master_timeout], [timeout], [wait_for_active_shards], so they are not modelled here. The remaining parameters — fields, expand_wildcards, ignore_unavailable and allow_no_indices — were live-verified accepted against ES 7.17.25.

defaultFieldUsageStatsOptions :: FieldUsageStatsOptions Source #

FieldUsageStatsOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the parameterless GET /{index}/_field_usage_stats.

fieldUsageStatsOptionsParams :: FieldUsageStatsOptions -> [(Text, Maybe Text)] Source #

Render a FieldUsageStatsOptions record as a (key, value) list suitable for withQueries. Nothing fields are omitted, so defaultFieldUsageStatsOptions produces an empty list (and therefore no query string).

getScriptContexts :: MonadBH m => m ScriptContextsResponse Source #

getScriptContexts lists every Painless / expression execution context the cluster knows about, with each context's method catalogue. Maps to GET /_script_context.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/painless-api-reference.html.

Since: 0.26.0.0

data ScriptContextsResponse Source #

Top-level response of GET /_script_context. The contexts array has one entry per execution context the server's script engines expose (e.g. aggs, filter, score, update, painless_test). The list is server-defined and varies across versions and installed plugins; treat it as a diagnostic catalogue rather than a stable enumeration.

Constructors

ScriptContextsResponse 

Fields

data ScriptContextInfo Source #

One element of the contexts array: a named execution context and the methods available to scripts running in it.

Constructors

ScriptContextInfo 

Fields

  • sciName :: Text

    Context name, e.g. aggs, filter, score, update.

  • sciMethods :: [ScriptContextMethod]

    Methods the context exposes to scripts. Every context lists at least execute; richer contexts (aggs, field) surface additional accessors such as getDoc, getParams, get_score.

data ScriptContextMethod Source #

One method exposed by a ScriptContextInfo. The scmReturnType and scpType values are fully-qualified JVM type names (e.g. java.util.Map, org.elasticsearch.analysis.common.AnalysisPredicateScript$Token); they are opaque transport strings intended for diagnostic display, not stable across versions.

Constructors

ScriptContextMethod 

Fields

  • scmName :: Text

    Method name, e.g. execute, getDoc, getParams, get_score.

  • scmReturnType :: Text

    Fully-qualified JVM return type of the method.

  • scmParams :: [ScriptContextParam]

    Formal parameters of the method. Most contexts surface zero-argument methods; a handful (e.g. the analysis context's execute) take parameters.

data ScriptContextParam Source #

One formal parameter of a ScriptContextMethod. Both fields are present whenever the parameter exists.

Constructors

ScriptContextParam 

Fields

  • scpName :: Text

    Parameter name, e.g. token.

  • scpType :: Text

    Fully-qualified JVM type of the parameter. The JSON key is type; the field is named scpType because type is a Haskell keyword and cannot be used as a record selector.

getScriptLanguages :: MonadBH m => m ScriptLanguagesResponse Source #

getScriptLanguages lists the script languages the cluster supports and, per language, the execution contexts in which each may run. Maps to GET /_script_language.

Note: on OpenSearch 1.3 this endpoint returns HTTP 500 (a server bug); calls against a 1.3 cluster will fail.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/painless-api-reference.html.

Since: 0.26.0.0

data ScriptLanguagesResponse Source #

Top-level response of GET /_script_language.

The types_allowed array lists the script source forms the cluster accepts (in practice always ["inline", "stored"]); the language_contexts array has one entry per supported language, each naming the execution contexts in which that language may run.

Constructors

ScriptLanguagesResponse 

Fields

data ScriptLanguageContext Source #

One element of the language_contexts array: a supported language and the execution contexts in which it may run. The slcLanguage values (expression, mustache, painless) match the lang field of Script, so the existing ScriptLanguage newtype is reused for coherence.

Constructors

ScriptLanguageContext 

Fields

deleteIndex :: MonadBH m => IndexName -> m Acknowledged Source #

deleteIndex will delete an index given a Server and an IndexName.

>>> _ <- runBH' $ createIndex defaultIndexSettings (IndexName "didimakeanindex")
>>> response <- runBH' $ deleteIndex (IndexName "didimakeanindex")
>>> isSuccess response
True
>>> runBH' $ indexExists (IndexName "didimakeanindex")
False

updateIndexSettings :: MonadBH m => NonEmpty UpdatableIndexSetting -> IndexName -> m Acknowledged Source #

updateIndexSettings will apply a non-empty list of setting updates to an index

>>> _ <- runBH' $ createIndex defaultIndexSettings (IndexName "unconfiguredindex")
>>> response <- runBH' $ updateIndexSettings (BlocksWrite False :| []) (IndexName "unconfiguredindex")
>>> isSuccess response
True

Equivalent to updateIndexSettingsWith updates defaultUpdateIndexSettingsOptions.

data UpdateIndexSettingsOptions Source #

URI parameters accepted by PUT index_settings (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-update-settings.html). The four documented parameters are modelled: master_timeout, timeout, preserve_existing and flat_settings. Every field is optional so defaultUpdateIndexSettingsOptions renders to no query string — byte-for-byte identical to the legacy parameterless updateIndexSettings. Durations are (unit, magnitude) pairs (e.g. (TimeUnitSeconds, 30) renders as 30s), matching OpenCloseIndexOptions.

defaultUpdateIndexSettingsOptions :: UpdateIndexSettingsOptions Source #

UpdateIndexSettingsOptions with every parameter set to Nothing. Produces no query string, so updateIndexSettingsWith updates name defaultUpdateIndexSettingsOptions emits a request identical to updateIndexSettings.

getIndexSettings :: MonadBH m => IndexName -> m IndexSettingsSummary Source #

getIndexSettings retrieves the live settings of a single index. Equivalent to getIndexSettingsWith name defaultGetIndexSettingsOptions.

data GetIndexSettingsOptions Source #

URI parameters accepted by GET index_settings (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-settings.html). The four documented parameters are modelled: master_timeout, flat_settings, include_defaults and local. Every field is optional so defaultGetIndexSettingsOptions renders to no query string — byte-for-byte identical to the legacy parameterless getIndexSettings. Durations are (unit, magnitude) pairs (e.g. (TimeUnitSeconds, 30) renders as 30s), matching OpenCloseIndexOptions.

defaultGetIndexSettingsOptions :: GetIndexSettingsOptions Source #

GetIndexSettingsOptions with every parameter set to Nothing. Produces no query string, so getIndexSettingsWith name defaultGetIndexSettingsOptions emits a request identical to getIndexSettings.

getIndex :: MonadBH m => IndexName -> m IndexInfo Source #

getIndex fetches the full definition of a single index — its aliases, mappings and settings — in one request. Wraps the GET /<index> endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-index.html).

getIndexStats :: MonadBH m => IndexName -> m IndexStats Source #

getIndexStats returns statistics for a single index — the GET /<index>/_stats endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-stats.html).

getIndexRecovery :: MonadBH m => IndexName -> m IndexRecovery Source #

getIndexRecovery returns information about ongoing and completed shard recoveries for the given index (e.g. after snapshot restore, replica allocation or peer recovery on node restart). Wraps the GET /<index>/_recovery endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-recovery.html).

getIndexSegments :: MonadBH m => IndexName -> m IndexSegments Source #

getIndexSegments returns low-level Lucene segment information for the given index, one entry per shard copy (primary and each replica). Wraps the GET /<index>/_segments endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-segments.html; also implemented by OpenSearch — see https://docs.opensearch.org/latest/api-reference/index-apis/segments/).

getShardStores :: MonadBH m => IndexName -> m ShardStores Source #

getShardStores returns store information for every shard copy (primary and each replica) of the given index, one entry per copy describing where it is allocated and its allocation state. Wraps the GET /<index>/_shard_stores endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-shards-stores.html; also implemented by OpenSearch — see https://docs.opensearch.org/latest/api-reference/index-apis/shard-stores/).

Equivalent to getShardStoresWith defaultShardStoresOptions. Use the With variant to pass URI parameters such as status (cluster-health filter). Surfaced as StatusDependant so genuine server-side errors (auth, missing index, 5xx, ...) decode as an EsError.

getShardStoresWith :: MonadBH m => IndexName -> ShardStoresOptions -> m ShardStores Source #

Like getShardStores but additionally accepts ShardStoresOptions rendered as URI parameters. defaultShardStoresOptions makes this byte-for-byte identical to getShardStores.

data ShardStoresOptions Source #

URI parameters accepted by GET {index}_shard_stores. The four documented parameters are modelled: status (cluster-health filter, comma-joined on the wire), ignore_unavailable, allow_no_indices and expand_wildcards (comma-joined). Every field is optional so defaultShardStoresOptions renders to no query string at all — byte-for-byte identical to a parameterless call.

expand_wildcards reuses ExpandWildcards (matching ResolveIndexOptions, OpenCloseIndexOptions and friends); status is a list because the server accepts a comma-separated combination (e.g. [ShardStoresStatusYellow, ShardStoresStatusRed], the server-side default).

defaultShardStoresOptions :: ShardStoresOptions Source #

ShardStoresOptions with every parameter set to Nothing. Produces no query string, so getShardStoresWith defaultShardStoresOptions emits a request byte-for-byte identical to getShardStores.

data IndexInfo Source #

Response of the GET /{index} (get-index) endpoint, which returns the aliases, mappings and settings of one index in a single envelope. The server wraps the payload in a single-key object keyed by the index name — the same shape as IndexSettingsSummary — but additionally surfaces aliases and mappings alongside the settings.

https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-index.html

Constructors

IndexInfo 

Fields

data IndexStats Source #

Top-level envelope of the GET /<index>/_stats response. Carries the shard result, an optional _all rollup (present when the server aggregates the requested indices) and the per-index entries keyed by index name.

data IndexStatMetrics Source #

A metric block (either primaries or total). The docs and store sub-objects are typed; every other section (indexing, search, merge, flush, refresh, query_cache, fielddata, segments, translog, completion, ...) is preserved verbatim in indexStatMetricsOther.

Note: docs and store appear both as typed fields and verbatim inside indexStatMetricsOther (which captures the whole original object). The typed copies are authoritative; the verbatim copy exists so callers can navigate any not-yet-typed section without waiting for a follow-up bead to promote it.

Instances

Instances details
FromJSON IndexStatMetrics Source #

Parse a metric block. indexStatMetricsOther captures the full original object so callers can navigate any section beyond docs and store without waiting for a typed model.

Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Show IndexStatMetrics Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Eq IndexStatMetrics Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

newtype IndexRecovery Source #

Top-level envelope of the GET /<index>/_recovery response. The keys are index names echoed back by the server (parsed through IndexName's FromJSON instance, the lenient validator that accepts hidden indices like .kibana, matching IndexStats).

data IndexSegments Source #

Top-level envelope of the GET {index}_segments response. The outer map is keyed by index name (parsed through IndexName's FromJSON instance, the lenient validator that accepts hidden indices like .kibana, matching IndexStats and IndexRecovery). The inner map is keyed by shard number as a string.

data ShardStores Source #

Top-level envelope of the GET {index}_shard_stores response. The outer map is keyed by index name (parsed through IndexName's FromJSON instance, the lenient validator that accepts hidden indices like .kibana, matching IndexSegments and IndexRecovery). The inner map is keyed by shard number as a string (kept as Text because ES documents it as a string and uses non-numeric suffixes for relocating copies in some responses).

data ShardStoresShard Source #

Per-shard wrapper inside a ShardStores response. ES reports every copy of a shard (primary and each replica) under the same shard number, collected in shardStoresShardStores. A shard with no assigned copy stores emits an empty list.

data ShardStore Source #

A single store copy. The server emits a dynamic per-node key (the node id) alongside the known sibling fields (shardStoreAllocationId, shardStoreAllocation, shardStoreStoreException); the parser peels off the known keys and treats the single remaining Object-valued key as (node_id, ShardStoreNode). Any other non-known entry (typically a future scalar sibling field) is preserved verbatim in shardStoreOther, mirroring segmentOther and shardStoreNodeOther.

data ShardStoreNode Source #

Per-node metadata attached to each store copy. ES emits a richer set of fields than OpenSearch (which only documents name, ephemeral_id, transport_address and attributes); the typed subset below is the union of both, with anything else preserved verbatim in shardStoreNodeOther (mirroring segmentOther).

data ShardStoreAllocation Source #

The per-copy allocation enum. Wire values are lowercase strings. ES recognises three values; OpenSearch documents only ShardStoreAllocationPrimary and ShardStoreAllocationReplica. The ShardStoreAllocationOther constructor preserves any future / engine-specific value verbatim.

data ShardRecovery Source #

A single shard recovery entry. The id is the shard number; type reports the source of the recovery (SNAPSHOT, REPLICA, EXISTING_STORE, EMPTY_STORE or PEER_RECOVERY); stage reports the current phase (INITIALIZING, INDEX, FINALIZE or DONE).

data ShardRecoveryIndex Source #

The index sub-block of a shard recovery. The files progress object — the most useful summary of a recovery's progress — is typed; everything else in the index sub-object (size, total_time, source_throttle_time, target_throttle_time, translog, verify_index, ...) is preserved verbatim in shardRecoveryIndexOther so callers can navigate it with aeson while later beads promote individual sections to typed records.

forceMergeIndex :: MonadBH m => IndexSelection -> ForceMergeIndexSettings -> m ShardsResult Source #

forceMergeIndex

The force merge API allows to force merging of one or more indices through an API. The merge relates to the number of segments a Lucene index holds within each shard. The force merge operation allows to reduce the number of segments by merging them.

This call will block until the merge is complete. If the http connection is lost, the request will continue in the background, and any new requests will block until the previous force merge is complete.

indexExists :: MonadBH m => IndexName -> m Bool Source #

indexExists enables you to check if an index exists. Returns Bool in IO

>>> exists <- runBH' $ indexExists testIndex

openIndex :: MonadBH m => IndexName -> m Acknowledged Source #

openIndex opens an index given a Server and an IndexName. Explained in further detail at http://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-open-close.html

>>> response <- runBH' $ openIndex testIndex

openIndexWith :: MonadBH m => OpenCloseIndexOptions -> IndexName -> m Acknowledged Source #

openIndexWith is the fully-parameterised form of openIndex. Pass defaultOpenCloseIndexOptions to reproduce the legacy behaviour.

closeIndex :: MonadBH m => IndexName -> m Acknowledged Source #

closeIndex closes an index given a Server and an IndexName. Explained in further detail at http://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-open-close.html

>>> response <- runBH' $ closeIndex testIndex

closeIndexWith :: MonadBH m => OpenCloseIndexOptions -> IndexName -> m Acknowledged Source #

closeIndexWith is the fully-parameterised form of closeIndex. Pass defaultOpenCloseIndexOptions to reproduce the legacy behaviour.

data OpenCloseIndexOptions Source #

URI parameters accepted by POST index_open and POST index_close (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-open-close.html). All six documented parameters are modelled: wait_for_active_shards, ignore_unavailable, allow_no_indices, expand_wildcards, master_timeout (deprecated alias cluster_manager_timeout on ES 7.16+/OS) and timeout. Every field is optional so defaultOpenCloseIndexOptions renders to no query string at all — byte-for-byte identical to the legacy parameterless openIndex / closeIndex.

wait_for_active_shards reuses ActiveShardCount (so AllActiveShards renders as all and ActiveShards n as the bare decimal), matching the convention used by ClusterHealthOptions and CreateIndexOptions. Durations are (unit, magnitude) pairs (e.g. (TimeUnitSeconds, 30) renders as 30s).

defaultOpenCloseIndexOptions :: OpenCloseIndexOptions Source #

OpenCloseIndexOptions with every parameter set to Nothing. Produces no query string, so openIndexWith defaultOpenCloseIndexOptions and closeIndexWith defaultOpenCloseIndexOptions emit requests identical to openIndex and closeIndex.

listIndices :: MonadBH m => m [IndexName] Source #

listIndices returns a list of all index names on a given Server

catIndices :: MonadBH m => m [(IndexName, Int)] Source #

catIndices returns a list of all index names on a given Server as well as their doc counts

catIndicesWith :: MonadBH m => CatIndicesOptions -> m [CatIndicesRow] Source #

catIndicesWith is the fully-parameterised form of catIndices. See Database.Bloodhound.Common.Requests and CatIndicesOptions for the available parameters.

catAliases :: MonadBH m => m [CatAliasesRow] Source #

catAliases lists every index alias on the cluster via GET /_cat/aliases?format=json. Equivalent to catAliasesWith Nothing defaultCatAliasesOptions.

catAliasesWith :: MonadBH m => Maybe AliasName -> CatAliasesOptions -> m [CatAliasesRow] Source #

catAliasesWith is the fully-parameterised form of catAliases. See Database.Bloodhound.Common.Requests and CatAliasesOptions for the available parameters.

catAllocation :: MonadBH m => m [CatAllocationRow] Source #

catAllocation lists the allocation of disk space for indexes and the number of shards on each data node via GET /_cat/allocation?format=json. Equivalent to catAllocationWith Nothing defaultCatAllocationOptions.

catCount :: MonadBH m => m [CatCountRow] Source #

catCount reports the document count for the whole cluster via GET /_cat/count?format=json. Equivalent to catCountWith Nothing defaultCatCountOptions.

catCountWith :: MonadBH m => Maybe IndexName -> CatCountOptions -> m [CatCountRow] Source #

catCountWith is the fully-parameterised form of catCount. See Database.Bloodhound.Common.Requests and CatCountOptions for the available parameters.

catMaster :: MonadBH m => m [CatMasterRow] Source #

catMaster reports the identity of the elected master node via GET /_cat/master?format=json. Equivalent to catMasterWith defaultCatMasterOptions.

catMasterWith :: MonadBH m => CatMasterOptions -> m [CatMasterRow] Source #

catMasterWith is the fully-parameterised form of catMaster. See Database.Bloodhound.Common.Requests and CatMasterOptions for the available parameters.

catHealth :: MonadBH m => m [CatHealthRow] Source #

catHealth reports a one-row-per-snapshot summary of cluster health via GET /_cat/health?format=json. Equivalent to catHealthWith defaultCatHealthOptions.

catHealthWith :: MonadBH m => CatHealthOptions -> m [CatHealthRow] Source #

catHealthWith is the fully-parameterised form of catHealth. See Database.Bloodhound.Common.Requests and CatHealthOptions for the available parameters.

catPendingTasks :: MonadBH m => m [CatPendingTasksRow] Source #

catPendingTasks lists the cluster-level tasks waiting to be executed via GET /_cat/pending_tasks?format=json. Equivalent to catPendingTasksWith defaultCatPendingTasksOptions.

catPlugins :: MonadBH m => m [CatPluginsRow] Source #

catPlugins lists the plugins installed on each node via GET /_cat/plugins?format=json. Equivalent to catPluginsWith defaultCatPluginsOptions.

catPluginsWith :: MonadBH m => CatPluginsOptions -> m [CatPluginsRow] Source #

catPluginsWith is the fully-parameterised form of catPlugins. See Database.Bloodhound.Common.Requests and CatPluginsOptions for the available parameters.

catTemplates :: MonadBH m => m [CatTemplatesRow] Source #

catTemplates lists the cluster's index templates via GET /_cat/templates?format=json. Equivalent to catTemplatesWith Nothing defaultCatTemplatesOptions.

catThreadPool :: MonadBH m => m [CatThreadPoolRow] Source #

catThreadPool lists the thread pools of each node via GET /_cat/thread_pool?format=json. Equivalent to catThreadPoolWith Nothing defaultCatThreadPoolOptions.

catFielddata :: MonadBH m => m [CatFielddataRow] Source #

catFielddata lists the amount of heap memory currently used by the field data cache, per field per node, via GET /_cat/fielddata?format=json. Equivalent to catFielddataWith Nothing defaultCatFielddataOptions.

catNodeattrs :: MonadBH m => m [CatNodeattrsRow] Source #

catNodeattrs lists custom node attributes via GET /_cat/nodeattrs?format=json. Equivalent to catNodeattrsWith defaultCatNodeattrsOptions.

catRepositories :: MonadBH m => m [CatRepositoriesRow] Source #

catRepositories lists snapshot repositories registered on the cluster via GET /_cat/repositories?format=json. Equivalent to catRepositoriesWith defaultCatRepositoriesOptions.

catShards :: MonadBH m => m [CatShardsRow] Source #

catShards lists the state of every primary and replica shard in the cluster via GET /_cat/shards?format=json. Equivalent to catShardsWith Nothing defaultCatShardsOptions.

catShardsWith :: MonadBH m => Maybe IndexName -> CatShardsOptions -> m [CatShardsRow] Source #

catShardsWith is the fully-parameterised form of catShards. See Database.Bloodhound.Common.Requests and CatShardsOptions for the available parameters.

catTasks :: MonadBH m => m [CatTasksRow] Source #

catTasks lists the tasks currently executing on the cluster via GET /_cat/tasks?format=json. Equivalent to catTasksWith defaultCatTasksOptions.

catTasksWith :: MonadBH m => CatTasksOptions -> m [CatTasksRow] Source #

catTasksWith is the fully-parameterised form of catTasks. See Database.Bloodhound.Common.Requests and CatTasksOptions for the available parameters.

catSnapshots :: MonadBH m => m [CatSnapshotsRow] Source #

catSnapshots lists the snapshots stored in every snapshot repository registered on the cluster via GET /_cat/snapshots?format=json. Equivalent to catSnapshotsWith Nothing defaultCatSnapshotsOptions.

catNodes :: MonadBH m => m [CatNodesRow] Source #

catNodes lists the cluster topology — one row per node with its identity, resource usage, and elected-master flag — via GET /_cat/nodes?format=json. Equivalent to catNodesWith defaultCatNodesOptions.

catNodesWith :: MonadBH m => CatNodesOptions -> m [CatNodesRow] Source #

catNodesWith is the fully-parameterised form of catNodes. See Database.Bloodhound.Common.Requests and CatNodesOptions for the available parameters.

catSegments :: MonadBH m => m [CatSegmentsRow] Source #

catSegments lists the low-level Lucene segments of each shard of each index via GET /_cat/segments?format=json. Equivalent to catSegmentsWith Nothing defaultCatSegmentsOptions.

catRecovery :: MonadBH m => m [CatRecoveryRow] Source #

catRecovery lists shard recovery progress for each shard of each index via GET /_cat/recovery?format=json. Equivalent to catRecoveryWith Nothing defaultCatRecoveryOptions.

catCircuitBreakers :: MonadBH m => m [CatCircuitBreakersRow] Source #

catCircuitBreakers lists the JVM circuit breakers. See catCircuitBreakers and CatCircuitBreakersRow.

Since: 0.26.0.0

catMlJobs :: MonadBH m => m [CatMlJobsRow] Source #

catMlJobs lists the ML anomaly-detection jobs. See catMlJobs and CatMlJobsRow.

Since: 0.26.0.0

catMlJobsWith :: MonadBH m => Maybe Text -> CatMlJobsOptions -> m [CatMlJobsRow] Source #

catMlJobsWith is the fully-parameterised form of catMlJobs.

Since: 0.26.0.0

catMlDatafeeds :: MonadBH m => m [CatMlDatafeedsRow] Source #

catMlDatafeeds lists the ML datafeeds. See catMlDatafeeds and CatMlDatafeedsRow.

Since: 0.26.0.0

catMlDatafeedsWith :: MonadBH m => Maybe Text -> CatMlDatafeedsOptions -> m [CatMlDatafeedsRow] Source #

catMlDatafeedsWith is the fully-parameterised form of catMlDatafeeds.

Since: 0.26.0.0

catTransforms :: MonadBH m => m [CatTransformsRow] Source #

catTransforms lists the transforms. See catTransforms and CatTransformsRow.

Since: 0.26.0.0

catTransformsWith :: MonadBH m => Maybe Text -> CatTransformsOptions -> m [CatTransformsRow] Source #

catTransformsWith is the fully-parameterised form of catTransforms.

Since: 0.26.0.0

catHelp :: MonadBH m => m Text Source #

catHelp fetches the GET /_cat report, which lists the available cat commands as plain text. See catHelp.

Since: 0.26.0.0

addIndexBlock :: MonadBH m => IndexName -> IndexBlock -> m Acknowledged Source #

addIndexBlock applies an IndexBlock to an index via PUT <index>_block/<block>, returning Acknowledged on success. Useful for cluster maintenance: temporarily disabling writes, reads, or metadata operations without closing the index.

See addIndexBlock for the underlying request builder, and https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-blocks.html for the upstream documentation.

Since: 0.26.0.0

removeIndexBlock :: MonadBH m => IndexName -> IndexBlock -> m Acknowledged Source #

removeIndexBlock releases an IndexBlock from an index. Counterpart to addIndexBlock. Because the dedicated PUT <index>_block/<block> endpoint is add-only on every supported backend (ES7+ and OS1+), the removal uses PUT <index>_settings with the matching BlocksX False UpdatableIndexSetting. Surfaced as StatusDependant so a 404 for a missing index decodes as a structured EsError (unlike updateIndexSettings, which is StatusIndependant). See removeIndexBlock for details.

Since: 0.26.0.0

data IndexBlock Source #

The block kind passed as the last path segment of PUT <index>_block/<block> (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-blocks.html, https://docs.opensearch.org/latest/api-reference/index-apis/block-index/).

Each constructor maps to a documented wire string rendered by indexBlockText. This is the canonical way to apply an index block. The dedicated _block endpoint is add-only on every supported backend (ES7+/OS1+), so removal routes through PUT <index>_settings with the matching UpdatableIndexSetting via indexBlockToSetting — see removeIndexBlock. The BlocksWrite, BlocksRead, BlocksReadOnly, BlocksMetaData, BlocksReadOnlyAllowDelete ToJSON renderers emit the index.blocks.X form ES requires (fixed in bloodhound-442).

Constructors

IndexBlockWrite

write — disable data write operations (matches BlocksWrite).

IndexBlockRead

read — disable data read operations (matches BlocksRead).

IndexBlockReadOnly

read_only — disable both data read and write operations (matches BlocksReadOnly).

IndexBlockMetadata

metadata — disable metadata operations (matches BlocksMetaData).

indexBlockText :: IndexBlock -> Text Source #

Wire string for an IndexBlock. Single source of truth used by addIndexBlock to render the trailing path segment of PUT <index>_block/<block>.

waitForYellowIndex :: MonadBH m => IndexName -> m HealthStatus Source #

Block until the index becomes available for indexing documents. This is useful for integration tests in which indices are rapidly created and deleted.

rolloverIndex :: MonadBH m => IndexAliasName -> Maybe RolloverConditions -> m RolloverResponse Source #

rolloverIndex rolls an alias over to a new index when the supplied conditions are met on the alias's current write index. The alias must point at exactly one write index whose name matches the rollover naming convention (e.g. logs-000001 -> logs-000002). Wraps POST <alias>_rollover.

Pass Just conditions to set thresholds (any subset of rolloverConditionsMaxAge / rolloverConditionsMaxDocs / rolloverConditionsMaxSize / rolloverConditionsMaxPrimaryShardSize; at least one should be Just). Pass Nothing to roll over unconditionally. See RolloverResponse for the result.

Since: 0.26.0.0

data RolloverConditions Source #

Conditions under which rolloverIndex should roll the alias over to a new index. At least one field should be Just when the value is actually sent to the server; the Maybe fields let the caller express any subset.

Sizes and ages carry units (e.g. "7d", "50gb") so they are Text rather than numbers, matching the on-the-wire grammar used by both Elasticsearch and OpenSearch. rolloverConditionsMaxDocs is a plain integer.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-rollover-index.html and https://docs.opensearch.org/latest/api-reference/index-apis/rollover-index/.

Since: 0.26.0.0

Instances

Instances details
FromJSON RolloverConditions Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

ToJSON RolloverConditions Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Generic RolloverConditions Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Associated Types

type Rep RolloverConditions 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

type Rep RolloverConditions = D1 ('MetaData "RolloverConditions" "Database.Bloodhound.Internal.Versions.Common.Types.Indices" "bloodhound-1.0.0.0-49XSndf62hW73KoVhdlR9I" 'False) (C1 ('MetaCons "RolloverConditions" 'PrefixI 'True) ((S1 ('MetaSel ('Just "rolloverConditionsMaxAge") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Text)) :*: S1 ('MetaSel ('Just "rolloverConditionsMaxDocs") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Int))) :*: (S1 ('MetaSel ('Just "rolloverConditionsMaxSize") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Text)) :*: S1 ('MetaSel ('Just "rolloverConditionsMaxPrimaryShardSize") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Text)))))
Show RolloverConditions Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Eq RolloverConditions Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

type Rep RolloverConditions Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

type Rep RolloverConditions = D1 ('MetaData "RolloverConditions" "Database.Bloodhound.Internal.Versions.Common.Types.Indices" "bloodhound-1.0.0.0-49XSndf62hW73KoVhdlR9I" 'False) (C1 ('MetaCons "RolloverConditions" 'PrefixI 'True) ((S1 ('MetaSel ('Just "rolloverConditionsMaxAge") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Text)) :*: S1 ('MetaSel ('Just "rolloverConditionsMaxDocs") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Int))) :*: (S1 ('MetaSel ('Just "rolloverConditionsMaxSize") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Text)) :*: S1 ('MetaSel ('Just "rolloverConditionsMaxPrimaryShardSize") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Text)))))

data RolloverResponse Source #

Response body for POST alias_rollover.

All fields are modelled defensively with .:.? to tolerate backends that omit them. The ES OpenAPI spec marks every field as Required in the 200 body, but other backends (OpenSearch) may be looser, and a dry_run response still populates old_index/new_index with the candidate names.

conditions, when present, is the server's own evaluation of the supplied thresholds: a map from a human-readable condition description (e.g. "[max_docs: 1]") to whether that condition was met (True) or not (False). The shape is therefore not the same as RolloverConditions — the server re-renders thresholds as display strings rather than echoing the request body.

Since: 0.26.0.0

Instances

Instances details
FromJSON RolloverResponse Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

ToJSON RolloverResponse Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Generic RolloverResponse Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Associated Types

type Rep RolloverResponse 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

type Rep RolloverResponse = D1 ('MetaData "RolloverResponse" "Database.Bloodhound.Internal.Versions.Common.Types.Indices" "bloodhound-1.0.0.0-49XSndf62hW73KoVhdlR9I" 'False) (C1 ('MetaCons "RolloverResponse" 'PrefixI 'True) ((S1 ('MetaSel ('Just "rolloverResponseAcknowledged") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool) :*: (S1 ('MetaSel ('Just "rolloverResponseShardsAcknowledged") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool) :*: S1 ('MetaSel ('Just "rolloverResponseOldIndex") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe IndexName)))) :*: ((S1 ('MetaSel ('Just "rolloverResponseNewIndex") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe IndexName)) :*: S1 ('MetaSel ('Just "rolloverResponseRolledOver") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool)) :*: (S1 ('MetaSel ('Just "rolloverResponseDryRun") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool) :*: S1 ('MetaSel ('Just "rolloverResponseConditions") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (Map Text Bool)))))))
Show RolloverResponse Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

Eq RolloverResponse Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

type Rep RolloverResponse Source # 
Instance details

Defined in Database.Bloodhound.Internal.Versions.Common.Types.Indices

type Rep RolloverResponse = D1 ('MetaData "RolloverResponse" "Database.Bloodhound.Internal.Versions.Common.Types.Indices" "bloodhound-1.0.0.0-49XSndf62hW73KoVhdlR9I" 'False) (C1 ('MetaCons "RolloverResponse" 'PrefixI 'True) ((S1 ('MetaSel ('Just "rolloverResponseAcknowledged") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool) :*: (S1 ('MetaSel ('Just "rolloverResponseShardsAcknowledged") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool) :*: S1 ('MetaSel ('Just "rolloverResponseOldIndex") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe IndexName)))) :*: ((S1 ('MetaSel ('Just "rolloverResponseNewIndex") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe IndexName)) :*: S1 ('MetaSel ('Just "rolloverResponseRolledOver") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool)) :*: (S1 ('MetaSel ('Just "rolloverResponseDryRun") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool) :*: S1 ('MetaSel ('Just "rolloverResponseConditions") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (Map Text Bool)))))))

defaultRolloverConditions :: RolloverConditions Source #

RolloverConditions with every threshold set to Nothing. Useful only as a seed for record updates, e.g.

defaultRolloverConditions { rolloverConditionsMaxDocs = Just 1000 }

WARNING: sending defaultRolloverConditions verbatim to the server produces an empty conditions object, which the rollover endpoint will reject. Always override at least one field with Just before passing it to rolloverIndex. To roll over unconditionally, pass Nothing instead.

shrinkIndex :: MonadBH m => IndexName -> IndexName -> ShrinkSettings -> m Acknowledged Source #

Shrink an existing index into a new index with fewer primary shards. Wraps POST <source>_shrink/<target>. The source must be read-only (index.blocks.write: true) and all primary shards must be co-located on one node; the target's number_of_shards must be a divisor of the source's. Override shrinkSettingsOptions to set the target shard count, aliases and the other body fields and URI parameters (wait_for_active_shards, master_timeout, timeout).

Since: 0.26.0.0

newtype ShrinkSettings Source #

Body and URI parameters for POST index_shrink/target. The source index must be read-only (index.blocks.write: true) and every primary shard of the source must be resident on a single node before the call; the target's number_of_shards must be a divisor of the source's. Wrap defaultCreateIndexOptions (or override shrinkSettingsOptions) to populate settings / aliases for the new index.

Since: 0.26.0.0

defaultShrinkSettings :: ShrinkSettings Source #

ShrinkSettings with every optional field set to Nothing: empty body, no URI parameters. The server then copies the source index's settings verbatim and applies its built-in defaults for anything missing.

Since: 0.26.0.0

splitIndex :: MonadBH m => IndexName -> IndexName -> SplitSettings -> m Acknowledged Source #

Split an existing index into a new index with more primary shards. Wraps POST <source>_split/<target>. The source must be read-only (index.blocks.write: true); the target's number_of_shards must be a multiple of the source's, and the source's index.number_of_routing_shards must be a multiple of the target's. See shrinkSettingsOptions for the body and URI parameter surface.

Since: 0.26.0.0

newtype SplitSettings Source #

Body and URI parameters for POST index_split/target. The source index must be read-only (index.blocks.write: true); the target's number_of_shards must be a multiple of the source's, and the source's index.number_of_routing_shards must be a multiple of the target's. See ShrinkSettings for the field layout — both newtypes wrap CreateIndexOptions.

Since: 0.26.0.0

defaultSplitSettings :: SplitSettings Source #

SplitSettings with every optional field set to Nothing.

Since: 0.26.0.0

cloneIndex :: MonadBH m => IndexName -> IndexName -> CloneSettings -> m Acknowledged Source #

Clone an existing index into a new index with the same mappings and settings. Wraps POST <source>_clone/<target>. The source must be read-only (index.blocks.write: true); the target inherits the source's number_of_shards. See shrinkSettingsOptions for the body and URI parameter surface (the record is wrapped under cloneSettingsOptions here).

Since: 0.26.0.0

newtype CloneSettings Source #

Body and URI parameters for POST index_clone/target. The source index must be read-only (index.blocks.write: true); the target inherits the source's number_of_shards. See ShrinkSettings for the field layout.

Since: 0.26.0.0

defaultCloneSettings :: CloneSettings Source #

CloneSettings with every optional field set to Nothing.

Since: 0.26.0.0

resolveIndex :: MonadBH m => [IndexPattern] -> m ResolvedIndices Source #

resolveIndex resolves indices, aliases and data streams matching the given patterns. Wraps GET _resolveindex/{name} (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-resolve-index-api.html; also implemented by OpenSearch — see https://docs.opensearch.org/latest/api-reference/index-apis/resolve-index/).

Patterns are comma-joined into a single path segment; an empty list is treated as the wildcard *. Use resolveIndexWith to pass URI parameters such as expand_wildcards. Surfaced as StatusDependant so genuine server-side errors (auth, malformed pattern, ...) decode as an EsError. A missing concrete target usually returns 200 with empty result arrays rather than a 404 — see ResolveIndexOptions for the ignore_unavailable knob (documented on ES 8.x+, silently accepted by OpenSearch).

resolveIndexWith :: MonadBH m => ResolveIndexOptions -> [IndexPattern] -> m ResolvedIndices Source #

Like resolveIndex but additionally accepts ResolveIndexOptions rendered as URI parameters. defaultResolveIndexOptions makes this byte-for-byte identical to resolveIndex.

data ResolveIndexOptions Source #

URI parameters accepted by GET _resolveindex. Only expand_wildcards is documented by every backend (ES 7.17, ES 8.x, ES 9.x, OpenSearch); ignore_unavailable and allow_no_indices are documented by ES 8.x/9.x but accepted (undocumented) by OpenSearch. The deprecated ES-7.x-only ignore_throttled and the ES-9.2-only mode parameters are not modelled here.

expand_wildcards is a list because the server accepts a comma-separated combination (e.g. [ExpandWildcardsOpen, ExpandWildcardsHidden]). Note that ExpandWildcardsHidden must be combined with ExpandWildcardsOpen and/or ExpandWildcardsClosed — the server rejects a bare hidden.

defaultResolveIndexOptions :: ResolveIndexOptions Source #

ResolveIndexOptions with every parameter set to Nothing. Produces no query string, so a call made with this value is byte-identical to a parameterless call.

data ResolvedIndex Source #

One entry in the indices array. The universally-present name and attributes fields are typed; aliases (the alias names that point at this index) is optional and defaults to empty when absent; data_stream and mode are ES-9.x-only and kept as Maybe.

attributes is intentionally [Text] rather than a sum type: the documented value set differs across versions (ES 8.17 enumerates open, closed, hidden, system, frozen; frozen is removed in ES 9.x; OpenSearch does not enumerate the values at all), so a permissive list preserves forward compatibility.

The remainder of the entry (any not-yet-typed field the server may add) is captured verbatim in resolvedIndexOther so callers can navigate it with aeson.

Strict names: resolvedIndexName is parsed through IndexName's FromJSON instance, which runs mkIndexNameSystem. A name that violates that validator — most realistically a <cluster>:<index> remote-cluster reference (the : is rejected) — fails the entire ResolvedIndices parse, not just this entry. This matches the precedent set by FieldMappingResponse and IndexStats.

data ResolvedAlias Source #

One entry in the aliases array. name is the alias; indices lists the concrete indices the alias resolves to. The ES-9.x OpenAPI spec types indices as string | array[string], but every documented example renders it as an array; the FromJSON instance below accepts both forms (a bare string is lifted to a singleton list) so the same parser works regardless of backend.

data ResolvedDataStream Source #

One entry in the data_streams array. The ES-9.x OpenAPI spec types backing_indices as string | array[string]; as with ResolvedAlias, the parser accepts both forms. OpenSearch's example always returns an empty data_streams array, so this type is exercised primarily against Elasticsearch.

Dangling indices

listDanglingIndices :: MonadBH m => m [DanglingIndex] Source #

listDanglingIndices returns every dangling index currently known to the cluster. See listDanglingIndices for the underlying builder and wire-shape details. Not implemented by OpenSearch — a request against an OS backend surfaces as an EsError.

Since: 0.26.0.0

importDanglingIndex :: MonadBH m => DanglingIndexUuid -> m Acknowledged Source #

importDanglingIndex re-attaches a dangling index to the cluster metadata via POST _dangling{uuid}. The accept_data_loss=true flag is set by defaultImportDanglingIndexOptions. See importDanglingIndex.

Since: 0.26.0.0

deleteDanglingIndex :: MonadBH m => DanglingIndexUuid -> m Acknowledged Source #

deleteDanglingIndex permanently removes a dangling index's on-disk data via DELETE _dangling{uuid}. See deleteDanglingIndex.

Since: 0.26.0.0

unDanglingIndexUuid :: DanglingIndexUuid -> Text Source #

Deliberately no FromJSON or ToJSON instance: the dangling endpoints never put the UUID in a JSON body, only in the URL path. A bare accessor avoids an IsString implicit coercion in client code (which would defeat the newtype) while keeping the path-render trivially obvious in the request builders.

data DanglingIndex Source #

One entry in the GET /_dangling response. The creation_date_millis field is the epoch-millisecond timestamp at which the index was created; it is required by the spec, so we parse it strictly as an Int.

The node_ids field is the list of node IDs holding the dangling index's data; it is required and emitted as an array by the server.

The index_name is surfaced as plain Text rather than IndexName: a dangling index originated on another cluster and its name may not satisfy this library's index-name validator. Callers that want to re-import it under a sanitized name can do so themselves.

data ImportDanglingIndexOptions Source #

URI parameters accepted by POST _dangling{uuid}.

accept_data_loss is required by the server — the request fails 400 without it. The default defaultImportDanglingIndexOptions sets it to True (the only meaningful value), but the field is exposed in case a future caller wants to inspect or override it (e.g. to render an "I have not consented" request shape for audit logging).

master_timeout and timeout follow the project-wide (unit, magnitude) convention rendered via timeUnitsSuffix (e.g. (TimeUnitSeconds, 30) -> 30s). Nothing omits the parameter.

defaultImportDanglingIndexOptions :: ImportDanglingIndexOptions Source #

True for accept_data_loss (the server-required value), no master_timeout, no timeout.

Index Aliases

updateIndexAliases :: MonadBH m => NonEmpty IndexAliasAction -> m Acknowledged Source #

updateIndexAliases updates the server's index alias table. Operations are atomic. Explained in further detail at https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-aliases.html

>>> let src = IndexName "a-real-index"
>>> let aliasName = IndexName "an-alias"
>>> let iAlias = IndexAlias src (IndexAliasName aliasName)
>>> let aliasCreate = defaultIndexAliasCreate
>>> _ <- runBH' $ deleteIndex src
>>> isSuccess <$> runBH' (createIndex defaultIndexSettings src)
True
>>> runBH' $ indexExists src
True
>>> isSuccess <$> runBH' (updateIndexAliases (AddAlias iAlias aliasCreate :| []))
True
>>> runBH' $ indexExists aliasName
True

updateIndexAliasesWith :: MonadBH m => UpdateAliasesOptions -> NonEmpty IndexAliasAction -> m Acknowledged Source #

updateIndexAliasesWith is the fully-parameterised form of updateIndexAliases. See Database.Bloodhound.Common.Requests for the underlying builder and UpdateAliasesOptions for the available URI parameters.

data UpdateAliasesOptions Source #

The URI parameters accepted by POST /_aliases (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-aliases.html): master_timeout (the pre-7.16 alias of cluster_manager_timeout, still accepted by every supported backend) and timeout. Both are modelled as a magnitude paired with a TimeUnits suffix (e.g. (TimeUnitSeconds, 30) renders as 30s).

Every field is optional, so defaultUpdateAliasesOptions produces no query string at all — byte-for-byte identical to a parameterless call to updateIndexAliases.

defaultUpdateAliasesOptions :: UpdateAliasesOptions Source #

UpdateAliasesOptions with every parameter set to Nothing. Produces no query string, so updateIndexAliasesWith defaultUpdateAliasesOptions emits a request identical to updateIndexAliases.

updateAliasesOptionsParams :: UpdateAliasesOptions -> [(Text, Maybe Text)] Source #

Render UpdateAliasesOptions as a list of (key, value) pairs suitable for withQueries. Nothing fields are omitted, so defaultUpdateAliasesOptions produces an empty list (and therefore no query string).

createIndexAlias :: MonadBH m => IndexName -> IndexAliasName -> IndexAliasCreate -> m Acknowledged Source #

Add an alias to a single index via PUT {index}_alias/{name} — the non-atomic, single-action variant of updateIndexAliases. Pass defaultIndexAliasCreate for an empty body. Returns the server's Acknowledged flag.

>>> _ <- runBH' $ createIndexAlias (IndexName "my-index") (IndexAliasName (IndexName "my-alias")) defaultIndexAliasCreate

getIndexAliases :: MonadBH m => m IndexAliasesSummary Source #

Get all aliases configured on the server.

getIndexAlias :: MonadBH m => IndexName -> Maybe AliasName -> m IndexAliasesInfo Source #

Get aliases for a single source index, optionally narrowed to one alias name (GET {index}_alias[/{name}]). See Database.Bloodhound.Common.Requests for the underlying builder and the wire-shape details. A missing index or named alias surfaces as an EsError (404); wrap with tryEsError for a miss-tolerant variant.

>>> IndexAliasesInfo _ <- runBH' $ getIndexAlias (IndexName "my-index") (Just (AliasName (IndexName "my-alias")))

deleteIndexAlias :: MonadBH m => IndexAliasName -> m Acknowledged Source #

Delete a single alias name, removing it from every index it is currently associated with (the underlying request uses the _all wildcard). See deleteIndexAliasFrom for a per-source-index variant.

deleteIndexAliasFrom :: MonadBH m => IndexName -> IndexAliasName -> m Acknowledged Source #

Remove an alias from a single source index, hitting DELETE {index}_alias/{name}. Leaves any other index publishing the same alias name untouched.

aliasExists :: MonadBH m => IndexAliasName -> m Bool Source #

Check whether an alias name exists anywhere in the cluster, hitting HEAD _alias{name}. Returns False when the alias is absent (404) rather than throwing.

>>> present <- runBH' $ aliasExists (IndexAliasName (IndexName "my-alias"))

defaultIndexAliasCreate :: IndexAliasCreate Source #

IndexAliasCreate with every field set to Nothing. Renders to the empty object {}. New code is encouraged to start from defaultIndexAliasCreate and override individual fields via the ...Lens accessors:

let body = defaultIndexAliasCreate { aliasCreateIsWriteIndex = Just True }
in updateIndexAliases (AddAlias alias body :| [])

Index Templates

putTemplate :: MonadBH m => IndexTemplate -> TemplateName -> m Acknowledged Source #

putTemplate creates a template given an IndexTemplate and a TemplateName. Explained in further detail at https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-templates.html

>>> let idxTpl = IndexTemplate [IndexPattern "tweet-*"] (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
>>> resp <- runBH' $ putTemplate idxTpl (TemplateName "tweet-tpl")

templateExists :: MonadBH m => TemplateName -> m Bool Source #

templateExists checks to see if a template exists.

>>> exists <- runBH' $ templateExists (TemplateName "tweet-tpl")

getTemplate :: MonadBH m => Maybe TemplateNamePattern -> m [TemplateInfo] Source #

getTemplate fetches legacy templates (the GET /_template endpoint). Read-side counterpart of putTemplate. See getTemplate for the wire envelope details and the TemplateInfo body shape.

(https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-template.html)

deleteTemplate :: MonadBH m => TemplateName -> m Acknowledged Source #

deleteTemplate is an HTTP DELETE and deletes a template.

>>> let idxTpl = IndexTemplate [IndexPattern "tweet-*"] (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
>>> _ <- runBH' $ putTemplate idxTpl (TemplateName "tweet-tpl")
>>> resp <- runBH' $ deleteTemplate (TemplateName "tweet-tpl")

data ComponentTemplate Source #

Request body for PUT _component_template{name}. The cpTemplate content is the same ComposableTemplateContent shape used by ComposableTemplate (settings / mappings / aliases), reused here verbatim — the inner template object is byte-identical between the two endpoints. Every field is optional and emitted only when present (via omitNulls), so a minimal ComponentTemplate with Nothing everywhere produces {} on the wire, which the server accepts as an empty component template.

Constructors

ComponentTemplate 

Fields

  • cpTemplate :: Maybe ComposableTemplateContent

    template. The settings / mappings / aliases contributed by this component template. Nothing is unusual but valid (a component template that only carries metadata).

  • cpVersion :: Maybe Int

    version. Opaque version number for external tracking. Used by built-in templates (e.g. logs-settings) for upgrade ordering.

  • cpMeta :: Maybe Object

    _meta. Optional user metadata, stored in the cluster state. May have any contents; keeping it short is preferable.

  • cpDeprecated :: Maybe Bool

    deprecated. Marks this component template as deprecated. Creating or updating a non-deprecated template that composes a deprecated component emits a deprecation warning.

data ComposableTemplate Source #

Request body for PUT _index_template{name}. The index_patterns field is required by the server; the ctTemplate content and every metadata field is optional and emitted only when present and non-empty (via omitNulls, so Nothing and Just [] both render to no field), so a minimal ComposableTemplate with just ctIndexPatterns = [...] produces {"index_patterns": [...]} on the wire.

Constructors

ComposableTemplate 

Fields

  • ctIndexPatterns :: [IndexPattern]

    index_patterns. One or more glob patterns matched against new index names. Reuses the IndexPattern newtype from the legacy IndexTemplate API.

  • ctTemplate :: Maybe ComposableTemplateContent

    template. The settings / mappings / aliases applied to matching indices. Nothing is unusual but valid (a template that only contributes composed_of).

  • ctPriority :: Maybe Int

    priority. When several templates match an index, the highest priority wins and its template (merged with lower-priority templates that also matched) is applied.

  • ctVersion :: Maybe Int

    version. Opaque version number for external tracking.

  • ctComposedOf :: Maybe [TemplateName]

    composed_of. Names of component templates (created via PUT _component_template{name}) whose content is merged into this template, in the given order.

  • ctAllowAutoCreate :: Maybe Bool

    allow_auto_create. Overrides the cluster-wide action.auto_create_index setting for indices matched by this template.

data ComposableTemplateContent Source #

Inner template object of a ComposableTemplate. Carries the settings, mappings and aliases that Elasticsearch applies to every new index matching the surrounding ComposableTemplate's index_patterns. Every field is optional — omitting one leaves the server free to derive it from a component template or its defaults — and each is encoded as a raw JSON Value so callers can express arbitrary settings (not just the typed subset modelled by IndexSettings), exactly like CreateIndexOptions does for PUT /{index}.

Constructors

ComposableTemplateContent 

Fields

  • ctcSettings :: Maybe Value

    settings body field. Note that the composable template's settings object is flat — e.g. {"number_of_shards": 1, "index.refresh_interval": "1s"} — so passing toJSON defaultIndexSettings is wrong (it produces the wrapped {"settings":{"index":{...}}} shape used by PUT /{index}). Hand-roll an Object with the flat keys instead, exactly as for cioSettings on OpenSearch clusters.

  • ctcMappings :: Maybe Value

    mappings body field. Pass any ToJSONable mapping blob, e.g. toJSON TweetMapping.

  • ctcAliases :: Maybe Object

    aliases body field. Each key is an alias name; each value is an (optionally empty) alias body.

data ComposableTemplateOptions Source #

URI parameters accepted by PUT _index_template{name} that are modelled here: create (fail the request if a template with the given name already exists, instead of upserting), master_timeout (the pre-7.16 alias of cluster_manager_timeout, still accepted by every supported backend) and cause (an opaque reason string recorded in the server logs). Every field is optional so defaultComposableTemplateOptions renders to no parameters at all — byte-for-byte identical to a parameterless call via putIndexTemplate.

Constructors

ComposableTemplateOptions 

Fields

  • ctoCreate :: Maybe Bool

    create. When Just True the server returns a 4xx if a template with the same name already exists.

  • ctoMasterTimeout :: Maybe (TimeUnits, Word32)

    master_timeout, encoded as a magnitude paired with a TimeUnits suffix (e.g. (TimeUnitSeconds, 30) renders as 30s).

  • ctoCause :: Maybe Text

    cause. Opaque reason string recorded in the server logs. Rendered verbatim by the (dumbed-down) withQueries renderer, so it must not contain characters that require URL-encoding (spaces, &, =, ...).

defaultComposableTemplateOptions :: ComposableTemplateOptions Source #

ComposableTemplateOptions with every parameter set to Nothing. Produces no query string, so putIndexTemplateWith name tpl defaultComposableTemplateOptions emits a request identical to putIndexTemplate.

composableTemplateOptionsParams :: ComposableTemplateOptions -> [(Text, Maybe Text)] Source #

Render ComposableTemplateOptions as a list of (key, value) pairs suitable for withQueries. Nothing fields are omitted, so defaultComposableTemplateOptions produces an empty list (and therefore no query string).

putIndexTemplate :: MonadBH m => TemplateName -> ComposableTemplate -> m Acknowledged Source #

putIndexTemplate creates or updates a composable index template (the PUT _index_template{name} endpoint, available since Elasticsearch 7.8 and in OpenSearch 2.x). This is the modern replacement for the legacy putTemplate (which targets PUT /_template): composable templates can be assembled from reusable component templates and carry an explicit priority for deterministic conflict resolution.

Unlike the legacy putTemplate this surfaces 4xx responses as EsErrors. To fail when a template with the given name already exists, use putIndexTemplateWith with ctoCreate = Just True.

(https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-put-index-template.html)

putIndexTemplateWith :: MonadBH m => TemplateName -> ComposableTemplate -> ComposableTemplateOptions -> m Acknowledged Source #

Like putIndexTemplate but additionally accepts ComposableTemplateOptions rendered as URI parameters. Use defaultComposableTemplateOptions to send no parameters at all.

getIndexTemplate :: MonadBH m => Maybe TemplateNamePattern -> m [IndexTemplateInfo] Source #

getIndexTemplate fetches composable index templates (the GET /_index_template endpoint). Read-side counterpart of putIndexTemplate.

  • Nothing → list every composable template on the cluster.
  • Just (TemplateNamePattern p) → list the templates whose names match p (a literal name or a glob such as "logs-*"; the server does the matching). A pattern that matches no template surfaces as an EsError (HTTP 404); wrap with tryPerformBHRequest if you need miss-tolerant lookup.

The body of each returned IndexTemplateInfo is decoded into a ComposableTemplate.

(https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-template.html)

deleteIndexTemplate :: MonadBH m => TemplateName -> m Acknowledged Source #

deleteIndexTemplate deletes a composable index template (DELETE _index_template{name}). It is the write-side counterpart of putIndexTemplate. Like getIndexTemplate, a 404 for a missing template is surfaced as an EsError; wrap with tryPerformBHRequest for miss-tolerant deletion.

putComponentTemplate :: MonadBH m => TemplateName -> ComponentTemplate -> m Acknowledged Source #

putComponentTemplate creates or updates a reusable component template (PUT _component_template{name}, available since Elasticsearch 7.8 and in OpenSearch 2.x). Component templates are building blocks composed into composable index templates (see ComposableTemplate's composed_of field); they have no index_patterns of their own.

Like putIndexTemplate, this surfaces 4xx responses as EsErrors.

(https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-component-template.html)

deleteComponentTemplate :: MonadBH m => TemplateName -> m Acknowledged Source #

deleteComponentTemplate deletes a reusable component template (DELETE _component_template{name}). It is the write-side counterpart of putComponentTemplate. Like deleteIndexTemplate, a 404 for a missing template is surfaced as an EsError; wrap with tryPerformBHRequest for miss-tolerant deletion.

newtype GetIndexTemplatesResponse Source #

Envelope returned by GET /_index_template. The server wraps the matching templates in a single index_templates array (see IndexTemplateInfo); this newtype peels off that outer key.

data TemplateInfo Source #

One entry in a GET /_template response: the template's name (lifted from the outer JSON key by GetTemplatesResponse) paired with its legacy body fields. Every field except tiName and tiIndexPatterns is optional — ES omits absent fields on the wire rather than emitting null, and Nothing round-trips back to an absent key via the ToJSON instance.

Constructors

TemplateInfo 

Fields

newtype GetTemplatesResponse Source #

Envelope returned by GET /_template. The server returns the matching templates as a single object keyed by template name (each value being a TemplateInfo body); this newtype peels off that outer key, lifting each key into the corresponding entry's tiName.

getComponentTemplate :: MonadBH m => Maybe TemplateNamePattern -> m [ComponentTemplateInfo] Source #

getComponentTemplate fetches reusable component templates (the GET /_component_template endpoint, available since Elasticsearch 7.8 and in OpenSearch 2.x). Read-side counterpart of putComponentTemplate. See getComponentTemplate for the shape of the Maybe TemplateNamePattern argument.

Like getIndexTemplate, this is StatusDependant: a 4xx (in particular a 404 when no component template matches the pattern) is surfaced as an EsError. Callers that want miss-tolerant lookup should use tryPerformBHRequest.

(https://www.elastic.co/guide/en/elasticsearch/reference/7.17/getting-component-templates.html)

data ComponentTemplateInfo Source #

One entry in a GET /_component_template response: the template's name paired with its component_template body (decoded into a ComponentTemplate). The wire shape is {"name": ..., "component_template": {...}}.

newtype GetComponentTemplatesResponse Source #

Envelope returned by GET /_component_template. The server wraps the matching templates in a single component_templates array (see ComponentTemplateInfo); this newtype peels off that outer key.

newtype TemplateNamePattern Source #

A glob pattern matched against template names by GET /_index_template/{pattern} (e.g. "serv*", "logs-*"). The server resolves the wildcard; the client forwards the literal text verbatim, exactly as for TemplateName. Introduced to distinguish the path-style "match many templates" argument from the "identify-one-template" TemplateName used by PUT and DELETE.

Like every path newtype in this library, the value is interpolated into the URL without percent-encoding, so it must not contain /, ? or # — those characters would corrupt the request path or inject spurious query parameters.

data SimulatedTemplate Source #

Response body of POST _index_template_simulate. The template field reuses ComposableTemplateContent because the resolved settings/mappings/aliases shape is identical to the per-template content type. Forward-compat keys survive in stOther.

Constructors

SimulatedTemplate 

Fields

  • stTemplate :: ComposableTemplateContent

    template. The merged settings/mappings/aliases that would be applied to a new index matching the simulated template. Decoded leniently into an empty ComposableTemplateContent when the server omits the key (which is unusual but well-defined).

  • stOverlapping :: [SimulatedTemplateOverlap]

    overlapping. Existing composable templates whose index_patterns overlap the simulated template's patterns. Defaults to [] when the server omits the key (i.e. no overlap).

  • stOther :: Value

    Unmodified source object, so callers can inspect any server-added field (e.g. future Elasticsearch additions) without losing it on round-trip.

data SimulatedTemplateOverlap Source #

One entry in the overlapping array of a SimulatedTemplate response: the name of an existing composable template whose index_patterns overlap the simulated template's patterns. Forward- compat keys survive in stoOther.

Constructors

SimulatedTemplateOverlap 

Fields

  • stoName :: Maybe TemplateName

    name of the overlapping composable template.

  • stoIndexPatterns :: [IndexPattern]

    index_patterns of the overlapping template. Decoded leniently (defaults to [] when the server omits the key).

  • stoOther :: Value

    Unmodified source object, so callers can inspect any server-added field without losing it on round-trip.

simulateIndexTemplate :: MonadBH m => ComposableTemplate -> m SimulatedTemplate Source #

simulateIndexTemplate resolves a hypothetical ComposableTemplate against the templates already registered on the cluster (the POST _index_template_simulate endpoint, available since Elasticsearch 7.8 and in OpenSearch 2.x). The server returns the merged settings/mappings/aliases that would be applied to a new matching index, plus the list of existing composable templates whose index_patterns overlap the supplied template's patterns.

Like putIndexTemplate, this surfaces 4xx responses as EsErrors.

(https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-simulate-template.html)

simulateIndex :: MonadBH m => IndexName -> m SimulatedTemplate Source #

simulateIndex resolves the composable index template(s) that Elasticsearch would apply to a hypothetical new index with the given name (POST _index_template_simulate_index/{name}, available since Elasticsearch 7.8 and in OpenSearch 2.x). Returns the merged settings/mappings/aliases and any lower-priority templates that also matched. Read-only — safe to call without side effects.

This is the index-name-driven counterpart of simulateIndexTemplate (which takes a ComposableTemplate body).

simulateIndexWith :: MonadBH m => IndexName -> ComposableTemplateOptions -> m SimulatedTemplate Source #

Like simulateIndex but additionally accepts ComposableTemplateOptions rendered as URI parameters. Use defaultComposableTemplateOptions to send no parameters at all, in which case the emitted request is byte-for-byte identical to simulateIndex. See simulateIndexWith in the Requests module for the wire-shape details.

Mapping

putMapping :: forall r a m. (MonadBH m, FromJSON r, ToJSON a) => IndexName -> a -> m r Source #

putMapping is an HTTP PUT and has upsert semantics. Mappings are schemas for documents in indexes.

>>> _ <- runBH' $ createIndex defaultIndexSettings testIndex
>>> resp <- runBH' $ putMapping testIndex TweetMapping
>>> print resp
Response {responseStatus = Status {statusCode = 200, statusMessage = "OK"}, responseVersion = HTTP/1.1, responseHeaders = [("content-type","application/json; charset=UTF-8"),("content-encoding","gzip"),("transfer-encoding","chunked")], responseBody = "{\"acknowledged\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}

putMappingWith :: forall r a m. (MonadBH m, FromJSON r, ToJSON a) => IndexName -> a -> PutMappingOptions -> m r Source #

putMappingWith is the fully-parameterised form of putMapping. Every URI parameter accepted by PUT {index}_mapping is exposed via PutMappingOptions. defaultPutMappingOptions makes this byte-for-byte identical to putMapping. See putMappingWith for details.

getMapping :: forall r m. (MonadBH m, FromJSON r) => IndexName -> m r Source #

getMapping fetches the mapping for a given index. Wraps the GET /<index>/_mapping endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-mapping.html).

The response is generic over any FromJSON r, mirroring putMapping. Decode into a Value for an untyped view of the mapping (the response is shaped {<index>: {mappings: {...}}}), or into a custom type. Use getIndex to fetch aliases and settings alongside the mappings in a single request.

getFieldMapping :: forall r m. (MonadBH m, FromJSON r) => IndexName -> [FieldName] -> m r Source #

getFieldMapping fetches the mapping for specific fields of a given index. Wraps the GET /<index>/_mapping/field/<fields> endpoint (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-field-mapping.html).

The response is generic over any FromJSON @r', mirroring getMapping. Decode into a Value for an untyped view, or into FieldMappingResponse for a structured one.

newtype FieldMappingResponse Source #

Response shape for GET /<index>/_mapping/field/<fields> (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-get-field-mapping.html).

The server returns one entry per requested index. Use this type when you want a structured view of the response; decode into a Value instead if you need the raw JSON.

Index names in the response are decoded as Map keys and are therefore not subject to the mkIndexNameSystem validation that IndexName's value-level FromJSON performs; the server may legitimately echo back indices whose names the client would refuse to create.

Documents

indexDocument :: forall doc m. (MonadBH m, ToJSON doc) => IndexName -> IndexDocumentSettings -> doc -> DocId -> m IndexedDocument Source #

indexDocument is the primary way to save a single document in Elasticsearch. The document itself is simply something we can convert into a JSON Value. The DocId will function as the primary key for the document. You are encouraged to generate your own id's and not rely on Elasticsearch's automatic id generation. Read more about it here: https://github.com/bitemyapp/bloodhound/issues/107

>>> resp <- runBH' $ indexDocument testIndex defaultIndexDocumentSettings exampleTweet (DocId "1")
>>> print resp
Response {responseStatus = Status {statusCode = 200, statusMessage = "OK"}, responseVersion = HTTP/1.1, responseHeaders = [("content-type","application/json; charset=UTF-8"),("content-encoding","gzip"),("content-length","152")], responseBody = "{\"_index\":\"twitter\",\"_type\":\"_doc\",\"_id\":\"1\",\"_version\":2,\"result\":\"updated\",\"_shards\":{\"total\":1,\"successful\":1,\"failed\":0},\"_seq_no\":1,\"_primary_term\":1}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}

updateDocument :: forall patch m. (MonadBH m, ToJSON patch) => IndexName -> IndexDocumentSettings -> patch -> DocId -> m IndexedDocument Source #

updateDocument provides a way to perform an partial update of a an already indexed document.

updateDocumentWith :: MonadBH m => IndexName -> IndexDocumentSettings -> UpdateBody -> DocId -> m IndexedDocument Source #

Like updateDocument but accepts the full UpdateBody union, supporting script-driven updates, upserts, doc_as_upsert and scripted_upsert. The IndexDocumentSettings argument still supplies the URI-level parameters shared with the Index API.

data UpdateBody Source #

Body of POST /{index}/_update/{id}. The Elasticsearch Update API takes either a partial document (the doc form) or a script (the script form); the two cannot be mixed in the same request. See docs-update.

The legacy updateDocument function constructs the UpdateDoc form from its patch argument; use updateDocumentWith (added alongside this type) to send the UpdateScript form.

Constructors

UpdateDoc

Partial-document update: sends {"doc": doc}, plus {"doc_as_upsert": true} when ubDocAsUpsert is set so the document is created if it does not yet exist.

UpdateScript

Script-driven update: sends {"script": script-inner, "upsert": doc?, "scripted_upsert": bool?}. ubUpsert is the document inserted if the referenced document does not exist; ubScriptedUpsert = Just True flips that to "always run the script for the upsert too". The script value is rendered via scriptInnerValue (no "script" wrapper) because it is already placed under the top-level "script" key.

mkUpdateDoc :: Value -> UpdateBody Source #

Smart constructor for the {"doc": …} body with no upsert behaviour.

mkUpdateScript :: Script -> UpdateBody Source #

Smart constructor for a script-only update (no upsert document, no scripted_upsert).

updateByQueryWith :: forall a m. (MonadBH m, FromJSON a) => ByQueryOptions -> IndexName -> Query -> Maybe Script -> m a Source #

Like updateByQuery but accepts ByQueryOptions for URI-level parameters (conflicts, wait_for_completion, slices, max_docs, routing, scroll_size, refresh, timeout, scroll, request_cache, pipeline).

rethrottleUpdateByQuery :: MonadBH m => TaskNodeId -> RethrottleRate -> m TaskListResponse Source #

rethrottleUpdateByQuery changes the maximum documents-per-second rate of an in-progress asynchronous update_by_query task. Maps to POST _update_by_query{task_id}/_rethrottle?requests_per_second=n. Returns a TaskListResponse (same shape as cancelTask) listing the task(s) whose rate was changed — an empty node list means the task had already finished. Pass the TaskNodeId returned by an asynchronous updateByQueryWith (called with bqoWaitForCompletion = Just False). Use RethrottleUnlimited to disable throttling, or RethrottlePerSecond n for any non-negative decimal rate.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/docs-update-by-query.html#docs-update-by-query-rethrottle-api.

getDocument :: (MonadBH m, FromJSON a) => IndexName -> DocId -> m (EsResult a) Source #

getDocument is a straight-forward way to fetch a single document from Elasticsearch using a Server, IndexName, and a DocId. The DocId is the primary key for your Elasticsearch document.

>>> yourDoc <- runBH' $ getDocument testIndex (DocId "1")

getDocumentWith :: forall a m. (MonadBH m, FromJSON a) => GetDocumentOptions -> IndexName -> DocId -> m (EsResult a) Source #

Like getDocument but accepts GetDocumentOptions for URI-level parameters (_source, _source_includes/_source_excludes, stored_fields, preference, realtime, refresh, routing, version, version_type).

getDocumentSource :: forall a m. (MonadBH m, FromJSON a) => IndexName -> DocId -> m (Maybe a) Source #

getDocumentSource fetches only the _source of a document (no metadata envelope). Maps to GET /{index}/_doc/{id}/_source. Returns Nothing when the document does not exist (HTTP 404); other non-2xx responses throw EsError (use tryPerformBHRequest to surface them as Either EsError (Maybe a) instead).

getDocumentSourceWith :: forall a m. (MonadBH m, FromJSON a) => GetDocumentSourceOptions -> IndexName -> DocId -> m (Maybe a) Source #

Like getDocumentSource but accepts GetDocumentSourceOptions carrying the source-filtering and routing parameters that apply to the source-only endpoint.

getDocumentsWith :: forall a m. (MonadBH m, FromJSON a) => MultiGetOptions -> IndexName -> [DocId] -> m (MultiGetResponse a) Source #

Like getDocuments but accepts MultiGetOptions applied at the URI level.

getDocumentsMultiWith :: forall a m. (MonadBH m, FromJSON a) => MultiGetOptions -> MultiGet -> m (MultiGetResponse a) Source #

Like getDocumentsMulti but accepts MultiGetOptions applied at the URI level. Per-document filtering is carried by the MultiGet body.

data TermVectors Source #

Response body for POST /{index}/_termvectors/{id}.

The _index and _id fields are kept as raw Text (matching the EsResult wrapper) rather than parsed into IndexName, so that unusual system-index names that fail the IndexName validator do not cause the whole response to be rejected. The spec marks _id as optional on this response; termVectorsId therefore defaults to DocId "" when the server omits it (rather than failing the decode or exposing a Maybe).

data FieldTermVectors Source #

Per-field term-vector block. The field_statistics object is only present when the request asked for it (termVectorsRequestFieldStatistics = Just True); terms is always present when the field exists in the document, and is empty if the field has no indexed terms.

data TermVectorToken Source #

A single token occurrence of a term. position, start_offset, end_offset are present when the request enabled positions/offsets respectively; payload is present when payloads are enabled and the token carries one.

data TermVectorsRequest Source #

Body for POST /{index}/_termvectors/{id}. Every field is Maybe; defaultTermVectorsRequest leaves them all Nothing so the server falls back to its documented defaults (offsets=true, positions=true, field_statistics=true, term_statistics=false, payload=true, no fields filter).

Note that the server defaults are not echoed back by the encoder: a Nothing field is simply omitted, producing the same wire shape as a request with no body at all when no field is set.

defaultTermVectorsRequest :: TermVectorsRequest Source #

TermVectorsRequest with every field set to Nothing. Sending this to the server reproduces the legacy parameterless behaviour of the endpoint.

data TermVectorsOptions Source #

URI parameters of the POST /{index}/_termvectors/{id}, POST /_mtermvectors, and POST /{index}/_mtermvectors endpoints. See docs-termvectors.

Every field is Maybe; defaultTermVectorsOptions leaves them all Nothing so the legacy parameterless getTermVectors / getMultiTermVectors entry points remain byte-for-byte identical on the wire, and termVectorsOptionsParams drops Nothing fields via catMaybes.

Constructors

TermVectorsOptions 

Fields

defaultTermVectorsOptions :: TermVectorsOptions Source #

TermVectorsOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless getTermVectors / getMultiTermVectors / getMultiTermVectorsByIndex.

termVectorsOptionsParams :: TermVectorsOptions -> [(Text, Maybe Text)] Source #

Render a TermVectorsOptions record as a key=value list for withQueries. Nothing fields are omitted; the order of the list is stable but unspecified.

getTermVectors :: MonadBH m => IndexName -> DocId -> TermVectorsRequest -> m TermVectors Source #

getTermVectors returns information and statistics about the terms in the fields of a particular document. Maps to POST /{index}/_termvectors/{id}. Pass defaultTermVectorsRequest to reproduce the parameterless form; populate TermVectorsRequest fields to request fields, offsets, positions, term_statistics, field_statistics, payload, or apply a TermVectorsFilter.

getTermVectorsWith :: MonadBH m => TermVectorsOptions -> IndexName -> DocId -> TermVectorsRequest -> m TermVectors Source #

Like getTermVectors but accepts TermVectorsOptions carrying the URI-level parameters (preference, realtime, routing, version, version_type). defaultTermVectorsOptions makes the wire output byte-identical to getTermVectors.

data MultiTermVectorsDoc Source #

One document entry in a MultiTermVectors body. Fields mirror TermVectorsRequest so each document can override the fields/offsets/positions/term_statistics/ field_statistics/payload/filter knobs independently. multiTermVectorsDocIndex is only required when the index is not already in the URL path (i.e. when calling getMultiTermVectors rather than the by-index variant).

mkMultiTermVectorsDoc :: DocId -> MultiTermVectorsDoc Source #

Construct a MultiTermVectorsDoc from just its id, with no _index and no per-doc parameter overrides. The most common case when targeting a single index via the URL-path variant (getMultiTermVectorsByIndex).

getMultiTermVectors :: MonadBH m => MultiTermVectors -> m MultiTermVectorsResponse Source #

getMultiTermVectors returns term vectors for multiple documents in a single request. Maps to POST /_mtermvectors (no index in the URL). Each MultiTermVectorsDoc must carry its own _index. For the single-index form, see getMultiTermVectorsByIndex.

getMultiTermVectorsWith :: MonadBH m => TermVectorsOptions -> MultiTermVectors -> m MultiTermVectorsResponse Source #

Like getMultiTermVectors but accepts TermVectorsOptions carrying the URI-level parameters (preference, realtime, routing, version, version_type). defaultTermVectorsOptions makes the wire output byte-identical to getMultiTermVectors.

getMultiTermVectorsByIndex :: MonadBH m => IndexName -> [DocId] -> m MultiTermVectorsResponse Source #

getMultiTermVectorsByIndex is the single-index form of getMultiTermVectors. Maps to POST /{index}/_mtermvectors. Each DocId is wrapped with mkMultiTermVectorsDoc (no per-doc _index, no parameter overrides); for per-document overrides, build the MultiTermVectors body directly and use getMultiTermVectors.

getMultiTermVectorsByIndexWith :: MonadBH m => TermVectorsOptions -> IndexName -> [DocId] -> m MultiTermVectorsResponse Source #

Like getMultiTermVectorsByIndex but accepts TermVectorsOptions carrying the URI-level parameters (preference, realtime, routing, version, version_type). defaultTermVectorsOptions makes the wire output byte-identical to getMultiTermVectorsByIndex.

data GetDocumentOptions Source #

URI parameters of the GET /{index}/_doc/{id} endpoint and its multi-get siblings. See docs-get and docs-multi-get.

Constructors

GetDocumentOptions 

Fields

  • gdoSource :: Maybe Bool

    _source — when Just False the source is omitted from the response entirely. Just True emits _source=true explicitly (the server treats it the same as Nothing, which omits the parameter and relies on the default of returning the source).

  • gdoSourceIncludes :: Maybe Text

    _source_includes — comma-separated field globs to include.

  • gdoSourceExcludes :: Maybe Text

    _source_excludes — comma-separated field globs to exclude.

  • gdoStoredFields :: Maybe Text

    stored_fields — comma-separated list of stored fields to return. Note this is the deprecated 7.x field-selection mechanism; new code should prefer the fields body field of _search. It is still honoured by the GET API.

  • gdoPreference :: Maybe Text

    preference — shard/route preference, e.g. "_local".

  • gdoRealtime :: Maybe Bool

    realtime — when Just False, fetch the document from the index rather than the translog (realtime). Defaults to true.

  • gdoRefresh :: Maybe Bool

    refresh — when Just True, refresh the relevant shard before fetching so the GET sees the effect of the most recent indexed document.

  • gdoRouting :: Maybe Text

    routing — target shard routing value. Must match the value used at index time for routed documents.

  • gdoVersion :: Maybe Word64

    version — return the document only if its current version matches. Typically combined with gdoVersionType = external.

  • gdoVersionType :: Maybe VersionType

    version_type — how to interpret gdoVersion. See the VersionType renderer for the accepted values.

defaultGetDocumentOptions :: GetDocumentOptions Source #

GetDocumentOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless getDocument.

data GetDocumentSourceOptions Source #

URI parameters of the GET /{index}/_doc/{id}/_source endpoint. This is a subset of GetDocumentOptions: the _source=true/_source=false toggle is meaningless for a source-only endpoint (the whole response is the _source object), and stored_fields is not honoured by the source API (it belongs to the full GET envelope). See docs-get-source-api.

Constructors

GetDocumentSourceOptions 

Fields

defaultGetDocumentSourceOptions :: GetDocumentSourceOptions Source #

GetDocumentSourceOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the parameterless getDocumentSource.

data MultiGetOptions Source #

URI parameters of the POST /_mget and POST {index}_mget endpoints. See docs-multi-get.

Every field is Maybe; defaultMultiGetOptions leaves them all Nothing so the legacy parameterless getDocuments / getDocumentsMulti entry points remain byte-for-byte identical on the wire, and multiGetOptionsParams drops Nothing fields via catMaybes.

Per-document _source/stored_fields filtering is not carried here — it lives on each MultiGetDoc in the MultiGet body, and overrides the URI-level setting for that single document.

Constructors

MultiGetOptions 

Fields

  • mgoSource :: Maybe Bool

    _source — when Just False the source is omitted from every response entirely. Just True emits _source=true explicitly (the server treats it the same as Nothing, which omits the parameter and relies on the default of returning the source).

  • mgoSourceIncludes :: Maybe Text

    _source_includes — comma-separated field globs to include.

  • mgoSourceExcludes :: Maybe Text

    _source_excludes — comma-separated field globs to exclude.

  • mgoStoredFields :: Maybe Text

    stored_fields — comma-separated list of stored fields to return. Note this is the deprecated 7.x field-selection mechanism; new code should prefer the fields body field of _search. It is still honoured by the multi-get API.

  • mgoPreference :: Maybe Text

    preference — shard/route preference, e.g. "_local".

  • mgoRealtime :: Maybe Bool

    realtime — when Just False, fetch documents from the index rather than the translog (realtime). Defaults to true.

  • mgoRefresh :: Maybe Bool

    refresh — when Just True, refresh the relevant shards before fetching so the multi-get sees the effect of the most recent indexed documents.

  • mgoRouting :: Maybe Text

    routing — target shard routing value. Must match the value used at index time for routed documents; applies to every requested document. Per-document routing is not yet modelled on MultiGetDoc (the per-doc _index IS available via multiGetDocIndex; only _routing is missing).

defaultMultiGetOptions :: MultiGetOptions Source #

MultiGetOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless getDocuments / getDocumentsMulti.

data DeleteDocumentOptions Source #

URI parameters of the DELETE /{index}/_doc/{id} endpoint. See docs-delete.

This is a hybrid of GetDocumentOptions (for the read-side version/version_type/routing parameters, which use the simple Word64 + VersionType form rather than the write-side VersionControl ADT — delete has no "force" or "external_gte" semantics) and IndexDocumentSettings (for the write-side refresh, wait_for_active_shards, if_seq_no/if_primary_term parameters, which share their types with the Index API).

timeout has no dedicated newtype in this library yet and is passed through as Text (e.g. "5s"), matching ByQueryOptions's bqoTimeout.

Constructors

DeleteDocumentOptions 

Fields

defaultDeleteDocumentOptions :: DeleteDocumentOptions Source #

DeleteDocumentOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless deleteDocument.

data DocumentExistsOptions Source #

URI parameters of the HEAD /{index}/_doc/{id} existence check. See docs-get-api-query-params.

This is the HEAD counterpart of GetDocumentOptions restricted to the parameters that influence shard selection freshness OCC on a request that carries no body: the _source/_source_includes/ _source_excludes toggles are meaningless (a HEAD returns no body), but stored_fields is still a documented parameter and is kept here for API-surface completeness. refresh uses the read-side Bool form (pre-check, like GetDocumentOptions's gdoRefresh) rather than the write-side RefreshPolicy.

Constructors

DocumentExistsOptions 

Fields

  • deoStoredFields :: Maybe Text

    stored_fields — documented for the HEAD API though it has no body to populate; kept for completeness. Comma-separated list of stored fields.

  • deoPreference :: Maybe Text

    preference — shard/route preference, e.g. "_local".

  • deoRealtime :: Maybe Bool

    realtime — when Just False, perform the existence check against the index rather than the translog (realtime). Defaults to true.

  • deoRefresh :: Maybe Bool

    refresh — when Just True, refresh the relevant shard before the check so the HEAD sees the effect of the most recent indexed document.

  • deoRouting :: Maybe Text

    routing — target shard routing value. Must match the value used at index time for routed documents.

  • deoVersion :: Maybe Word64

    version — report existence only if the document's current version matches. Typically combined with deoVersionType = external.

  • deoVersionType :: Maybe VersionType

    version_type — how to interpret deoVersion. See the VersionType renderer for the accepted values.

defaultDocumentExistsOptions :: DocumentExistsOptions Source #

DocumentExistsOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless documentExists.

data DocumentSourceExistsOptions Source #

URI parameters of the HEAD /{index}/_doc/{id}/_source existence check. See docs-get-source-api.

This is the HEAD counterpart of GetDocumentSourceOptions: a strict subset of DocumentExistsOptions that drops stored_fields (the source API does not honour it). The _source toggle is meaningless for a source-only endpoint and is also absent.

Constructors

DocumentSourceExistsOptions 

Fields

defaultDocumentSourceExistsOptions :: DocumentSourceExistsOptions Source #

DocumentSourceExistsOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless documentSourceExists.

data ByQueryOptions Source #

Shared URI parameters of POST /{index}/_update_by_query and POST /{index}/_delete_by_query. The two endpoints accept the same parameter set (see the ES docs); a single record therefore covers both. The body is not affected — only the URI.

Constructors

ByQueryOptions 

Fields

data ConflictsPolicy Source #

How the update_by_query / delete_by_query conflicts URI parameter should behave when a version conflict occurs. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/docs-update-by-query.html#docs-update-by-query-api-query-params.

Constructors

ConflictsProceed

conflicts=proceed — continue processing the remaining documents when a version conflict is encountered.

ConflictsAbort

conflicts=abort — abort the request on the first conflict. This is the server-side default.

data Slices Source #

The slices parameter — the number of sub-tasks to parallelise the by-query work across. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/docs-update-by-query.html#docs-update-by-query-api-slices.

Constructors

SlicesAuto

slices=auto — let the server pick (typically one per shard). Recommended in the docs.

SlicesCount Natural

slices=n — explicit slice count.

defaultByQueryOptions :: ByQueryOptions Source #

ByQueryOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless updateByQuery and deleteByQuery.

documentExistsWith :: MonadBH m => DocumentExistsOptions -> IndexName -> DocId -> m Bool Source #

Like documentExists but accepts DocumentExistsOptions for the URI-level parameters (stored_fields, preference, realtime, refresh, routing, version, version_type). See documentExistsWith for the wire-level details.

documentSourceExists :: MonadBH m => IndexName -> DocId -> m Bool Source #

documentSourceExists checks whether _source is present for the given document, hitting HEAD /{index}/_doc/{id}/_source. Returns False on any non-2xx status (including 404); see documentSourceExists for the wire-level details.

documentSourceExistsWith :: MonadBH m => DocumentSourceExistsOptions -> IndexName -> DocId -> m Bool Source #

Like documentSourceExists but accepts DocumentSourceExistsOptions for the URI-level parameters (preference, realtime, refresh, routing, version, version_type). See documentSourceExistsWith for the wire-level details.

deleteDocument :: MonadBH m => IndexName -> DocId -> m IndexedDocument Source #

deleteDocument is the primary way to delete a single document.

>>> _ <- runBH' $ deleteDocument testIndex (DocId "1")

deleteDocumentWith :: MonadBH m => DeleteDocumentOptions -> IndexName -> DocId -> m IndexedDocument Source #

Like deleteDocument but accepts DeleteDocumentOptions for URI-level parameters (wait_for_active_shards, refresh, routing, timeout, version, version_type, if_seq_no, if_primary_term).

deleteByQuery :: (MonadBH m, FromJSON a) => IndexName -> Query -> m a Source #

deleteByQuery performs a deletion on every document that matches a query.

>>> let query = TermQuery (Term "user" "bitemyapp") Nothing
>>> _ <- runBH' $ deleteByQuery testIndex query

deleteByQueryWith :: forall a m. (MonadBH m, FromJSON a) => ByQueryOptions -> IndexName -> Query -> m a Source #

Like deleteByQuery but accepts ByQueryOptions for URI-level parameters (same set as updateByQueryWith). The response type is polymorphic: instantiate at TaskNodeId when called with bqoWaitForCompletion = Just False to get the async task id.

rethrottleDeleteByQuery :: MonadBH m => TaskNodeId -> RethrottleRate -> m TaskListResponse Source #

rethrottleDeleteByQuery changes the maximum documents-per-second rate of an in-progress asynchronous delete_by_query task. Maps to POST _delete_by_query{task_id}/_rethrottle?requests_per_second=n. Returns a TaskListResponse (same shape as cancelTask) listing the task(s) whose rate was changed — an empty node list means the task had already finished. Pass the TaskNodeId returned by an asynchronous deleteByQueryWith (called with bqoWaitForCompletion = Just False). Use RethrottleUnlimited to disable throttling, or RethrottlePerSecond n for any non-negative decimal rate.

See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/docs-delete-by-query.html#docs-delete-by-query-rethrottle-api.

Searching

searchAll :: forall a m. (MonadBH m, FromJSON a) => Search -> m (SearchResult a) Source #

searchAll, given a Search, will perform that search against all indexes on an Elasticsearch server. Try to avoid doing this if it can be helped.

>>> let query = TermQuery (Term "user" "bitemyapp") Nothing
>>> let search = mkSearch (Just query) Nothing
>>> response <- runBH' $ searchAll search

searchAllWith :: forall a m. (MonadBH m, FromJSON a) => SearchOptions -> Search -> m (SearchResult a) Source #

searchAllWith is a variant of searchAll that accepts a SearchOptions record for URI-level parameters such as preference, routing, and request_cache. See SearchOptions for the full set.

multiSearchWith :: forall a m. (MonadBH m, FromJSON a) => SearchOptions -> NonEmpty MultiSearchItem -> m (MultiSearchResponse a) Source #

multiSearchWith is a variant of multiSearch that accepts a SearchOptions record for URI-level parameters (max_concurrent_searches, typed_keys, ...). Per-header fields ride on each MultiSearchItem.

data MultiSearchTemplateItem Source #

One item in an _msearch/template request body.

The header line of each NDJSON pair carries the same per-search hints as MultiSearchItem (see https://www.elastic.co/guide/en/elasticsearch/reference/7.17/search-multi-search-template.html):

index
target index, optional at the request level
routing
custom routing value(s)
search_type
query_then_fetch or dfs_query_then_fetch
preference
shard preference, e.g. _local
allow_partial_search_results
tolerate shard failures for this item

The body line is a SearchTemplate rendered by its existing ToJSON instance (source/id, params, explain, profile).

Constructors

MultiSearchTemplateItem 

Fields

multiSearchTemplate :: forall a m. (MonadBH m, FromJSON a) => NonEmpty MultiSearchTemplateItem -> m (MultiSearchResponse a) Source #

multiSearchTemplate performs a multi-search template request against _msearch/template. Each MultiSearchTemplateItem pairs a per-sub-request header with a SearchTemplate body. See multiSearchTemplate.

multiSearchTemplateByIndex :: forall a m. (MonadBH m, FromJSON a) => IndexName -> NonEmpty SearchTemplate -> m (MultiSearchResponse a) Source #

multiSearchTemplateByIndex runs an _msearch/template scoped to a single index.

searchByIndex :: forall a m. (MonadBH m, FromJSON a) => IndexName -> Search -> m (SearchResult a) Source #

searchByIndex, given a Search and an IndexName, will perform that search within an index on an Elasticsearch server.

>>> let query = TermQuery (Term "user" "bitemyapp") Nothing
>>> let search = mkSearch (Just query) Nothing
>>> response <- runBH' $ searchByIndex testIndex search

searchByIndexWith :: forall a m. (MonadBH m, FromJSON a) => IndexName -> SearchOptions -> Search -> m (SearchResult a) Source #

searchByIndexWith is a variant of searchByIndex that accepts a SearchOptions record for URI-level parameters such as preference, routing, and request_cache. See SearchOptions for the full set.

>>> let opts = defaultSearchOptions { soPreference = Just "_local", soRequestCache = Just True }
>>> response <- runBH' $ searchByIndexWith testIndex opts search

searchByIndices :: forall a m. (MonadBH m, FromJSON a) => NonEmpty IndexName -> Search -> m (SearchResult a) Source #

searchByIndices is a variant of searchByIndex that executes a Search over many indices. This is much faster than using mapM to searchByIndex over a collection since it only causes a single HTTP request to be emitted.

searchByIndicesWith :: forall a m. (MonadBH m, FromJSON a) => NonEmpty IndexName -> SearchOptions -> Search -> m (SearchResult a) Source #

searchByIndicesWith is a variant of searchByIndices that accepts a SearchOptions record for URI-level parameters. See SearchOptions for the full set.

explainDocument :: MonadBH m => IndexName -> DocId -> Query -> m ExplainResponse Source #

explainDocument computes a score explanation for a single document under a given Query (see ES docs, OpenSearch docs).

See explainDocument for the full semantics, in particular the three distinguishable outcomes: matched; doc exists but query does not match (explanation is Just (Explanation 0.0 ...)); and missing document (explanation is Nothing). A missing document does not surface as an EsError — its HTTP-404 body is shaped like an ExplainResponse and decodes cleanly as ExplainResponse { explainResponseMatched = False, explainResponseExplanation = Nothing }.

explainDocumentWith :: MonadBH m => ExplainOptions -> IndexName -> DocId -> Query -> m ExplainResponse Source #

Like explainDocument but accepts an ExplainOptions record carrying the URI-level _explain parameters (routing, preference, stored_fields, _source filtering, and the query-parsing default_operator/analyzer/df/ analyze_wildcard/lenient). defaultExplainOptions makes this byte-for-byte equivalent to explainDocument. See explainDocumentWith for the full semantics.

data ExplainOptions Source #

URI parameters of the POST /{index}/_explain/{id} endpoint. See ES _explain docs and OpenSearch _explain docs.

Every field is Maybe; defaultExplainOptions leaves them all Nothing, which emits no query string and is therefore byte-for-byte equivalent to the legacy parameterless explainDocument.

Important: explainDocumentWith always sends the Query as a JSON body ({"query": ...}). The five query-parsing parameters below are only honoured by the server when _explain is driven by a URI-mode q=... query string, which this client does not currently emit — they are therefore inert on the wire today and are modelled here prospectively (so a future URI-search variant can expose them without a schema change). Setting them has no effect until such a variant exists:

The source-selection and routing parameters apply regardless of how the query is supplied:

Constructors

ExplainOptions 

Fields

defaultExplainOptions :: ExplainOptions Source #

ExplainOptions with every field Nothing. Emits an empty query string, preserving the wire behaviour of the legacy parameterless explainDocument.

explainOptionsParams :: ExplainOptions -> [(Text, Maybe Text)] Source #

Render an ExplainOptions record as a (key, value) list suitable for withQueries. Nothing fields are omitted, so defaultExplainOptions produces an empty list (and therefore no query string). The order of the list is stable but unspecified — callers and tests should treat it as a set.

searchByIndicesTemplate :: forall a m. (MonadBH m, FromJSON a) => NonEmpty IndexName -> SearchTemplate -> m (SearchResult a) Source #

searchByIndicesTemplate is a variant of searchByIndexTemplate that executes a SearchTemplate over many indices. This is much faster than using mapM to searchByIndexTemplate over a collection since it only causes a single HTTP request to be emitted.

scanSearch :: (FromJSON a, MonadBH m) => IndexName -> Search -> m [Hit a] Source #

scanSearch uses the scroll API of elastic, for a given IndexName. Note that this will consume the entire search result set and will be doing O(n) list appends so this may not be suitable for large result sets. In that case, getInitialScroll and advanceScroll are good low level tools. You should be able to hook them up trivially to conduit, pipes, or your favorite streaming IO abstraction of choice. Note that ordering on the search would destroy performance and thus is ignored.

getInitialScroll :: forall a m. (MonadBH m, FromJSON a) => IndexName -> Search -> m (ParsedEsResponse (SearchResult a)) Source #

For a given search, request a scroll for efficient streaming of search results. Note that the search is put into SearchTypeScan mode and thus results will not be sorted. Combine this with advanceScroll to efficiently stream through the full result set

getInitialSortedScroll :: forall a m. (MonadBH m, FromJSON a) => IndexName -> Search -> m (SearchResult a) Source #

For a given search, request a scroll for efficient streaming of search results. Combine this with advanceScroll to efficiently stream through the full result set. Note that this search respects sorting and may be less efficient than getInitialScroll.

advanceScroll Source #

Arguments

:: forall a m. (MonadBH m, FromJSON a) 
=> ScrollId 
-> NominalDiffTime

How