An Elasticsearch and OpenSearch client: documents, search, aggregations, bulk, SQL and index management.
Types
SQL query results; implements db.Rows and fetches further pages with the cursor as you call Next.
Name Type Description handlevoid*The internal state pointer.
db-elasticsearch-Sql.salam Copy
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
Whether the query succeeded.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The error of the query, empty on success.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
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
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
func ColumnName (col: int ): str The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
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
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
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
A cell as text; empty for null.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
func Int64 (col: int ): i64 The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
func Float (col: int ): f64 The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
Frees the rows and closes an open cursor.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
A client seen through db.Connection, so code written for the db interfaces can read Elasticsearch with SQL.
Name Type Description handlevoid*The internal state pointer.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
Whether the client is valid.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
Whether the cluster answers.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
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
func Query (sql: str ): dyn db.Rows The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
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
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The error of the last call.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
Quotes a string literal for SQL.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The transaction Database.Begin returns. Elasticsearch has no transactions, so every call fails.
Name Type Description handlevoid*The internal state pointer.
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
func Exec (_sql: str ): int The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
func Query (_sql: str ): dyn db.Rows The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
The example for this item is shown with the ones above: db-elasticsearch-Sql.salam
Everything a client needs: nodes, credentials, TLS, timeout, retries and extra headers.
Name Type Description 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 Copy
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
A client handle. It is cheap to pass by value; free it with Close.
Name Type Description handlevoid*The internal state pointer.
The example for this item is shown with the ones above: db-elasticsearch-Client.salam
The raw answer of Perform: status, body and the parsed error envelope.
Name Type Description 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
Optional request parameters shared by the write calls: refresh, routing, pipeline, optimistic concurrency and more.
Name Type Description 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
The outcome of indexing, creating, updating or deleting one document.
Name Type Description 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
One fetched document with its metadata and raw _source.
Name Type Description 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
Name Type Description 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 Copy
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
A parsed search response: totals, hits, aggregations and paging ids.
Name Type Description 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
A search request; SearchBody turns it into JSON. Empty fields are left out.
Name Type Description 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
One bucket of a bucket aggregation.
Name Type Description 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
A bulk request being built; add actions with the Bulk* functions.
Name Type Description linesVector<str>The NDJSON lines so far. countint = 0How many actions were added.
db-elasticsearch-Bulk.salam Copy
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
The result of one action in a bulk request.
Name Type Description 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
The result of a bulk request, with one item per action.
Name Type Description 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
What the root endpoint says about the cluster.
Name Type Description 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
Name Type Description 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
Name Type Description 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
An async search: its id, whether it still runs, and the result so far.
Name Type Description 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 Copy
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
A server task started with one of the Start* calls.
Name Type Description 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
Functions
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
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
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
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
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
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 Copy
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
func IndexWith (c: Client, index: str , id: str , doc: str , opts: Options): WriteResult The example for this item is shown with the ones above: db-elasticsearch-Client.salam
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
func CreateWith (c: Client, index: str , id: str , doc: str , opts: Options): WriteResult The example for this item is shown with the ones above: db-elasticsearch-Documents.salam
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
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
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
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
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
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
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
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
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
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
func DeleteWith (c: Client, index: str , id: str , opts: Options): WriteResult The example for this item is shown with the ones above: db-elasticsearch-Documents.salam
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
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
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
func DeleteIndex (c: Client, index: str ): bool db-elasticsearch-Indices.salam Copy
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
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
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
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
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
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
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
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
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
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
func OpenIndex (c: Client, index: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Indices.salam
func CloseIndex (c: Client, index: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Indices.salam
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
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
func AliasExists (c: Client, alias: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Indices.salam
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
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
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
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
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
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
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
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
A query matching every document.
The example for this item is shown with the ones above: db-elasticsearch-Search.salam
A query matching no document.
db-elasticsearch-Queries.salam Copy
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
func Match (field: str , text: str ): str The example for this item is shown with the ones above: db-elasticsearch-Search.salam
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
func Fuzzy (field: str , value: str ): str The example for this item is shown with the ones above: db-elasticsearch-Queries.salam
func Ids (ids: Vector < str >): str The example for this item is shown with the ones above: db-elasticsearch-Queries.salam
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
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
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
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
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
func Not (clause: str ): str Matches when the clause does not.
The example for this item is shown with the ones above: db-elasticsearch-Search.salam
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
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
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
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
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
func SortAsc (field: str ): str An ascending sort clause.
The example for this item is shown with the ones above: db-elasticsearch-Queries.salam
func SortDesc (field: str ): str A descending sort clause.
The example for this item is shown with the ones above: db-elasticsearch-Search.salam
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
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
func AvgAgg (field: str ): str The example for this item is shown with the ones above: db-elasticsearch-Search.salam
func SumAgg (field: str ): str The example for this item is shown with the ones above: db-elasticsearch-Queries.salam
func MinAgg (field: str ): str The smallest value of a field.
The example for this item is shown with the ones above: db-elasticsearch-Queries.salam
func MaxAgg (field: str ): str The largest value of a field.
The example for this item is shown with the ones above: db-elasticsearch-Search.salam
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
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
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
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
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
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
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
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
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
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
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
The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam
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
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
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
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
func BulkDelete (b &: Bulk, index: str , id: str ) The example for this item is shown with the ones above: db-elasticsearch-Bulk.salam
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
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
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
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
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
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
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
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
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
func ConnectAuth (url: str , username: str , password: str ): Client A client that sends HTTP basic authentication.
db-elasticsearch-Connect.salam Copy
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
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
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
Whether the client has at least one valid node.
The example for this item is shown with the ones above: db-elasticsearch-Connect.salam
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
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
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
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
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
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
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
Frees the client. The handle is null afterwards.
The example for this item is shown with the ones above: db-elasticsearch-Client.salam
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
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
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
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
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
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
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
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
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
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
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
func ClearScroll (c: Client, scroll_id: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Search.salam
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
func ClosePit (c: Client, pit_id: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Search.salam
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
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
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
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
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
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
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
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
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
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
func Ping (c: Client): bool Whether the cluster answers.
The example for this item is shown with the ones above: db-elasticsearch-Client.salam
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
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
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
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
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
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
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
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
func DeletePipeline (c: Client, id: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Admin.salam
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
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
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
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
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
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
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
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
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
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
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
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
func DeleteSnapshot (c: Client, repository: str , snapshot: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Admin.salam
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
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
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
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
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
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
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
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
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
func DeleteStoredScript (c: Client, id: str ): bool The example for this item is shown with the ones above: db-elasticsearch-Admin.salam
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
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
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
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
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
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
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
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
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