Standard library · Database

db.elasticsearch

An Elasticsearch and OpenSearch client: documents, search, aggregations, bulk, SQL and index management.

import db.elasticsearch

Elasticsearch is a search engine and document store spoken to with JSON over HTTP. This package is written in Salam on top of net.http and tls, with no outside library. It works with Elasticsearch 7 and 8, Elastic Cloud (ConnectCloud) and OpenSearch; SQL and point in time calls switch to the OpenSearch endpoints by themselves. A client keeps one connection open per node and can list several nodes: it rotates over them, skips a node that refuses connections for DEAD_NODE_MS, and retries on 502, 503 and 504. Documents and query clauses are plain JSON text, so you can mix the builders here with JSON you write by hand, and Perform reaches every API that has no function of its own. After any call, Error, ErrorType and Status describe what the server said. The examples need a running cluster, so they are only checked.

Tutorial: Search with Elasticsearch

You give Elasticsearch JSON documents, and it finds the ones that match a query, ranks them and counts them in any way you ask. The sections below build a small library catalogue, from the first connection to bulk loading and SQL.

A cluster to talk to

The package speaks to Elasticsearch 7 and 8, to Elastic Cloud and to OpenSearch, over plain HTTP or TLS, with no outside library. For trying things out, one node in Docker is enough:

docker run -d -p 127.0.0.1:9200:9200 -e discovery.type=single-node -e xpack.security.enabled=false docker.elastic.co/elasticsearch/elasticsearch:8.15.3

That node answers on http://localhost:9200 without a password. The examples that need a running cluster are marked as only checked; the ones that build JSON or read answers run here, with their real output.

Connecting

elasticsearch.Connect(url) is the short form. For anything more, fill an elasticsearch.Config and pass it to NewClient: several nodes, a user and password, an API key, a bearer token, the CA file that signed the cluster certificate, a timeout and the number of retries. A node URL may also carry the credentials itself, as in https://user:pass@host:9200.

es-connect.salam
import db.elasticsearch

func main:
    mut cfg := elasticsearch.DefaultConfig()
    cfg.nodes = Vector {} as Vector<str>
    cfg.nodes.Push("https://es-1.example.com:9200")
    cfg.nodes.Push("https://es-2.example.com:9200")
    cfg.username = "elastic"
    cfg.password = "s3cret"
    cfg.ca_file = "/etc/elasticsearch/certs/http_ca.crt"
    cfg.timeout_ms = 10000
    mut c := elasticsearch.NewClient(cfg)
    if not elasticsearch.Ping(c):
        println "no answer:", elasticsearch.Error(c)
        ret
    end
    info := elasticsearch.GetInfo(c)
    println info.distribution, info.version, elasticsearch.ClusterHealth(c).status
    elasticsearch.Close(c)
end

Creating a client does not touch the network. Ping asks whether the cluster answers, GetInfo returns its name, version and distribution, and ClusterHealth its green, yellow or red status. When you are done, Close frees the client and the connections it keeps open.

You haveUse
A local node, no securityConnect("http://localhost:9200")
A user and passwordConnectAuth(url, user, password)
An API keyConnectApiKey(url, key), encoded or as id:key
An Elastic Cloud deploymentConnectCloud(cloud_id, api_key)
A service account tokenConfig with bearer
A self-signed cluster certificateConfig with ca_file

Storing and reading documents

A document is a JSON object stored in an index under an id. Documents and query clauses are plain str values holding JSON, so you can write them by hand, build them with encoding.json or use the builders of this package. CreateIndex sets up an index with its mappings; Index stores a document; Get reads it back; Update merges fields into it and Delete removes it.

es-documents.salam
import db.elasticsearch

func main:
    mut c := elasticsearch.Connect("http://localhost:9200")
    mapping := `{"mappings":{"properties":{"title":{"type":"text"},"author":{"type":"keyword"},"year":{"type":"integer"}}}}`
    if not elasticsearch.IndexExists(c, "books"):
        elasticsearch.CreateIndex(c, "books", mapping)
    end

    w := elasticsearch.IndexWith(
        c,
        "books",
        "1",
        `{"title":"Shahnameh","author":"ferdowsi","year":1010}`,
        elasticsearch.Options { refresh = elasticsearch.REFRESH_WAIT_FOR }
    )
    println w.ok, w.result, w.version

    d := elasticsearch.Get(c, "books", "1")
    if d.found:
        println d.source
    end

    u := elasticsearch.UpdateWith(
        c,
        "books",
        "1",
        `{"year":1011}`,
        elasticsearch.Options { if_seq_no = d.seq_no, if_primary_term = d.primary_term }
    )
    if not u.ok:
        println "someone else changed it first:", elasticsearch.ErrorType(c)
    end

    println elasticsearch.Exists(c, "books", "1"), elasticsearch.Count(c, "books", "")
    elasticsearch.Delete(c, "books", "1")
    elasticsearch.Close(c)
end

Every write returns a WriteResult with ok, the result (created, updated, deleted), the new version and the sequence numbers. Passing if_seq_no and if_primary_term from a Get turns the update into a compare and swap: if someone changed the document in between, the update fails with a version conflict instead of overwriting their change.

A new document is searchable only after the index refreshes, about once a second. Options { refresh = elasticsearch.REFRESH_WAIT_FOR } makes the call wait for that, which is handy in tests and scripts.

Building queries

Each query builder returns one JSON clause: Match for full text, Term and Terms for exact values, Range for numbers and dates, and And, Or, Not and Filtered to combine them. A SearchRequest holds the query with the size, sort order and the fields to return, and SearchBody shows the JSON that will be sent.

es-queries.salam
import db.elasticsearch

func main:
    mut must := Vector {} as Vector<str>
    must.Push(elasticsearch.Match("title", "book of kings"))
    mut filter := Vector {} as Vector<str>
    filter.Push(elasticsearch.Range("year", "900", "1100"))
    filter.Push(elasticsearch.Not(elasticsearch.Term("status", "draft")))
    query := elasticsearch.Filtered(elasticsearch.And(must), filter)
    println query

    mut sort := Vector {} as Vector<str>
    sort.Push(elasticsearch.SortDesc("year"))
    mut shown := Vector {} as Vector<str>
    shown.Push("title")
    shown.Push("year")
    req := elasticsearch.SearchRequest {
        query = query,
        size = 10,
        sort = sort,
        source = shown
    }
    println elasticsearch.SearchBody(req)
end
Output
{"bool": {"must": {"bool": {"must": [{"match": {"title": "book of kings"}}]}}, "filter": [{"range": {"year": {"gte": "900", "lte": "1100"}}}, {"bool": {"must_not": [{"term": {"status": "draft"}}]}}]}}
{"query": {"bool": {"must": {"bool": {"must": [{"match": {"title": "book of kings"}}]}}, "filter": [{"range": {"year": {"gte": "900", "lte": "1100"}}}, {"bool": {"must_not": [{"term": {"status": "draft"}}]}}]}}, "size": 10, "sort": [{"year": {"order": "desc"}}], "_source": ["title", "year"]}

Clauses inside Filtered's filter list only decide whether a document matches; they do not change its score, and Elasticsearch can cache them. Put free text in the query and exact conditions such as dates, statuses and ids in the filter.

Searching and reading the answer

Search(c, index, request) runs the request and parses the answer into a SearchResult: the total number of matches, the hits of this page, each with its id, score, source and highlight, and the time it took.

es-search.salam
import db.elasticsearch

func main:
    mut c := elasticsearch.Connect("http://localhost:9200")
    mut fields := Vector {} as Vector<str>
    fields.Push("title")
    req := elasticsearch.SearchRequest {
        query = elasticsearch.Match("title", "kings"),
        size = 5,
        highlight = elasticsearch.Highlight(fields)
    }
    res := elasticsearch.Search(c, "books", req)
    if not res.ok:
        println "search failed:", elasticsearch.Error(c)
        ret
    end
    println res.total, "matches in", res.took, "ms"
    each hit in res.hits:
        println hit.id, hit.score, hit.source, hit.highlight
    end
    elasticsearch.Close(c)
end

The same parsing is available on its own: ParseSearchResult reads any search answer, for example one you fetched with Perform.

es-results.salam
import db.elasticsearch

func main:
    body := `{"took":3,"hits":{"total":{"value":2,"relation":"eq"},"max_score":1.8,"hits":[{"_id":"1","_score":1.8,"_source":{"title":"Shahnameh","year":1010}},{"_id":"7","_score":0.9,"_source":{"title":"Garshasp-nama","year":1066}}]}}`
    res := elasticsearch.ParseSearchResult(body)
    println res.total, res.total_relation, res.max_score
    each hit in res.hits:
        println hit.id, hit.score, hit.source
    end
end
Output
2 eq 1.8
1 1.8 {"title":"Shahnameh","year":1010}
7 0.9 {"title":"Garshasp-nama","year":1066}

Aggregations

Aggregations summarise the matching documents instead of listing them: how many per author, the average year, the oldest book. Build them with AddAgg(aggs, name, agg), nest one inside a bucket with SubAggs, and read them back with AggValue for a single number and AggBuckets for groups. A bucket's raw JSON goes to AggValueIn to read what is nested inside it.

es-aggs.salam
import db.elasticsearch

func main:
    per_author := elasticsearch.SubAggs(
        elasticsearch.TermsAgg("author", 5),
        elasticsearch.AddAgg("", "avg_year", elasticsearch.AvgAgg("year"))
    )
    mut aggs := elasticsearch.AddAgg("", "by_author", per_author)
    aggs = elasticsearch.AddAgg(aggs, "oldest", elasticsearch.MinAgg("year"))
    println elasticsearch.SearchBody(elasticsearch.SearchRequest { size = 0, aggs = aggs })

    answer := `{"hits":{"total":{"value":120,"relation":"eq"},"hits":[]},"aggregations":{"oldest":{"value":940.0},"by_author":{"buckets":[{"key":"ferdowsi","doc_count":70,"avg_year":{"value":1010.0}},{"key":"saadi","doc_count":50,"avg_year":{"value":1258.0}}]}}}`
    res := elasticsearch.ParseSearchResult(answer)
    println "oldest:", elasticsearch.AggValue(res, "oldest")
    each b in elasticsearch.AggBuckets(res, "by_author"):
        println b.key, b.doc_count, elasticsearch.AggValueIn(b.raw, "avg_year")
    end
end
Output
{"size": 0, "aggs": {"by_author": {"terms": {"field": "author", "size": 5}, "aggs": {"avg_year": {"avg": {"field": "year"}}}}, "oldest": {"min": {"field": "year"}}}}
oldest: 940
ferdowsi 70 1010
saadi 50 1258

Setting size = 0 skips the hits when only the summary matters, which makes the request much cheaper.

Loading many documents

Sending documents one by one costs a round trip each. A Bulk collects index, create, update and delete actions and sends them in one request. The answer says per item whether it worked, so a partial failure is never silent.

es-bulk.salam
import str
import db.elasticsearch

func main:
    mut b := elasticsearch.NewBulk()
    repeat 3 in i:
        id := str.FromInt(i as i64)
        elasticsearch.BulkIndex(b, "logs", id, `{"line":` + id + `,"level":"info"}`)
    end
    elasticsearch.BulkUpdate(b, "logs", "1", `{"level":"warn"}`)
    elasticsearch.BulkDelete(b, "logs", "2")
    println elasticsearch.BulkLen(b), "actions"
    print elasticsearch.BulkBody(b)

    answer := `{"took":5,"errors":true,"items":[{"index":{"_id":"0","status":201,"result":"created"}},{"index":{"_id":"1","status":201,"result":"created"}},{"index":{"_id":"2","status":201,"result":"created"}},{"update":{"_id":"1","status":200,"result":"updated"}},{"delete":{"_id":"2","status":429,"error":{"type":"es_rejected_execution_exception","reason":"queue is full"}}}]}`
    res := elasticsearch.ParseBulkResult(answer)
    println res.succeeded, "ok,", res.failed, "failed"
    each it in res.items:
        if not it.ok:
            println "retry", it.action, it.id, it.error_type
        end
    end
end
Output
5 actions
{"index": {"_index": "logs", "_id": "0"}}
{"line":0,"level":"info"}
{"index": {"_index": "logs", "_id": "1"}}
{"line":1,"level":"info"}
{"index": {"_index": "logs", "_id": "2"}}
{"line":2,"level":"info"}
{"update": {"_index": "logs", "_id": "1"}}
{"doc": {"level":"warn"}}
{"delete": {"_index": "logs", "_id": "2"}}
4 ok, 1 failed
retry delete 2 es_rejected_execution_exception

For large loads, send a batch every thousand or so actions and start over with BulkReset. The client keeps the connection to each node open between calls, so over HTTPS the TLS handshake is paid once, not once per request.

es-bulk-run.salam
import str
import db.elasticsearch

func main:
    mut c := elasticsearch.Connect("http://localhost:9200")
    mut b := elasticsearch.NewBulk()
    repeat 10000 in i:
        id := str.FromInt(i as i64)
        elasticsearch.BulkIndex(b, "logs", id, `{"line":` + id + `}`)
        if elasticsearch.BulkLen(b) == 1000:
            res := elasticsearch.RunBulk(c, b)
            println res.succeeded, res.failed
            elasticsearch.BulkReset(b)
        end
    end
    if elasticsearch.BulkLen(b) > 0:
        res := elasticsearch.RunBulk(c, b)
        println res.succeeded, res.failed
    end
    elasticsearch.Refresh(c, "logs")
    println elasticsearch.Count(c, "logs", "")
    elasticsearch.Close(c)
end

Paging through everything

from and size are fine for the first few pages of a result list. To walk through every match, open a point in time with OpenPit, sort by the fields you need, and pass the whole sort array of the last hit as search_after to get the next page. A point-in-time search adds a unique _shard_doc value to the end of every hit's sort, so no two hits tie and you do not need to sort by _id. The point in time keeps the view stable while you read. SearchScroll and Scroll do the same in the older style.

es-paging.salam
import db.elasticsearch

func main:
    mut c := elasticsearch.Connect("http://localhost:9200")
    mut sort := Vector {} as Vector<str>
    sort.Push(elasticsearch.SortAsc("year"))

    pit := elasticsearch.OpenPit(c, "books", "1m")
    mut after := ""
    mut more := true
    until more:
        page := elasticsearch.Search(c, "", elasticsearch.SearchRequest {
            size = 500,
            sort = sort,
            pit_id = pit,
            pit_keep_alive = "1m",
            search_after = after
        })
        if page.hits.Len() == 0:
            more = false
        else:
            each hit in page.hits:
                println hit.id
            end
            after = page.hits.Get(page.hits.Len() - 1).sort
        end
    end
    elasticsearch.ClosePit(c, pit)
    elasticsearch.Close(c)
end

SQL

Elasticsearch, and the SQL plugin of OpenSearch, also answer SQL. Sql and SqlWith return rows that implement db.Rows and fetch further pages by themselves as you call Next. Conn(c) wraps the client as a db.Connection, so a function written for SQLite or PostgreSQL can read from Elasticsearch too. That connection is read only: writes go through Index, Bulk and DeleteByQuery.

es-sql.salam
import db
import db.elasticsearch

func authors(conn: dyn db.Connection):
    rows := conn.Query(
        "SELECT author, COUNT(*) AS books FROM books GROUP BY author ORDER BY author"
    )
    until rows.Next():
        println rows.Text(0), rows.Int(1)
    end
    rows.Close()
end

func main:
    mut c := elasticsearch.Connect("http://localhost:9200")
    mut params := Vector {} as Vector<str>
    params.Push("1000")
    mut rows := elasticsearch.SqlWith(
        c, "SELECT title, year FROM books WHERE year > ? ORDER BY year", params, 100
    )
    until rows.Next():
        println rows.Text(0), rows.Int(1)
    end
    rows.Close()
    authors(elasticsearch.Conn(c))
    elasticsearch.Close(c)
end

Errors and retries

A call that fails returns its sentinel (false, -1, an empty string or a result with ok false), and the client remembers why: Error(c) gives the message, ErrorType(c) the Elasticsearch error type such as version_conflict_engine_exception, and Status(c) the HTTP status, 0 when no node answered. With several nodes the client rotates over them, skips a node that refused a connection for a minute, and retries on 502, 503 and 504.

es-errors.salam
import db.elasticsearch

func main:
    mut cfg := elasticsearch.Config { max_retries = 3, timeout_ms = 5000, keep_alive = true }
    cfg.nodes.Push("http://es-1:9200")
    cfg.nodes.Push("http://es-2:9200")
    mut c := elasticsearch.NewClient(cfg)
    w := elasticsearch.Create(c, "books", "1", `{"title":"Shahnameh"}`)
    if not w.ok:
        switch elasticsearch.ErrorType(c):
            "version_conflict_engine_exception":
                println "already there"
                break
            end
            "":
                println "no node answered:", elasticsearch.Error(c)
                break
            end
            else:
                println elasticsearch.Status(c), elasticsearch.Error(c)
            end
        end
    end
    r := elasticsearch.Perform(c, "GET", "/_cat/indices?format=json", "")
    println r.status, r.body
    elasticsearch.Close(c)
end

Anything the package has no function for is one Perform(c, method, path, body) away; it returns the status and the raw body.

Where to go next

NeedReach for
Index settings, mappings, aliases and templatesPutMapping, PutSettings, SwapAlias, PutIndexTemplate
Copying an indexReindex, or StartReindex and GetTask in the background
Cleaning documents on the way inPutPipeline and Options { pipeline = ... }
Logs and other time seriesCreateDataStream, Rollover, PutLifecyclePolicy
BackupsPutRepository, CreateSnapshot, RestoreSnapshot
Long searchesSubmitAsyncSearch and GetAsyncSearch
Vector searchKnn in SearchRequest.knn

Every function, type and field is described, with examples, in the reference below.

Types

SqlRows

#
struct SqlRows

SQL query results; implements db.Rows and fetches further pages with the cursor as you call Next.

NameTypeDescription
handlevoid*The internal state pointer.
db-elasticsearch-Sql.salam
import db
import db.elasticsearch

func report(conn: dyn db.Connection):
    rows := conn.Query("SELECT level, COUNT(*) AS n FROM logs GROUP BY level")
    until rows.Next():
        println rows.Text(0), rows.Int(1)
    end
    rows.Close()
end

func main:
    c := elasticsearch.Connect("http://localhost:9200")
    mut params := Vector {} as Vector<str>
    params.Push("100")
    mut rows := elasticsearch.SqlWith(
        c, "SELECT line, level FROM logs WHERE line < ? ORDER BY line", params, 50
    )
    println rows.ColumnCount(),
        rows.ColumnName(0),
        rows.ColumnTypeName(0),
        rows.ColumnType(0) == db.TYPE_INT
    until rows.Next():
        println rows.Int64(0), rows.Text(1), rows.IsNull(1)
    end
    rows.Close()
    plain := elasticsearch.Sql(c, "SELECT COUNT(*) FROM logs")
    println plain.Next()
    plain.Close()
    print elasticsearch.SqlText(c, "SELECT level FROM logs LIMIT 3")
    println elasticsearch.SqlTranslate(c, "SELECT line FROM logs WHERE level = 'warn'")
    report(elasticsearch.Conn(c))
end

Error

#
func Error(): str

The error of the query, empty on success.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Next

#
func Next(): bool

Moves to the next row, fetching the next page when needed.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

ColumnCount

#
func ColumnCount(): int

The number of columns.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

ColumnName

#
func ColumnName(col: int): str

The name of a column.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

ColumnTypeName

#
func ColumnTypeName(col: int): str

The Elasticsearch type of a column, such as long or keyword.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

ColumnType

#
func ColumnType(col: int): int

The db.TYPE_* kind of a column, TYPE_NULL for a null cell.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

IsNull

#
func IsNull(col: int): bool

Whether a cell of the current row is null.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Text

#
func Text(col: int): str

A cell as text; empty for null.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Close

#
func Close(): int

Frees the rows and closes an open cursor.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Database

#
struct Database

A client seen through db.Connection, so code written for the db interfaces can read Elasticsearch with SQL.

NameTypeDescription
handlevoid*The internal state pointer.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Exec

#
func Exec(_sql: str): int

Always -1: Elasticsearch SQL is read only. Write with Index, Bulk or DeleteByQuery.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Query

#
func Query(sql: str): dyn db.Rows

Runs a SQL query.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Begin

#
func Begin(): dyn db.Tx

Returns a transaction whose calls all fail; Elasticsearch has no transactions.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Quote

#
func Quote(s: str): str

Quotes a string literal for SQL.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Txn

#
struct Txn

The transaction Database.Begin returns. Elasticsearch has no transactions, so every call fails.

NameTypeDescription
handlevoid*The internal state pointer.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Query

#
func Query(_sql: str): dyn db.Rows

Returns empty rows.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Config

#
struct Config

Everything a client needs: nodes, credentials, TLS, timeout, retries and extra headers.

NameTypeDescription
nodesVector<str>Node URLs; each may list several separated by commas.
cloud_idstr = ""An Elastic Cloud id, used before nodes.
usernamestr = ""The user for basic authentication.
passwordstr = ""The password for basic authentication.
api_keystr = ""An API key, encoded or id:key; wins over basic authentication.
bearerstr = ""A bearer token, such as a service account token.
ca_filestr = ""A PEM file of the CA that signed the cluster certificate, for example http_ca.crt.
insecurebool = falseSkip TLS certificate checks. Only for local testing.
timeout_msint = 30000The connect and read timeout of one request in milliseconds; 0 waits forever.
max_retriesint = 3How many more nodes to try after a connection failure or a 502, 503 or 504.
keep_alivebool = trueReuse one connection per node across requests (the default). Over HTTPS this skips a TLS handshake per call; a connection the server closed is reopened on its own.
headersHashMap<str, str>Extra headers sent with every request.
db-elasticsearch-Client.salam
import db.elasticsearch

func main:
    mut cfg := elasticsearch.DefaultConfig()
    cfg.username = "elastic"
    cfg.password = "s3cret"
    cfg.ca_file = "/etc/elasticsearch/certs/http_ca.crt"
    cfg.timeout_ms = 10000
    cfg.headers.Put("X-Opaque-Id", "salam-docs")
    mut c := elasticsearch.NewClient(cfg)
    if not elasticsearch.Ping(c):
        println "cannot reach elasticsearch:", elasticsearch.Error(c)
        ret
    end
    info := elasticsearch.GetInfo(c)
    println info.distribution, info.version, elasticsearch.ClusterHealth(c).status

    mapping := `{"mappings":{"properties":{"title":{"type":"text"},"year":{"type":"integer"}}}}`
    if not elasticsearch.IndexExists(c, "books"):
        elasticsearch.CreateIndex(c, "books", mapping)
    end
    w := elasticsearch.IndexWith(
        c,
        "books",
        "1",
        `{"title":"Shahnameh","year":1010}`,
        elasticsearch.Options { refresh = elasticsearch.REFRESH_WAIT_FOR }
    )
    println w.result, w.version

    d := elasticsearch.Get(c, "books", "1")
    if d.found: println d.source end
    u := elasticsearch.UpdateWith(
        c,
        "books",
        "1",
        `{"year":1011}`,
        elasticsearch.Options { if_seq_no = d.seq_no, if_primary_term = d.primary_term }
    )
    if not u.ok: println "conflict:", elasticsearch.ErrorType(c) end
    elasticsearch.UpdateScript(c, "books", "1", "ctx._source.year += params.n", `{"n": 1}`)
    println elasticsearch.Exists(c, "books", "1"), elasticsearch.Count(c, "books", "")

    r := elasticsearch.Perform(c, "GET", "/_cat/health?format=json", "")
    println r.status, r.body
    elasticsearch.Delete(c, "books", "1")
    elasticsearch.Close(c)
end

Client

#
struct Client

A client handle. It is cheap to pass by value; free it with Close.

NameTypeDescription
handlevoid*The internal state pointer.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Response

#
struct Response

The raw answer of Perform: status, body and the parsed error envelope.

NameTypeDescription
statusint = 0The HTTP status, or the status reported for this item.
okbool = falseWhether it succeeded.
bodystr = ""The response body.
errorstr = ""The error text, empty on success.
error_typestr = ""The Elasticsearch error.type.
error_reasonstr = ""The Elasticsearch error.reason.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Options

#
struct Options

Optional request parameters shared by the write calls: refresh, routing, pipeline, optimistic concurrency and more.

NameTypeDescription
refreshstr = ""true, wait_for or false; see the REFRESH_* constants.
routingstr = ""A custom routing value.
pipelinestr = ""An ingest pipeline to run first.
timeoutstr = ""A server side timeout such as 30s.
wait_for_active_shardsstr = ""How many shard copies must be active, or all.
sourcestr = ""Source filtering: for Options a comma list of fields, for SearchRequest the fields to return; on results the raw _source JSON.
conflictsstr = ""proceed to skip version conflicts in by query operations.
if_seq_noi64 = -1Only write when the document still has this sequence number; -1 turns it off.
if_primary_termi64 = -1The primary term that goes with if_seq_no.
retry_on_conflictint = -1How many times an update retries on a version conflict; -1 leaves the default.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

WriteResult

#
struct WriteResult

The outcome of indexing, creating, updating or deleting one document.

NameTypeDescription
okbool = falseWhether it succeeded.
statusint = 0The HTTP status, or the status reported for this item.
indexstr = ""The index name.
idstr = ""The document id.
resultstr = ""created, updated, deleted, noop or not_found.
versioni64 = 0The document version, or the cluster version for Info.
seq_noi64 = -1The sequence number, for optimistic concurrency; -1 when unknown.
primary_termi64 = 0The primary term, for optimistic concurrency.
errorstr = ""The error text, empty on success.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Document

#
struct Document

One fetched document with its metadata and raw _source.

NameTypeDescription
foundbool = falseWhether the document exists.
indexstr = ""The index name.
idstr = ""The document id.
versioni64 = 0The document version, or the cluster version for Info.
seq_noi64 = -1The sequence number, for optimistic concurrency; -1 when unknown.
primary_termi64 = 0The primary term, for optimistic concurrency.
sourcestr = ""Source filtering: for Options a comma list of fields, for SearchRequest the fields to return; on results the raw _source JSON.
fieldsstr = ""Stored or runtime fields: raw JSON on results, a field list on SearchRequest.
errorstr = ""The error text, empty on success.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Hit

#
struct Hit

One search hit.

NameTypeDescription
indexstr = ""The index name.
idstr = ""The document id.
scoref64 = 0The relevance score.
sourcestr = ""Source filtering: for Options a comma list of fields, for SearchRequest the fields to return; on results the raw _source JSON.
sortstr = ""Sort clauses on a request; on a hit the raw sort values, to pass to search_after.
highlightstr = ""Highlighting: the section on a request, the raw fragments on a hit.
fieldsstr = ""Stored or runtime fields: raw JSON on results, a field list on SearchRequest.
rawstr = ""The raw JSON it was parsed from.
db-elasticsearch-Search.salam
import db.elasticsearch

func main:
    c := elasticsearch.Connect("http://localhost:9200")
    mut must := Vector {} as Vector<str>
    must.Push(elasticsearch.Match("title", "persian poetry"))
    mut filters := Vector {} as Vector<str>
    filters.Push(elasticsearch.Range("year", "900", "1500"))
    filters.Push(elasticsearch.Not(elasticsearch.Term("status", "draft")))
    mut aggs := elasticsearch.AddAgg(
        "",
        "by_author",
        elasticsearch.SubAggs(
            elasticsearch.TermsAgg("author", 5),
            elasticsearch.AddAgg("", "avg_year", elasticsearch.AvgAgg("year"))
        )
    )
    aggs = elasticsearch.AddAgg(aggs, "newest", elasticsearch.MaxAgg("year"))
    mut sort := Vector {} as Vector<str>
    sort.Push(elasticsearch.SortDesc("year"))
    mut fields := Vector {} as Vector<str>
    fields.Push("title")
    req := elasticsearch.SearchRequest {
        query = elasticsearch.Filtered(elasticsearch.And(must), filters),
        size = 10,
        sort = sort.Copy(),
        aggs = aggs,
        highlight = elasticsearch.Highlight(fields)
    }
    res := elasticsearch.Search(c, "books", req)
    if not res.ok:
        println elasticsearch.Error(c)
        ret
    end
    println res.total, res.total_relation, res.took
    each h in res.hits:
        println h.id, h.score, h.source, h.highlight
    end
    println elasticsearch.AggValue(res, "newest")
    each b in elasticsearch.AggBuckets(res, "by_author"):
        println b.key, b.doc_count, elasticsearch.AggValueIn(b.raw, "avg_year")
    end

    mut page := elasticsearch.SearchScroll(
        c,
        "books",
        elasticsearch.SearchRequest { query = elasticsearch.MatchAll(), size = 500 },
        "1m"
    )
    until page.hits.Len() > 0:
        println "page of", page.hits.Len()
        page = elasticsearch.Scroll(c, page.scroll_id, "1m")
    end
    elasticsearch.ClearScroll(c, page.scroll_id)

    pit := elasticsearch.OpenPit(c, "books", "1m")
    first := elasticsearch.Search(
        c, "", elasticsearch.SearchRequest { pit_id = pit, size = 100, sort = sort }
    )
    if first.hits.Len() > 0:
        last := first.hits.Get(first.hits.Len() - 1)
        next := elasticsearch.Search(c, "", elasticsearch.SearchRequest {
            pit_id = pit,
            size = 100,
            sort = sort,
            search_after = last.sort
        })
        println next.hits.Len()
    end
    elasticsearch.ClosePit(c, pit)
    println elasticsearch.DeleteByQuery(c, "books", elasticsearch.Term("status", "draft"))
end

SearchResult

#
struct SearchResult

A parsed search response: totals, hits, aggregations and paging ids.

NameTypeDescription
okbool = falseWhether it succeeded.
statusint = 0The HTTP status, or the status reported for this item.
tooki64 = 0Milliseconds the server spent.
timed_outbool = falseWhether the server timed out.
totali64 = 0The number of matching documents.
total_relationstr = ""eq when total is exact, gte when it is a lower bound.
max_scoref64 = 0The best score.
hitsVector<Hit>The hits of this page.
aggregationsstr = ""The raw aggregations JSON.
suggeststr = ""Suggesters: the section on a request, the raw result on a response.
scroll_idstr = ""The id for the next Scroll.
pit_idstr = ""A point in time id: on a request to search it, on a result the refreshed id.
rawstr = ""The raw JSON it was parsed from.
errorstr = ""The error text, empty on success.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

SearchRequest

#
struct SearchRequest

A search request; SearchBody turns it into JSON. Empty fields are left out.

NameTypeDescription
querystr = ""The query clause JSON; empty matches everything.
fromint = -1The offset of the first hit; -1 leaves it out.
sizeint = -1How many hits to return; -1 leaves it out.
sortVector<str>Sort clauses on a request; on a hit the raw sort values, to pass to search_after.
sourceVector<str>Source filtering: for Options a comma list of fields, for SearchRequest the fields to return; on results the raw _source JSON.
source_excludesVector<str>Fields to leave out of _source.
no_sourcebool = falseReturn no _source at all.
fieldsVector<str>Stored or runtime fields: raw JSON on results, a field list on SearchRequest.
aggsstr = ""The aggregations object, built with AddAgg.
highlightstr = ""Highlighting: the section on a request, the raw fragments on a hit.
post_filterstr = ""A filter applied after aggregations.
knnstr = ""A Knn clause for vector search.
collapsestr = ""A field to collapse hits on, one hit per value.
suggeststr = ""Suggesters: the section on a request, the raw result on a response.
search_afterstr = ""The raw sort values of the last hit of the previous page.
pit_idstr = ""A point in time id: on a request to search it, on a result the refreshed id.
pit_keep_alivestr = ""How long to keep the point in time alive, such as 1m.
track_total_hitsstr = ""true for an exact total, or a number as the counting limit.
min_scorestr = ""Leave out hits scoring below this.
timeoutstr = ""A server side timeout such as 30s.
extraVector<str>Raw members added to the body, such as "explain": true.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

Bucket

#
struct Bucket

One bucket of a bucket aggregation.

NameTypeDescription
keystr = ""The bucket key, or key_as_string when there is one.
doc_counti64 = 0How many documents fell into the bucket.
rawstr = ""The raw bucket JSON, for sub aggregations with AggValueIn.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

Bulk

#
struct Bulk

A bulk request being built; add actions with the Bulk* functions.

NameTypeDescription
linesVector<str>The NDJSON lines so far.
countint = 0How many actions were added.
db-elasticsearch-Bulk.salam
import str
import db.elasticsearch

func main:
    c := elasticsearch.Connect("http://localhost:9200")
    mut b := elasticsearch.NewBulk()
    repeat 1000 in i:
        id := str.FromInt(i as i64)
        elasticsearch.BulkIndex(b, "logs", id, `{"line":` + id + `,"level":"info"}`)
    end
    elasticsearch.BulkCreate(b, "logs", "fresh", `{"line":-2}`)
    elasticsearch.BulkUpdate(b, "logs", "7", `{"level":"warn"}`)
    elasticsearch.BulkUpsert(b, "logs", "new", `{"line":-1}`)
    elasticsearch.BulkDelete(b, "logs", "8")
    println elasticsearch.BulkLen(b)
    println elasticsearch.BulkBody(b).Len() > 0
    first := elasticsearch.RunBulk(c, b)
    println first.ok
    parsed := elasticsearch.ParseBulkResult(`{"took":1,"errors":false,"items":[]}`)
    println parsed.ok
    res := elasticsearch.RunBulkWith(
        c, "", b, elasticsearch.Options { refresh = elasticsearch.REFRESH_TRUE }
    )
    println res.ok, res.succeeded, res.failed, res.took
    if res.errors:
        each it in res.items:
            if not it.ok: println it.action, it.id, it.status, it.error_type, it.error_reason end
        end
    end
    elasticsearch.BulkReset(b)
end

BulkItem

#
struct BulkItem

The result of one action in a bulk request.

NameTypeDescription
actionstr = ""index, create, update or delete.
indexstr = ""The index name.
idstr = ""The document id.
statusint = 0The HTTP status, or the status reported for this item.
okbool = falseWhether it succeeded.
resultstr = ""created, updated, deleted, noop or not_found.
versioni64 = 0The document version, or the cluster version for Info.
error_typestr = ""The Elasticsearch error.type.
error_reasonstr = ""The Elasticsearch error.reason.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkResult

#
struct BulkResult

The result of a bulk request, with one item per action.

NameTypeDescription
okbool = falseWhether it succeeded.
statusint = 0The HTTP status, or the status reported for this item.
tooki64 = 0Milliseconds the server spent.
errorsbool = falseWhether any action failed.
succeededint = 0How many actions succeeded.
failedint = 0How many actions failed.
itemsVector<BulkItem>One result per action, in order.
errorstr = ""The error text, empty on success.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

Info

#
struct Info

What the root endpoint says about the cluster.

NameTypeDescription
okbool = falseWhether it succeeded.
namestr = ""The name of the node that answered.
cluster_namestr = ""The cluster name.
cluster_uuidstr = ""The cluster uuid.
versionstr = ""The server version number.
distributionstr = ""elasticsearch or opensearch.
build_flavorstr = ""The build flavor, such as default.
lucene_versionstr = ""The Lucene version.
taglinestr = ""The tagline the server sends.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Health

#
struct Health

Cluster health.

NameTypeDescription
okbool = falseWhether it succeeded.
cluster_namestr = ""The cluster name.
statusstr = ""green, yellow or red.
timed_outbool = falseWhether the server timed out.
nodesint = 0The number of nodes.
data_nodesint = 0The number of data nodes.
active_primary_shardsint = 0Active primary shards.
active_shardsint = 0Active shards.
relocating_shardsint = 0Shards being moved.
initializing_shardsint = 0Shards being initialized.
unassigned_shardsint = 0Shards with no node.
pending_tasksint = 0Cluster tasks waiting.
active_shards_percentf64 = 0The percent of shards that are active.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

IndexInfo

#
struct IndexInfo

One row of CatIndices.

NameTypeDescription
healthstr = ""green, yellow or red.
statusstr = ""open or close.
indexstr = ""The index name.
uuidstr = ""The index uuid.
primariesint = 0The number of primary shards.
replicasint = 0The number of replicas.
docs_counti64 = 0The number of documents.
docs_deletedi64 = 0Deleted documents not yet merged away.
store_sizestr = ""The size on disk in bytes.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

AsyncSearch

#
struct AsyncSearch

An async search: its id, whether it still runs, and the result so far.

NameTypeDescription
okbool = falseWhether it succeeded.
idstr = ""The id to fetch or delete the search with.
runningbool = falseWhether the search is still running.
partialbool = falseWhether the result is partial.
resultSearchResultThe search result so far.
errorstr = ""The error text, empty on success.
db-elasticsearch-Admin.salam
import time
import encoding.json
import db.elasticsearch

func main:
    c := elasticsearch.Connect("http://localhost:9200")

    elasticsearch.PutPipeline(
        c,
        "clean",
        `{"processors":[{"lowercase":{"field":"tag"}},{"set":{"field":"seen","value":true}}]}`
    )
    test := elasticsearch.SimulatePipeline(c, "clean", `{"docs":[{"_source":{"tag":"LOUD"}}]}`)
    println json.GetPath(test, "docs.0.doc._source.tag")
    elasticsearch.IndexWith(
        c, "books", "9", `{"tag":"Poetry"}`, elasticsearch.Options { pipeline = "clean" }
    )

    elasticsearch.PutIndexTemplate(
        c, "app_logs", `{"index_patterns":["applog-*"],"data_stream":{},"priority":200}`
    )
    elasticsearch.CreateDataStream(c, "applog-web")
    elasticsearch.Create(
        c, "applog-web", "", `{"@timestamp":"2026-10-16T10:00:00Z","msg":"started"}`
    )
    elasticsearch.Rollover(c, "applog-web", "")
    println elasticsearch.GetDataStream(c, "applog-web")

    policy := `{"policy":{"phases":{"delete":{"min_age":"30d","actions":{"delete":{}}}}}}`
    if not elasticsearch.IsOpenSearch(c): elasticsearch.PutLifecyclePolicy(c, "month", policy) end

    elasticsearch.PutRepository(
        c, "backups", `{"type":"fs","settings":{"location":"/mnt/backups"}}`
    )
    elasticsearch.CreateSnapshot(c, "backups", "nightly", `{"indices":"books"}`)
    println elasticsearch.ListSnapshots(c, "backups")

    id := elasticsearch.StartUpdateByQuery(
        c, "books", elasticsearch.MatchAll(), elasticsearch.Script("ctx._source.year += 1", "")
    )
    mut task := elasticsearch.GetTask(c, id)
    until task.ok and not task.completed:
        time.Sleep(200)
        task = elasticsearch.GetTask(c, id)
    end
    println json.Get(task.response, "updated")

    elasticsearch.PutStoredScript(c, "by_tag", "mustache", `{"query":{"term":{"tag":"{{tag}}"}}}`)
    hits := elasticsearch.SearchTemplate(c, "books", "by_tag", `{"tag":"poetry"}`)
    println hits.total

    mut a := elasticsearch.SubmitAsyncSearch(
        c, "books", elasticsearch.SearchRequest { query = elasticsearch.MatchAll() }, "1s"
    )
    until a.running:
        a = elasticsearch.GetAsyncSearch(c, a.id, "1s")
    end
    println a.result.total
    elasticsearch.DeleteAsyncSearch(c, a.id)

    println elasticsearch.ValidateQuery(c, "books", elasticsearch.Match("title", "shahnameh"))
    println elasticsearch.Explain(c, "books", "9", elasticsearch.Term("tag", "poetry"))
    println elasticsearch.GetClusterSettings(c)
    println elasticsearch.GetPipeline(c, "clean")
    println elasticsearch.GetLifecyclePolicy(c, "month")
    println elasticsearch.IndexStats(c, "books")
    mut tvf := Vector {} as Vector<str>
    tvf.Push("title")
    println elasticsearch.FieldCaps(c, "books", tvf)
    println elasticsearch.TermVectors(c, "books", "9", tvf)

    reindex := elasticsearch.StartReindex(
        c, `{"source":{"index":"books"},"dest":{"index":"books_v2"}}`
    )
    println elasticsearch.CancelTask(c, reindex)
    drop := elasticsearch.StartDeleteByQuery(c, "books", elasticsearch.Term("status", "draft"))
    println drop
    elasticsearch.RestoreSnapshot(c, "backups", "nightly", `{"indices":"books"}`)
    elasticsearch.DeleteSnapshot(c, "backups", "nightly")
    elasticsearch.DeleteRepository(c, "backups")
    elasticsearch.DeleteStoredScript(c, "by_tag")
    elasticsearch.DeletePipeline(c, "clean")
    elasticsearch.DeleteLifecyclePolicy(c, "month")
    elasticsearch.DeleteDataStream(c, "applog-web")
    println elasticsearch.PutClusterSettings(
        c, `{"persistent":{"indices.recovery.max_bytes_per_sec":"100mb"}}`
    )
end

Task

#
struct Task

A server task started with one of the Start* calls.

NameTypeDescription
okbool = falseWhether it succeeded.
idstr = ""The task id, node:number.
completedbool = falseWhether the task has finished.
actionstr = ""The task action, such as indices:data/write/update/byquery.
responsestr = ""The raw response of a finished task, such as counts of updated documents.
rawstr = ""The raw JSON it was parsed from.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

Constants and variables

DEFAULT_URL

#
const DEFAULT_URL: str = "http://localhost:9200"

The node used when a config lists none: http://localhost:9200.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

DEFAULT_PORT

#
const DEFAULT_PORT: i32 = 9200

The port used when a node URL has none: 9200.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

DEAD_NODE_MS

#
const DEAD_NODE_MS: i32 = 60000

How long, in milliseconds, a node that refused a connection is skipped before it is tried again.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

REFRESH_TRUE

#
const REFRESH_TRUE: str = "true"

refresh value: make the change searchable right away.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

REFRESH_WAIT_FOR

#
const REFRESH_WAIT_FOR: str = "wait_for"

refresh value: wait until the next refresh makes the change searchable.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

REFRESH_FALSE

#
const REFRESH_FALSE: str = "false"

refresh value: return without waiting for a refresh (the default).

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Functions

Sql

#
func Sql(c: Client, query: str): SqlRows

Runs a SQL query through Elasticsearch SQL, or the OpenSearch SQL plugin.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

SqlWith

#
func SqlWith(c: Client, query: str, params: Vector<str>, fetch_size: int): SqlRows

Runs SQL with ? parameters given as raw JSON values, and a page size.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

SqlText

#
func SqlText(c: Client, query: str): str

The result of a SQL query as a text table (CSV on OpenSearch).

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

SqlTranslate

#
func SqlTranslate(c: Client, query: str): str

The query DSL a SQL query turns into (the explain plan on OpenSearch).

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Conn

#
func Conn(c: Client): dyn db.Connection

The client as a db.Connection. Closing it closes the client.

The example for this item is shown with the ones above: db-elasticsearch-Sql.salam

Index

#
func Index(c: Client, index: str, id: str, doc: str): WriteResult

Stores a document. With an empty id Elasticsearch picks one, returned in id.

db-elasticsearch-Documents.salam
import db.elasticsearch

func main:
    c := elasticsearch.Connect("http://localhost:9200")
    opts := elasticsearch.Options { refresh = elasticsearch.REFRESH_TRUE }

    println elasticsearch.Index(c, "books", "1", `{"title":"Shahnameh","year":1010}`).result
    println elasticsearch.CreateWith(
        c, "books", "2", `{"title":"Masnavi","year":1258}`, opts
    ).result
    println elasticsearch.Upsert(c, "books", "3", `{"title":"Divan","year":1368}`).result
    println elasticsearch.Update(c, "books", "3", `{"year":1369}`).result

    println elasticsearch.GetSource(c, "books", "1")
    d := elasticsearch.GetWith(c, "books", "2", elasticsearch.Options { routing = "poetry" })
    println d.found, d.id
    mut ids := Vector {} as Vector<str>
    ids.Push("1")
    ids.Push("2")
    ids.Push("3")
    each doc in elasticsearch.MGet(c, "books", ids):
        println doc.id, doc.found
    end

    updated := elasticsearch.UpdateByQuery(
        c,
        "books",
        elasticsearch.Term("year", "1010"),
        elasticsearch.Script("ctx._source.year += 1", "")
    )
    println updated
    also := elasticsearch.UpdateByQueryWith(
        c,
        "books",
        elasticsearch.MatchAll(),
        elasticsearch.Script("ctx._source.seen = true", ""),
        opts
    )
    println also

    println elasticsearch.Reindex(c, "books", "books_v2")

    println elasticsearch.DeleteWith(c, "books", "1", opts).result
    println elasticsearch.DeleteByQueryWith(c, "books", elasticsearch.Term("year", "1369"), opts)
end

IndexWith

#
func IndexWith(c: Client, index: str, id: str, doc: str, opts: Options): WriteResult

Index with options.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Create

#
func Create(c: Client, index: str, id: str, doc: str): WriteResult

Stores a document only if its id is new; a duplicate fails with status 409.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

CreateWith

#
func CreateWith(c: Client, index: str, id: str, doc: str, opts: Options): WriteResult

Create with options.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

Get

#
func Get(c: Client, index: str, id: str): Document

Fetches a document by id. A missing document has found false and no error.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

GetWith

#
func GetWith(c: Client, index: str, id: str, opts: Options): Document

Get with options; source filters the returned fields.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

GetSource

#
func GetSource(c: Client, index: str, id: str): str

Only the _source of a document, empty when it is missing.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

Exists

#
func Exists(c: Client, index: str, id: str): bool

Whether a document exists.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Update

#
func Update(c: Client, index: str, id: str, partial: str): WriteResult

Merges a partial document into an existing one.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

UpdateWith

#
func UpdateWith(c: Client, index: str, id: str, partial: str, opts: Options): WriteResult

Update with options, including if_seq_no and if_primary_term for optimistic concurrency.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Upsert

#
func Upsert(c: Client, index: str, id: str, doc: str): WriteResult

Updates a document, or creates it when it does not exist.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

Script

#
func Script(source: str, params: str): str

A painless script object with optional raw JSON params.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

UpdateScript

#
func UpdateScript(c: Client, index: str, id: str, source: str, params: str): WriteResult

Updates a document with a painless script.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Delete

#
func Delete(c: Client, index: str, id: str): WriteResult

Deletes a document by id.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

DeleteWith

#
func DeleteWith(c: Client, index: str, id: str, opts: Options): WriteResult

Delete with options.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

MGet

#
func MGet(c: Client, index: str, ids: Vector<str>): Vector<Document>

Fetches several documents in one request, in the order of the ids.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

Count

#
func Count(c: Client, index: str, query: str): i64

The number of documents matching a query (all when it is empty); -1 on error.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

CreateIndex

#
func CreateIndex(c: Client, index: str, body: str): bool

Creates an index with an optional settings and mappings body.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

DeleteIndex

#
func DeleteIndex(c: Client, index: str): bool

Deletes an index.

db-elasticsearch-Indices.salam
import db.elasticsearch

func main:
    c := elasticsearch.Connect("http://localhost:9200")

    elasticsearch.CreateIndex(c, "books_v1", `{"settings":{"number_of_shards":1}}`)
    println elasticsearch.GetIndex(c, "books_v1")
    println elasticsearch.GetMapping(c, "books_v1")
    elasticsearch.PutMapping(c, "books_v1", `{"properties":{"author":{"type":"keyword"}}}`)
    println elasticsearch.GetSettings(c, "books_v1")
    elasticsearch.PutSettings(c, "books_v1", `{"index":{"refresh_interval":"5s"}}`)

    each info in elasticsearch.CatIndices(c, "books*"):
        println info.index, info.docs_count, info.health
    end

    elasticsearch.PutAlias(c, "books_v1", "books")
    println elasticsearch.AliasExists(c, "books"), elasticsearch.GetAlias(c, "books")
    elasticsearch.CreateIndex(c, "books_v2", "")
    elasticsearch.SwapAlias(c, "books", "books_v1", "books_v2")
    elasticsearch.UpdateAliases(c, `{"actions":[{"add":{"index":"books_v2","alias":"latest"}}]}`)
    elasticsearch.DeleteAlias(c, "books_v2", "latest")

    elasticsearch.PutIndexTemplate(c, "books_tpl", `{"index_patterns":["books-*"],"priority":100}`)
    println elasticsearch.IndexTemplateExists(c, "books_tpl")
    elasticsearch.DeleteIndexTemplate(c, "books_tpl")

    elasticsearch.Refresh(c, "books_v2")
    elasticsearch.Flush(c, "books_v2")
    elasticsearch.ForceMerge(c, "books_v2", 1)
    elasticsearch.CloseIndex(c, "books_v2")
    elasticsearch.OpenIndex(c, "books_v2")
    println elasticsearch.Analyze(c, "books_v2", "standard", "The Book of Kings")
    println elasticsearch.IndexStats(c, "books_v2")

    elasticsearch.DeleteIndex(c, "books_v1")
    elasticsearch.DeleteIndex(c, "books_v2")
end

IndexExists

#
func IndexExists(c: Client, index: str): bool

Whether an index (or alias) exists.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

GetIndex

#
func GetIndex(c: Client, index: str): str

The raw JSON definition of an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

GetMapping

#
func GetMapping(c: Client, index: str): str

The raw mappings JSON of an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

PutMapping

#
func PutMapping(c: Client, index: str, body: str): bool

Adds fields to the mappings of an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

GetSettings

#
func GetSettings(c: Client, index: str): str

The raw settings JSON of an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

PutSettings

#
func PutSettings(c: Client, index: str, body: str): bool

Changes dynamic settings of an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

Refresh

#
func Refresh(c: Client, index: str): bool

Makes recent changes searchable; an empty index refreshes all.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

Flush

#
func Flush(c: Client, index: str): bool

Flushes an index to disk; an empty index flushes all.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

ForceMerge

#
func ForceMerge(c: Client, index: str, max_segments: int): bool

Merges segments, down to max_segments when it is above 0.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

OpenIndex

#
func OpenIndex(c: Client, index: str): bool

Opens a closed index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

CloseIndex

#
func CloseIndex(c: Client, index: str): bool

Closes an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

PutAlias

#
func PutAlias(c: Client, index: str, alias: str): bool

Points an alias at an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

DeleteAlias

#
func DeleteAlias(c: Client, index: str, alias: str): bool

Removes an alias from an index.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

AliasExists

#
func AliasExists(c: Client, alias: str): bool

Whether an alias exists.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

GetAlias

#
func GetAlias(c: Client, alias: str): Vector<str>

The indices an alias points at.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

SwapAlias

#
func SwapAlias(c: Client, alias: str, old_index: str, new_index: str): bool

Moves an alias from one index to another atomically, the usual zero downtime reindex step.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

UpdateAliases

#
func UpdateAliases(c: Client, actions: str): bool

Runs a raw JSON array of alias actions atomically.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

PutIndexTemplate

#
func PutIndexTemplate(c: Client, name: str, body: str): bool

Creates or replaces a composable index template.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

DeleteIndexTemplate

#
func DeleteIndexTemplate(c: Client, name: str): bool

Deletes an index template.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

IndexTemplateExists

#
func IndexTemplateExists(c: Client, name: str): bool

Whether an index template exists.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

Reindex

#
func Reindex(c: Client, source: str, dest: str): i64

Copies every document of one index into another and returns how many were written; -1 on error.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

Analyze

#
func Analyze(c: Client, index: str, analyzer: str, text: str): Vector<str>

The tokens an analyzer makes of a text; an empty index uses the cluster analyzers.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

MatchNone

#
func MatchNone(): str

A query matching no document.

db-elasticsearch-Queries.salam
import db.elasticsearch

func main:
    c := elasticsearch.Connect("http://localhost:9200")

    mut words := Vector {} as Vector<str>
    words.Push("poetry")
    words.Push("history")
    mut fields := Vector {} as Vector<str>
    fields.Push("title")
    fields.Push("summary")
    mut ids := Vector {} as Vector<str>
    ids.Push("1")
    ids.Push("2")

    mut must := Vector {} as Vector<str>
    must.Push(
        elasticsearch.MatchAnd("title", "persian poetry")
    )
    must.Push(elasticsearch.MatchFuzzy("title", "shahnama"))
    must.Push(elasticsearch.MatchPhrase("summary", "book of kings"))
    must.Push(elasticsearch.MatchPhrasePrefix("summary", "book of"))
    must.Push(elasticsearch.MultiMatch("kings", fields))
    mut filter := Vector {} as Vector<str>
    filter.Push(elasticsearch.TermInt("year", 1010 as i64))
    filter.Push(elasticsearch.TermBool("published", true))
    filter.Push(elasticsearch.Terms("tag", words))
    filter.Push(elasticsearch.RangeExclusive("year", "900", "1500"))
    filter.Push(elasticsearch.FieldExists("author"))
    filter.Push(elasticsearch.Ids(ids))
    filter.Push(elasticsearch.Nested("reviews", elasticsearch.Term("reviews.stars", "5")))
    filter.Push(elasticsearch.GeoDistance("place", 36.2, 59.6, "50km"))
    mut should := Vector {} as Vector<str>
    should.Push(elasticsearch.Prefix("author", "fer"))
    should.Push(elasticsearch.Wildcard("author", "f*si"))
    should.Push(elasticsearch.Regexp("author", "fer.*"))
    should.Push(elasticsearch.Fuzzy("author", "ferdowsy"))
    should.Push(elasticsearch.QueryString("title:shah* AND year:[900 TO 1500]"))
    should.Push(elasticsearch.SimpleQueryString("epic | lyric", fields))
    mut none := Vector {} as Vector<str>
    none.Push(elasticsearch.MatchNone())

    query := elasticsearch.Bool(must, filter, should, none)
    println elasticsearch.Or(should)
    println elasticsearch.ConstantScore(elasticsearch.FieldExists("author"))

    mut vector := Vector {} as Vector<f64>
    vector.Push(0.1)
    vector.Push(0.9)
    println elasticsearch.Knn("embedding", vector, 5, 50)

    mut aggs := elasticsearch.AddAgg("", "authors", elasticsearch.CardinalityAgg("author"))
    aggs = elasticsearch.AddAgg(aggs, "first", elasticsearch.MinAgg("year"))
    aggs = elasticsearch.AddAgg(aggs, "total", elasticsearch.SumAgg("pages"))
    aggs = elasticsearch.AddAgg(aggs, "pages", elasticsearch.StatsAgg("pages"))
    aggs = elasticsearch.AddAgg(aggs, "values", elasticsearch.ValueCountAgg("year"))
    aggs = elasticsearch.AddAgg(aggs, "by_century", elasticsearch.HistogramAgg("year", 100.0))
    aggs = elasticsearch.AddAgg(aggs, "by_month", elasticsearch.DateHistogramAgg("added", "month"))
    aggs = elasticsearch.AddAgg(
        aggs, "drafts", elasticsearch.FilterAgg(elasticsearch.Term("status", "draft"))
    )
    aggs = elasticsearch.AddAgg(aggs, "latest", elasticsearch.TopHitsAgg(3))

    mut sort := Vector {} as Vector<str>
    sort.Push(elasticsearch.SortAsc("year"))
    req := elasticsearch.SearchRequest {
        query = query,
        size = 20,
        sort = sort,
        aggs = aggs
    }
    body := elasticsearch.SearchBody(req)
    println body
    println elasticsearch.AddMember(body, "track_total_hits", "true")

    res := elasticsearch.SearchRaw(c, "books", body)
    if not res.ok:
        println elasticsearch.Error(c)
        ret
    end
    println res.total, elasticsearch.AggRaw(res, "pages")
    each b in elasticsearch.AggBucketsIn(elasticsearch.AggRaw(res, "by_century"), "buckets"):
        println b.key, b.doc_count
    end

    quick := elasticsearch.SearchQuery(c, "books", elasticsearch.MatchAll(), 5)
    println quick.total

    mut bodies := Vector {} as Vector<str>
    bodies.Push(
        `{"query":` + elasticsearch.Match("title", "shahnameh") + `}`
    )
    bodies.Push(`{"query":` + elasticsearch.Prefix("author", "fer") + `}`)
    each r in elasticsearch.MSearch(c, "books", bodies):
        println r.ok, r.total
    end

    parsed := elasticsearch.ParseSearchResult(
        `{"took":1,"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}`
    )
    println parsed.total
end

Match

#
func Match(field: str, text: str): str

A full text match query.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

MatchAnd

#
func MatchAnd(field: str, text: str): str

A match query that needs every word.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

MatchFuzzy

#
func MatchFuzzy(field: str, text: str): str

A match query with automatic fuzziness, forgiving typos.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

MatchPhrase

#
func MatchPhrase(field: str, text: str): str

A query for the exact phrase.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

MatchPhrasePrefix

#
func MatchPhrasePrefix(field: str, text: str): str

A phrase query whose last word is a prefix, for search as you type.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

MultiMatch

#
func MultiMatch(text: str, fields: Vector<str>): str

A match over several fields; a field may carry a boost like title^2.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Term

#
func Term(field: str, value: str): str

An exact value term query.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

TermInt

#
func TermInt(field: str, value: i64): str

A term query on a number.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

TermBool

#
func TermBool(field: str, value: bool): str

A term query on a boolean.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Terms

#
func Terms(field: str, values: Vector<str>): str

Matches any of several exact values.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Range

#
func Range(field: str, low: str, high: str): str

An inclusive range query; an empty bound is open. Bounds are numbers or dates as text.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

RangeExclusive

#
func RangeExclusive(field: str, low: str, high: str): str

A range query that excludes its bounds.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

FieldExists

#
func FieldExists(field: str): str

Matches documents that have a value in the field.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Prefix

#
func Prefix(field: str, value: str): str

Matches values that start with a prefix.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Wildcard

#
func Wildcard(field: str, pattern: str): str

A wildcard query with * and ?.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Regexp

#
func Regexp(field: str, pattern: str): str

A regular expression query.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

QueryString

#
func QueryString(query: str): str

A query_string query in Lucene syntax.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

SimpleQueryString

#
func SimpleQueryString(query: str, fields: Vector<str>): str

A forgiving simple_query_string query for user input, over the given fields.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Bool

#
func Bool(must: Vector<str>, filter: Vector<str>, should: Vector<str>, must_not: Vector<str>): str

A bool query from must, filter, should and must_not clauses; any list may be empty.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

And

#
func And(clauses: Vector<str>): str

Matches when every clause matches.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

Or

#
func Or(clauses: Vector<str>): str

Matches when at least one clause matches.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Filtered

#
func Filtered(query: str, filters: Vector<str>): str

A scored query narrowed by unscored filters.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

ConstantScore

#
func ConstantScore(filter: str): str

Runs a filter and gives every match the same score.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Nested

#
func Nested(path: str, query: str): str

A query on nested objects under a path.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

GeoDistance

#
func GeoDistance(field: str, lat: f64, lon: f64, distance: str): str

Matches geo points within a distance, such as 10km, of a point.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Knn

#
func Knn(field: str, vector: Vector<f64>, k: int, num_candidates: int): str

An approximate nearest neighbour clause for dense vector search; put it in SearchRequest.knn.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Highlight

#
func Highlight(fields: Vector<str>): str

A highlight section for the given fields.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

TermsAgg

#
func TermsAgg(field: str, size: int): str

A terms bucket aggregation, the top values of a field.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

ValueCountAgg

#
func ValueCountAgg(field: str): str

How many values a field has.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

CardinalityAgg

#
func CardinalityAgg(field: str): str

The approximate number of distinct values.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

StatsAgg

#
func StatsAgg(field: str): str

Count, min, max, average and sum together.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

HistogramAgg

#
func HistogramAgg(field: str, interval: f64): str

Buckets of a fixed numeric width.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

DateHistogramAgg

#
func DateHistogramAgg(field: str, calendar_interval: str): str

Buckets per calendar interval such as day or month.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

FilterAgg

#
func FilterAgg(query: str): str

A single bucket of the documents matching a query.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

TopHitsAgg

#
func TopHitsAgg(size: int): str

The best hits inside each bucket.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

AddAgg

#
func AddAgg(aggs: str, name: str, agg: str): str

Adds a named aggregation to an aggregations object; start from an empty string.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

SubAggs

#
func SubAggs(agg: str, aggs: str): str

Nests an aggregations object under a bucket aggregation.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

AddMember

#
func AddMember(obj: str, key: str, raw: str): str

Adds a raw member to a JSON object, for options without a helper.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

SearchBody

#
func SearchBody(req: SearchRequest): str

The JSON body of a SearchRequest.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

BulkIndex

#
func BulkIndex(b &: Bulk, index: str, id: str, doc: str)

Adds an index action; an empty id lets Elasticsearch pick one. Multi line JSON is minified.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkCreate

#
func BulkCreate(b &: Bulk, index: str, id: str, doc: str)

Adds a create action, which fails for an existing id.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkUpdate

#
func BulkUpdate(b &: Bulk, index: str, id: str, partial: str)

Adds a partial update action.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkUpsert

#
func BulkUpsert(b &: Bulk, index: str, id: str, doc: str)

Adds an update that creates the document when it is missing.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkDelete

#
func BulkDelete(b &: Bulk, index: str, id: str)

Adds a delete action.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkLen

#
func BulkLen(b: Bulk): int

How many actions the bulk request holds.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkBody

#
func BulkBody(b: Bulk): str

The NDJSON body of the bulk request.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

BulkReset

#
func BulkReset(b &: Bulk)

Empties the bulk request for reuse.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

ParseBulkResult

#
func ParseBulkResult(body: str): BulkResult

Parses a raw bulk response.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

RunBulk

#
func RunBulk(c: Client, b: Bulk): BulkResult

Sends the bulk request. ok is false when any action failed; check items.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

RunBulkWith

#
func RunBulkWith(c: Client, index: str, b: Bulk, opts: Options): BulkResult

RunBulk with a default index for actions that name none, and options.

The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam

DefaultConfig

#
func DefaultConfig(): Config

A config for DEFAULT_URL with the default timeout and retries.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

NewClient

#
func NewClient(cfg: Config): Client

Builds a client from a config. Node URLs may carry credentials (https://user:pass@host:9200) and a path prefix, and one string may list several nodes separated by commas.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Connect

#
func Connect(url: str): Client

A client for one URL, or several separated by commas.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

ConnectAuth

#
func ConnectAuth(url: str, username: str, password: str): Client

A client that sends HTTP basic authentication.

db-elasticsearch-Connect.salam
import db.elasticsearch

func main:
    println elasticsearch.EncodeBasic("elastic", "s3cret")
    println elasticsearch.DecodeCloudId("prod:ZXVyb3BlLmNsb3VkLmVzLmlvJGFiYyRkZWY=")

    basic := elasticsearch.ConnectAuth("https://localhost:9200", "elastic", "s3cret")
    println elasticsearch.AuthHeader(basic)
    keyed := elasticsearch.ConnectApiKey(
        "https://localhost:9200", "VnVhQ2ZHY0JDZGJrUW0tZTVhT3g6dWkybHAyYXhUTm1zeWFrdzl0dk5ndw=="
    )
    println elasticsearch.AuthHeader(keyed)
    cloud := elasticsearch.ConnectCloud("prod:ZXVyb3BlLmNsb3VkLmVzLmlvJGFiYyRkZWY=", "key")
    println elasticsearch.Ok(cloud)

    c := elasticsearch.Connect("http://localhost:9200")
    if not elasticsearch.Ok(c):
        println elasticsearch.Status(c), elasticsearch.ErrorReason(c)
    end
    println elasticsearch.Distribution(c)
    println elasticsearch.Nodes(c)
    println elasticsearch.NodesInfo(c)
    println elasticsearch.ClusterStats(c)
    println elasticsearch.WaitForStatus(c, "yellow", "30s").status

    r := elasticsearch.PerformNdjson(
        c, "POST", "/_bulk", `{"delete":{"_index":"books","_id":"1"}}` + "\n"
    )
    println r.status
end

ConnectApiKey

#
func ConnectApiKey(url: str, api_key: str): Client

A client that authenticates with an API key, either encoded or as id:key.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

ConnectCloud

#
func ConnectCloud(cloud_id: str, api_key: str): Client

A client for an Elastic Cloud deployment, from its cloud id and an API key.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

Ok

#
func Ok(c: Client): bool

Whether the client has at least one valid node.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

Error

#
func Error(c: Client): str

The error of the last call: the type and reason Elasticsearch sent, or a connection or config error. Empty after a success.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

ErrorType

#
func ErrorType(c: Client): str

The error.type of the last failed call, for example version_conflict_engine_exception.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

ErrorReason

#
func ErrorReason(c: Client): str

The error.reason of the last failed call.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

Status

#
func Status(c: Client): int

The HTTP status of the last call, 0 when no answer came.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

Nodes

#
func Nodes(c: Client): Vector<str>

The node URLs the client rotates over.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

AuthHeader

#
func AuthHeader(c: Client): str

The Authorization header value the client sends.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

DecodeCloudId

#
func DecodeCloudId(cloud_id: str): str

Turns an Elastic Cloud id into the HTTPS URL of its Elasticsearch endpoint; empty when it cannot be decoded.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

Close

#
func Close(c &: Client)

Frees the client. The handle is null afterwards.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

Perform

#
func Perform(c: Client, method: str, path: str, body: str): Response

Sends any request with a JSON body and returns the raw response. Use it for every API this package does not wrap.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

PerformNdjson

#
func PerformNdjson(c: Client, method: str, path: str, body: str): Response

Like Perform, with an application/x-ndjson body.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

Distribution

#
func Distribution(c: Client): str

elasticsearch or opensearch, asked from the server once and remembered.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

IsOpenSearch

#
func IsOpenSearch(c: Client): bool

Whether the cluster is OpenSearch. SQL and point in time calls pick the right endpoints on their own.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

EncodeBasic

#
func EncodeBasic(username: str, password: str): str

The base64 of user:password used by basic authentication.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

ParseSearchResult

#
func ParseSearchResult(body: str): SearchResult

Parses a raw search response, for example one from Perform.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

Search

#
func Search(c: Client, index: str, req: SearchRequest): SearchResult

Runs a search on an index, a comma separated list, a pattern, or with an empty index on a point in time.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

SearchQuery

#
func SearchQuery(c: Client, index: str, query: str, size: int): SearchResult

Runs a query and returns up to size hits.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

SearchRaw

#
func SearchRaw(c: Client, index: str, body: str): SearchResult

Runs a search with a raw JSON body.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

SearchScroll

#
func SearchScroll(c: Client, index: str, req: SearchRequest, keep_alive: str): SearchResult

Starts a scroll; keep calling Scroll with scroll_id until a page comes back empty.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

Scroll

#
func Scroll(c: Client, scroll_id: str, keep_alive: str): SearchResult

The next page of a scroll.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

ClearScroll

#
func ClearScroll(c: Client, scroll_id: str): bool

Releases a scroll early.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

OpenPit

#
func OpenPit(c: Client, index: str, keep_alive: str): str

Opens a point in time on an index for consistent deep paging with search_after.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

ClosePit

#
func ClosePit(c: Client, pit_id: str): bool

Closes a point in time.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

DeleteByQuery

#
func DeleteByQuery(c: Client, index: str, query: str): i64

Deletes every document matching a query and returns how many; -1 on error.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

DeleteByQueryWith

#
func DeleteByQueryWith(c: Client, index: str, query: str, opts: Options): i64

DeleteByQuery with options such as refresh and conflicts.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

UpdateByQuery

#
func UpdateByQuery(c: Client, index: str, query: str, script: str): i64

Runs a script on every document matching a query and returns how many changed; -1 on error.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

UpdateByQueryWith

#
func UpdateByQueryWith(c: Client, index: str, query: str, script: str, opts: Options): i64

UpdateByQuery with options.

The example for this item is shown with the ones above: db-elasticsearch-Documents.salam

MSearch

#
func MSearch(c: Client, index: str, bodies: Vector<str>): Vector<SearchResult>

Runs several searches in one request; each result has its own ok and error.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

AggValueIn

#
func AggValueIn(aggs: str, name: str): f64

The value of a metric aggregation inside raw aggregations JSON, such as Bucket.raw.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

AggBucketsIn

#
func AggBucketsIn(aggs: str, name: str): Vector<Bucket>

The buckets of a bucket aggregation inside raw aggregations JSON.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

AggValue

#
func AggValue(res: SearchResult, name: str): f64

The value of a metric aggregation in a result.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

AggBuckets

#
func AggBuckets(res: SearchResult, name: str): Vector<Bucket>

The buckets of a bucket aggregation in a result.

The example for this item is shown with the ones above: db-elasticsearch-Search.salam

AggRaw

#
func AggRaw(res: SearchResult, name: str): str

The raw JSON of one aggregation in a result.

The example for this item is shown with the ones above: db-elasticsearch-Queries.salam

GetInfo

#
func GetInfo(c: Client): Info

The name, version and distribution of the cluster; distribution is opensearch on OpenSearch.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

ClusterHealth

#
func ClusterHealth(c: Client): Health

The health of the cluster.

The example for this item is shown with the ones above: db-elasticsearch-Client.salam

WaitForStatus

#
func WaitForStatus(c: Client, status: str, timeout: str): Health

Waits until the cluster reaches a status such as yellow, or the timeout runs out; ok is false on timeout.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

ClusterStats

#
func ClusterStats(c: Client): str

The raw cluster statistics JSON.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

NodesInfo

#
func NodesInfo(c: Client): str

The raw node information JSON.

The example for this item is shown with the ones above: db-elasticsearch-Connect.salam

CatIndices

#
func CatIndices(c: Client, pattern: str): Vector<IndexInfo>

The indices that match a pattern (all of them when it is empty), sorted by name.

The example for this item is shown with the ones above: db-elasticsearch-Indices.salam

PutPipeline

#
func PutPipeline(c: Client, id: str, body: str): bool

Creates or replaces an ingest pipeline.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

GetPipeline

#
func GetPipeline(c: Client, id: str): str

The raw JSON of a pipeline, empty when it is missing.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeletePipeline

#
func DeletePipeline(c: Client, id: str): bool

Deletes a pipeline.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

SimulatePipeline

#
func SimulatePipeline(c: Client, id: str, body: str): str

Runs sample documents through a pipeline (an empty id uses the pipeline in the body) and returns the raw result.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

CreateDataStream

#
func CreateDataStream(c: Client, name: str): bool

Creates a data stream; a matching index template with data_stream must exist.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

GetDataStream

#
func GetDataStream(c: Client, name: str): str

The raw JSON of matching data streams.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeleteDataStream

#
func DeleteDataStream(c: Client, name: str): bool

Deletes a data stream and its backing indices.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

Rollover

#
func Rollover(c: Client, target: str, body: str): bool

Rolls an alias or data stream over to a new index, with optional conditions in the body.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

PutLifecyclePolicy

#
func PutLifecyclePolicy(c: Client, name: str, body: str): bool

Creates a lifecycle policy: ILM on Elasticsearch, ISM on OpenSearch. The body follows the server's own format.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

GetLifecyclePolicy

#
func GetLifecyclePolicy(c: Client, name: str): str

The raw JSON of a lifecycle policy.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeleteLifecyclePolicy

#
func DeleteLifecyclePolicy(c: Client, name: str): bool

Deletes a lifecycle policy.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

PutRepository

#
func PutRepository(c: Client, name: str, body: str): bool

Registers a snapshot repository; an fs location must be listed in path.repo.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeleteRepository

#
func DeleteRepository(c: Client, name: str): bool

Unregisters a snapshot repository.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

CreateSnapshot

#
func CreateSnapshot(c: Client, repository: str, snapshot: str, body: str): bool

Takes a snapshot and waits for it to finish.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

RestoreSnapshot

#
func RestoreSnapshot(c: Client, repository: str, snapshot: str, body: str): bool

Restores a snapshot and waits for it to finish.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeleteSnapshot

#
func DeleteSnapshot(c: Client, repository: str, snapshot: str): bool

Deletes a snapshot.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

ListSnapshots

#
func ListSnapshots(c: Client, repository: str): Vector<str>

The snapshot names in a repository.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

GetClusterSettings

#
func GetClusterSettings(c: Client): str

The raw cluster settings, flattened.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

PutClusterSettings

#
func PutClusterSettings(c: Client, body: str): bool

Changes persistent or transient cluster settings; null resets one.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

GetTask

#
func GetTask(c: Client, id: str): Task

The state of a task; poll it until completed.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

CancelTask

#
func CancelTask(c: Client, id: str): bool

Cancels a running task; false when no node knew it.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

StartReindex

#
func StartReindex(c: Client, body: str): str

Starts a reindex in the background and returns its task id.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

StartDeleteByQuery

#
func StartDeleteByQuery(c: Client, index: str, query: str): str

Starts a delete by query in the background and returns its task id.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

StartUpdateByQuery

#
func StartUpdateByQuery(c: Client, index: str, query: str, script: str): str

Starts an update by query in the background and returns its task id.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

PutStoredScript

#
func PutStoredScript(c: Client, id: str, lang: str, source: str): bool

Stores a script: painless source, or a mustache search template given as JSON.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeleteStoredScript

#
func DeleteStoredScript(c: Client, id: str): bool

Deletes a stored script.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

SearchTemplate

#
func SearchTemplate(c: Client, index: str, id: str, params: str): SearchResult

Runs a stored search template with JSON params.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

SubmitAsyncSearch

#
func SubmitAsyncSearch(c: Client, index: str, req: SearchRequest, wait: str): AsyncSearch

Starts an async search, waiting up to wait (such as 1s) for the result. Works on OpenSearch too.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

GetAsyncSearch

#
func GetAsyncSearch(c: Client, id: str, wait: str): AsyncSearch

Fetches an async search by id.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

DeleteAsyncSearch

#
func DeleteAsyncSearch(c: Client, id: str): bool

Deletes an async search and its stored result.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

Explain

#
func Explain(c: Client, index: str, id: str, query: str): str

The raw explanation of how a document scores against a query.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

ValidateQuery

#
func ValidateQuery(c: Client, index: str, query: str): bool

Whether a query is valid for an index, without running it.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

FieldCaps

#
func FieldCaps(c: Client, index: str, fields: Vector<str>): str

The raw capabilities of fields (all when the list is empty) across indices.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

TermVectors

#
func TermVectors(c: Client, index: str, id: str, fields: Vector<str>): str

The raw term vectors of a document's fields.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam

IndexStats

#
func IndexStats(c: Client, index: str): str

The raw statistics of an index, or of all with an empty name.

The example for this item is shown with the ones above: db-elasticsearch-Admin.salam