Standard library · Database

db/opensearch

An OpenSearch client: documents, bulk, the query DSL, aggregations, scroll and point in time, index admin, SQL and PPL, k-NN vector search, ISM, security and AWS signing.

import db.opensearch

OpenSearch is an open source search and analytics engine. This package speaks its REST API directly over net.tcp and tls, with no outside library: several nodes with retries and dead node skipping, basic, bearer and AWS SigV4 authentication (for Amazon OpenSearch Service and Serverless), and TLS with your own CA file or, for a test server, no verification. On top of that it covers documents, bulk, every common query and aggregation, scroll and point in time paging, index, alias, template and data stream admin, cluster, task, snapshot and pipeline admin, and the plugins that make OpenSearch what it is: SQL and PPL, k-NN and neural search, hybrid search pipelines, ISM policies, the security plugin, alerting monitors and ML Commons.

Queries, aggregations and request bodies are plain JSON text: the builders such as Match, BoolOf and TermsAgg return it, and anything they do not cover can be written as a backtick string. Results come back as Salam structs whose JSON parts (a hit's source, the aggregations) are raw text you read with Buckets, AggValue and JsonPath. Every call records its status and error on the client, so read Error or ErrorType after a call that returned false. Conn boxes a client as a db.Connection, so SQL code written for the other engines can query OpenSearch too. For a route with no function of its own, use Perform. Only the examples for the query builders and request signing run here; the others need a server, so they are only checked.

db/elasticsearch also talks to the OpenSearch core API. Use this package when you need what only OpenSearch has: PPL, k-NN, neural and hybrid search, ISM, the security plugin, alerting, ML Commons, or AWS SigV4 for Amazon OpenSearch Service and Serverless.

Types

BoolQuery

struct BoolQuery
The four clause lists and options of a bool query, for BoolOf.
NameTypeDescription
mustVectorMust match and adds to the score.
filterVectorMust match, but does not score; cached.
shouldVectorShould match; raises the score.
must_notVectorMust not match.
minimum_should_matchstr = ""How many should clauses must match, such as 1 or 75%.
boostf64 = 0Multiplies the score; 0 leaves it out.
db-opensearch-Query.salam
import db.opensearch

func list(a: str, b: str): Vector<str>:
    mut v := Vector {} as Vector<str>
    v.push(a)
    if b.len() > 0: v.push(b) end
    ret v
end

func main:
    println opensearch.MatchAll(), opensearch.MatchNone()
    println opensearch.Match("title", "salam"), opensearch.MatchAnd("title", "salam world")
    println opensearch.MatchFuzzy("title", "slam"), opensearch.MatchPhrase("title", "hello world")
    println opensearch.MatchPhraseSlop("title", "hello world", 2), opensearch.MatchPhrasePrefix("title", "sal")
    println opensearch.MatchBoolPrefix("title", "quick bro")
    println opensearch.MultiMatch("salam", list("title^2", "body")), opensearch.MultiMatchType("salam", list("title", "body"), "phrase")
    println opensearch.Term("tag", "news"), opensearch.TermInt("year", 1403), opensearch.TermBool("published", true)
    println opensearch.TermCaseInsensitive("tag", "News"), opensearch.Terms("tag", list("news", "sport"))
    mut years := Vector {} as Vector<i64>
    years.push(1402)
    years.push(1403)
    println opensearch.TermsInt("year", years), opensearch.TermsLookup("tag", "users", "7", "follows")
    println opensearch.TermsSet("skills", list("go", "salam"), "required")
    println opensearch.Range("date", "2026-01-01", "2026-12-31"), opensearch.RangeExclusive("price", "10", "20")
    println opensearch.RangeNum("price", 9.5, 20.0), opensearch.RangeInt("stock", 1, 100), opensearch.RangeOp("price", "lt", "5")
    println opensearch.DateRange("at", "now-7d/d", "now", "", "+03:30")
    println opensearch.FieldExists("email"), opensearch.Prefix("sku", "AB-"), opensearch.Wildcard("sku", "AB-*-9")
    println opensearch.Regexp("sku", "AB-[0-9]+"), opensearch.Fuzzy("name", "maryem"), opensearch.Ids(list("1", "2"))
    println opensearch.QueryString("title:salam AND year:1403")
    println opensearch.QueryStringFields("salam world", list("title", "body"), "AND")
    println opensearch.SimpleQueryString("salam -draft", list("title", ""))

    mut b := opensearch.BoolQuery { minimum_should_match = "1", boost = 1.5 }
    b.must.push(opensearch.Match("title", "salam"))
    b.filter.push(opensearch.Term("status", "published"))
    b.should.push(opensearch.Term("tag", "featured"))
    b.must_not.push(opensearch.Term("tag", "spam"))
    println opensearch.BoolOf(b)
    println opensearch.Bool(list(opensearch.Match("t", "x"), ""), list(opensearch.Term("a", "1"), ""), Vector {} as Vector<str>, Vector {} as Vector<str>)
    println opensearch.And(list(opensearch.Term("a", "1"), opensearch.Term("b", "2")))
    println opensearch.Or(list(opensearch.Term("a", "1"), opensearch.Term("b", "2"))), opensearch.Not(opensearch.Term("a", "1"))
    println opensearch.Filtered(opensearch.Match("t", "x"), list(opensearch.Term("a", "1"), ""))
    println opensearch.ConstantScore(opensearch.Term("tag", "news"), 1.2)
    println opensearch.DisMax(list(opensearch.Match("title", "x"), opensearch.Match("body", "x")), 0.3)
    println opensearch.Boosting(opensearch.Match("t", "apple"), opensearch.Match("t", "pie"), 0.5)
    println opensearch.Nested("comments", opensearch.Match("comments.text", "great"))
    println opensearch.HasChild("answer", opensearch.MatchAll()), opensearch.HasParent("question", opensearch.MatchAll())
    println opensearch.MoreLikeThis(list("title", "body"), "search engines in Salam")
    println opensearch.ScriptQuery("doc['stock'].value > params.min", `{"min":5}`)
    println opensearch.ScriptScore(opensearch.MatchAll(), "_score * doc['rank'].value", "")
    println opensearch.FunctionScore(opensearch.Match("t", "x"), list(opensearch.FieldValueFactor("likes", 1.2, "log1p"), ""), "sum", "multiply")
    println opensearch.GeoDistance("location", 35.69, 51.39, "5km")
    println opensearch.GeoBoundingBox("location", 36.0, 51.0, 35.5, 51.8)

    mut v := Vector {} as Vector<f64>
    v.push(0.12)
    v.push(-0.5)
    v.push(0.9)
    println opensearch.Knn("embedding", v, 10), opensearch.KnnVector(v)
    println opensearch.KnnFiltered("embedding", v, 10, opensearch.Term("lang", "fa"))
    println opensearch.KnnRadial("embedding", v, 0.5), opensearch.KnnMinScore("embedding", v, 0.8)
    println opensearch.Neural("embedding", "a cosy cafe", "model-1", 5), opensearch.NeuralSparse("tokens", "a cosy cafe", "model-2")
    println opensearch.Hybrid(list(opensearch.Match("text", "cafe"), opensearch.Neural("embedding", "cafe", "model-1", 5)))

    println opensearch.SortAsc("price"), opensearch.SortDesc("date"), opensearch.SortScore()
    println opensearch.SortGeo("location", 35.69, 51.39, "km")
    println opensearch.Highlight(list("title", "body")), opensearch.HighlightTags(list("title", ""), "<mark>", "</mark>")
    println opensearch.Collapse("author"), opensearch.TermSuggest("fix", "salm", "title")
    println opensearch.CompletionSuggest("auto", "sal", "title.suggest", 5)

    mut aggs := opensearch.AddAgg("{}", "tags", opensearch.TermsAgg("tag", 10))
    aggs = opensearch.AddAgg(aggs, "avg_price", opensearch.AvgAgg("price"))
    aggs = opensearch.AddAgg(aggs, "total", opensearch.SumAgg("price"))
    aggs = opensearch.AddAgg(aggs, "cheapest", opensearch.MinAgg("price"))
    aggs = opensearch.AddAgg(aggs, "dearest", opensearch.MaxAgg("price"))
    aggs = opensearch.AddAgg(aggs, "priced", opensearch.ValueCountAgg("price"))
    aggs = opensearch.AddAgg(aggs, "authors", opensearch.CardinalityAgg("author"))
    println aggs
    mut pcts := Vector {} as Vector<f64>
    pcts.push(50.0)
    pcts.push(99.0)
    println opensearch.StatsAgg("price"), opensearch.ExtendedStatsAgg("price"), opensearch.PercentilesAgg("ms", pcts)
    println opensearch.HistogramAgg("price", 10.0), opensearch.RangeAgg("price", pcts)
    monthly := opensearch.SubAggs(opensearch.DateHistogramAgg("date", "month"), opensearch.AddAgg("{}", "sales", opensearch.SumAgg("price")))
    println monthly
    println opensearch.FilterAgg(opensearch.Term("tag", "news")), opensearch.NestedAgg("comments"), opensearch.MissingAgg("price")
    println opensearch.TopHitsAgg(3), opensearch.CompositeAgg(list("tag", "author"), 100)
    println opensearch.AddMember(`{"size":0}`, "aggs", aggs)

    mut req := opensearch.SearchRequest { query = opensearch.BoolOf(b), from = 0, size = 20, track_total_hits = "true" }
    req.sort.push(opensearch.SortDesc("date"))
    req.source.push("title")
    req.source_excludes.push("body")
    req.fields.push("date")
    req.docvalue_fields.push("price")
    req.aggs = aggs
    req.highlight = opensearch.Highlight(list("title", ""))
    req.post_filter = opensearch.Term("color", "red")
    req.collapse = opensearch.Collapse("author")
    req.suggest = opensearch.TermSuggest("fix", "salm", "title")
    req.rescore = `{"window_size":50,"query":{"rescore_query":{"match_phrase":{"title":"salam"}}}}`
    req.script_fields = `{"double":{"script":{"source":"doc['price'].value * 2"}}}`
    req.search_after = `[1700000000000]`
    req.track_scores = true
    req.min_score = "0.1"
    req.timeout = "2s"
    req.explain = false
    req.version = true
    req.seq_no_primary_term = true
    req.ext = `{"rag":{"llm_question":"why"}}`
    req.extra.push(`"profile":false`)
    println opensearch.SearchBody(req)
    println opensearch.SearchBody(opensearch.SearchRequest { query = opensearch.MatchAll(), pit_id = "PIT", pit_keep_alive = "1m", no_source = true })
end
Output{"match_all":{}} {"match_none":{}} {"match":{"title":"salam"}} {"match":{"title":{"query":"salam world","operator":"and"}}} {"match":{"title":{"query":"slam","fuzziness":"AUTO"}}} {"match_phrase":{"title":"hello world"}} {"match_phrase":{"title":{"query":"hello world","slop":2}}} {"match_phrase_prefix":{"title":"sal"}} {"match_bool_prefix":{"title":"quick bro"}} {"multi_match":{"query":"salam","fields":["title^2","body"]}} {"multi_match":{"query":"salam","fields":["title","body"],"type":"phrase"}} {"term":{"tag":"news"}} {"term":{"year":1403}} {"term":{"published":true}} {"term":{"tag":{"value":"News","case_insensitive":true}}} {"terms":{"tag":["news","sport"]}} {"terms":{"year":[1402,1403]}} {"terms":{"tag":{"index":"users","id":"7","path":"follows"}}} {"terms_set":{"skills":{"terms":["go","salam"],"minimum_should_match_field":"required"}}} {"range":{"date":{"gte":"2026-01-01","lte":"2026-12-31"}}} {"range":{"price":{"gt":"10","lt":"20"}}} {"range":{"price":{"gte":9.5,"lte":20}}} {"range":{"stock":{"gte":1,"lte":100}}} {"range":{"price":{"lt":"5"}}} {"range":{"at":{"gte":"now-7d/d","lte":"now","time_zone":"+03:30"}}} {"exists":{"field":"email"}} {"prefix":{"sku":"AB-"}} {"wildcard":{"sku":"AB-*-9"}} {"regexp":{"sku":"AB-[0-9]+"}} {"fuzzy":{"name":"maryem"}} {"ids":{"values":["1","2"]}} {"query_string":{"query":"title:salam AND year:1403"}} {"query_string":{"query":"salam world","fields":["title","body"],"default_operator":"AND"}} {"simple_query_string":{"query":"salam -draft","fields":["title"]}} {"bool":{"must":[{"match":{"title":"salam"}}],"filter":[{"term":{"status":"published"}}],"should":[{"term":{"tag":"featured"}}],"must_not":[{"term":{"tag":"spam"}}],"minimum_should_match":"1","boost":1.5}} {"bool":{"must":[{"match":{"t":"x"}}],"filter":[{"term":{"a":"1"}}]}} {"bool":{"must":[{"term":{"a":"1"}},{"term":{"b":"2"}}]}} {"bool":{"should":[{"term":{"a":"1"}},{"term":{"b":"2"}}],"minimum_should_match":"1"}} {"bool":{"must_not":[{"term":{"a":"1"}}]}} {"bool":{"must":[{"match":{"t":"x"}}],"filter":[{"term":{"a":"1"}}]}} {"constant_score":{"filter":{"term":{"tag":"news"}},"boost":1.2}} {"dis_max":{"queries":[{"match":{"title":"x"}},{"match":{"body":"x"}}],"tie_breaker":0.3}} {"boosting":{"positive":{"match":{"t":"apple"}},"negative":{"match":{"t":"pie"}},"negative_boost":0.5}} {"nested":{"path":"comments","query":{"match":{"comments.text":"great"}}}} {"has_child":{"type":"answer","query":{"match_all":{}}}} {"has_parent":{"parent_type":"question","query":{"match_all":{}}}} {"more_like_this":{"fields":["title","body"],"like":"search engines in Salam","min_term_freq":1,"min_doc_freq":1}} {"script":{"script":{"source":"doc['stock'].value > params.min","lang":"painless","params":{"min":5}}}} {"script_score":{"query":{"match_all":{}},"script":{"source":"_score * doc['rank'].value","lang":"painless"}}} {"function_score":{"query":{"match":{"t":"x"}},"functions":[{"field_value_factor":{"field":"likes","factor":1.2,"modifier":"log1p","missing":1}}],"score_mode":"sum","boost_mode":"multiply"}} {"geo_distance":{"distance":"5km","location":{"lat":35.69,"lon":51.39}}} {"geo_bounding_box":{"location":{"top_left":{"lat":36,"lon":51},"bottom_right":{"lat":35.5,"lon":51.8}}}} {"knn":{"embedding":{"vector":[0.12,-0.5,0.9],"k":10}}} [0.12,-0.5,0.9] {"knn":{"embedding":{"vector":[0.12,-0.5,0.9],"k":10,"filter":{"term":{"lang":"fa"}}}}} {"knn":{"embedding":{"vector":[0.12,-0.5,0.9],"max_distance":0.5}}} {"knn":{"embedding":{"vector":[0.12,-0.5,0.9],"min_score":0.8}}} {"neural":{"embedding":{"query_text":"a cosy cafe","model_id":"model-1","k":5}}} {"neural_sparse":{"tokens":{"query_text":"a cosy cafe","model_id":"model-2"}}} {"hybrid":{"queries":[{"match":{"text":"cafe"}},{"neural":{"embedding":{"query_text":"cafe","model_id":"model-1","k":5}}}]}} {"price":{"order":"asc"}} {"date":{"order":"desc"}} "_score" {"_geo_distance":{"location":{"lat":35.69,"lon":51.39},"order":"asc","unit":"km"}} {"fields":{"title":{},"body":{}}} {"pre_tags":["<mark>"],"post_tags":["</mark>"],"fields":{"title":{}}} {"field":"author"} {"fix":{"text":"salm","term":{"field":"title"}}} {"auto":{"prefix":"sal","completion":{"field":"title.suggest","size":5}}} {"tags":{"terms":{"field":"tag","size":10}},"avg_price":{"avg":{"field":"price"}},"total":{"sum":{"field":"price"}},"cheapest":{"min":{"field":"price"}},"dearest":{"max":{"field":"price"}},"priced":{"value_count":{"field":"price"}},"authors":{"cardinality":{"field":"author"}}} {"stats":{"field":"price"}} {"extended_stats":{"field":"price"}} {"percentiles":{"field":"ms","percents":[50,99]}} {"histogram":{"field":"price","interval":10}} {"range":{"field":"price","ranges":[{"to":50},{"from":50,"to":99},{"from":99}]}} {"date_histogram":{"field":"date","calendar_interval":"month"},"aggs":{"sales":{"sum":{"field":"price"}}}} {"filter":{"term":{"tag":"news"}}} {"nested":{"path":"comments"}} {"missing":{"field":"price"}} {"top_hits":{"size":3}} {"composite":{"size":100,"sources":[{"tag":{"terms":{"field":"tag"}}},{"author":{"terms":{"field":"author"}}}]}} {"size":0,"aggs":{"tags":{"terms":{"field":"tag","size":10}},"avg_price":{"avg":{"field":"price"}},"total":{"sum":{"field":"price"}},"cheapest":{"min":{"field":"price"}},"dearest":{"max":{"field":"price"}},"priced":{"value_count":{"field":"price"}},"authors":{"cardinality":{"field":"author"}}}} {"query":{"bool":{"must":[{"match":{"title":"salam"}}],"filter":[{"term":{"status":"published"}}],"should":[{"term":{"tag":"featured"}}],"must_not":[{"term":{"tag":"spam"}}],"minimum_should_match":"1","boost":1.5}},"from":0,"size":20,"sort":[{"date":{"order":"desc"}}],"_source":{"includes":["title"],"excludes":["body"]},"fields":["date"],"docvalue_fields":["price"],"aggs":{"tags":{"terms":{"field":"tag","size":10}},"avg_price":{"avg":{"field":"price"}},"total":{"sum":{"field":"price"}},"cheapest":{"min":{"field":"price"}},"dearest":{"max":{"field":"price"}},"priced":{"value_count":{"field":"price"}},"authors":{"cardinality":{"field":"author"}}},"highlight":{"fields":{"title":{}}},"post_filter":{"term":{"color":"red"}},"collapse":{"field":"author"},"suggest":{"fix":{"text":"salm","term":{"field":"title"}}},"rescore":{"window_size":50,"query":{"rescore_query":{"match_phrase":{"title":"salam"}}}},"script_fields":{"double":{"script":{"source":"doc['price'].value * 2"}}},"search_after":[1700000000000],"track_total_hits":true,"track_scores":true,"min_score":0.1,"timeout":"2s","version":true,"seq_no_primary_term":true,"ext":{"rag":{"llm_question":"why"}},"profile":false} {"query":{"match_all":{}},"_source":false,"pit":{"id":"PIT","keep_alive":"1m"}}

SearchParams

struct SearchParams
Settings sent in the url of a search. Empty strings are left out.
NameTypeDescription
routingstr = ""Search only the shards for this routing value.
preferencestr = ""Which shard copies to prefer, such as _local.
search_pipelinestr = ""A search pipeline to run, such as one for hybrid search.
search_typestr = ""query_then_fetch or dfs_query_then_fetch.
scrollstr = ""Keep a scroll open this long.
request_cachestr = ""true or false: use the request cache.
allow_partial_search_resultsstr = ""false fails the search when a shard fails.
ignore_unavailablebool = falseSkip missing or closed indices.
db-opensearch-Search.salam
import db.opensearch

func main:
    c := opensearch.Connect("http://localhost:9200")
    mut req := opensearch.SearchRequest { query = opensearch.Match("title", "kings"), size = 10 }
    req.sort.push(opensearch.SortDesc("year"))
    req.aggs = opensearch.AddAgg(opensearch.AddAgg("{}", "by_tag", opensearch.TermsAgg("tag", 5)), "avg_year", opensearch.AvgAgg("year"))
    req.aggs = opensearch.AddAgg(req.aggs, "stats", opensearch.StatsAgg("year"))
    req.suggest = opensearch.TermSuggest("fix", "kngs", "title")
    r := opensearch.SearchWith(c, "books", req)
    println r.ok, r.status, r.took, r.timed_out, r.total, r.total_relation, r.max_score, r.error
    each h in r.hits:
        println h.index, h.id, h.score, h.source, h.sort, h.highlight, h.fields, h.inner_hits, h.matched_queries, h.raw.len()
    end
    each bk in opensearch.Buckets(r.aggregations, "by_tag"):
        println bk.key, bk.key_as_string, bk.doc_count, bk.raw.len()
    end
    println opensearch.AggValue(r.aggregations, "avg_year"), opensearch.AggField(r.aggregations, "stats", "max")
    println opensearch.AggRaw(r.aggregations, "stats"), opensearch.Suggestions(r.suggest, "fix")
    println opensearch.Search(c, "books,articles", opensearch.MatchAll()).total
    println opensearch.SearchRaw(c, "books", `{"query":{"match_all":{}},"size":1}`).hits.len()
    p := opensearch.SearchParams {
        routing = "poetry", preference = "_local", search_pipeline = "rerank", search_type = "dfs_query_then_fetch",
        request_cache = "true", allow_partial_search_results = "false", ignore_unavailable = true
    }
    println opensearch.SearchParamsWith(c, "books", `{"size":0}`, p).total, p.scroll.len()
    parsed := opensearch.ParseSearch(r.raw)
    println parsed.hits.len(), parsed.scroll_id, parsed.pit_id

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

    pit := opensearch.CreatePit(c, "books", "2m")
    mut preq := opensearch.SearchRequest { query = opensearch.MatchAll(), size = 100, pit_id = pit, pit_keep_alive = "2m" }
    preq.sort.push(opensearch.SortAsc("year"))
    mut pp := opensearch.SearchWith(c, "", preq)
    until pp.hits.len() > 0:
        preq.search_after = pp.hits.get(pp.hits.len() - 1).sort
        pp = opensearch.SearchWith(c, "", preq)
    end
    println opensearch.ListPits(c), opensearch.DeletePit(c, pit), opensearch.DeleteAllPits(c)

    mut bodies := Vector {} as Vector<str>
    bodies.push(`{"query":{"term":{"tag":"poetry"}},"size":0}`)
    bodies.push(`{"query":{"match_all":{}},"size":0}`)
    each one in opensearch.MSearch(c, "books", bodies):
        println one.ok, one.total
    end
    println opensearch.SearchTemplate(c, "books", "by_tag", `{"tag":"poetry"}`).total
    println opensearch.SearchInlineTemplate(c, "books", `{"query":{"term":{"tag":"{{t}}"}}}`, `{"t":"poetry"}`).total
    println opensearch.RenderTemplate(c, `{"query":{"term":{"tag":"{{t}}"}}}`, `{"t":"poetry"}`)
    println opensearch.Explain(c, "books", "1", opensearch.Match("title", "kings"))
    println opensearch.Validate(c, "books", opensearch.Match("title", "kings"))
    mut fields := Vector {} as Vector<str>
    fields.push("title")
    println opensearch.FieldCaps(c, "books", fields)
    println opensearch.JsonPath(r.raw, "hits.hits.0._source.title"), opensearch.JsonPathRaw(r.raw, "hits.total")
    println opensearch.JsonItems(`[1,"two",{"three":3}]`).len()
end

TaskInfo

struct TaskInfo
A background task.
NameTypeDescription
okbool = falseThe request succeeded and the task did not fail.
idstr = ""The task id, node:number.
completedbool = falseIt has finished.
actionstr = ""What it does, such as indices:data/write/reindex.
descriptionstr = ""A description.
statusstr = ""Its progress as raw JSON.
responsestr = ""Its result as raw JSON, once completed.
errorstr = ""What went wrong.
db-opensearch-ClusterHealth.salam
import db.opensearch

func main:
    c := opensearch.Connect("http://localhost:9200")
    h := opensearch.ClusterHealth(c)
    println h.ok, h.cluster_name, h.status, h.timed_out, h.nodes, h.data_nodes, h.active_primary_shards
    println h.active_shards, h.relocating_shards, h.initializing_shards, h.unassigned_shards, h.pending_tasks, h.active_shards_percent
    println opensearch.WaitForStatus(c, "books", "yellow", "30s").status
    println opensearch.ClusterStats(c).len() > 0, opensearch.ClusterState(c, "metadata").len() > 0
    println opensearch.PutClusterSettings(c, `{"cluster.routing.allocation.enable":"all"}`, "")
    println opensearch.GetClusterSettings(c)
    println opensearch.AllocationExplain(c, `{"index":"books","shard":0,"primary":true}`).len()
    println opensearch.NodesInfo(c, "os").len() > 0, opensearch.NodesStats(c, "jvm").len() > 0, opensearch.HotThreads(c).len() > 0
    each row in opensearch.Cat(c, "shards?h=index,shard,state"):
        println row
    end
    println opensearch.CatText(c, "nodes"), opensearch.Plugins(c), opensearch.HasPlugin(c, "opensearch-knn")

    rx := opensearch.ReindexBody(c, `{"source":{"index":"books"},"dest":{"index":"books_v4"}}`, false)
    t := opensearch.GetTask(c, rx.task)
    println t.ok, t.id, t.completed, t.action, t.description, t.status, t.response, t.error
    println opensearch.WaitTask(c, rx.task, "60s").completed, opensearch.CancelTask(c, rx.task)
    println opensearch.ListTasks(c, "*reindex").len() > 0

    println opensearch.PutRepository(c, "backups", "fs", `{"location":"/mnt/backups"}`), opensearch.VerifyRepository(c, "backups")
    println opensearch.GetRepository(c, "backups"), opensearch.CreateSnapshot(c, "backups", "nightly-1", "books", true)
    println opensearch.Snapshots(c, "backups"), opensearch.GetSnapshot(c, "backups", "nightly-1").len() > 0
    println opensearch.SnapshotStatus(c, "backups", "nightly-1").len() > 0
    println opensearch.RestoreSnapshot(c, "backups", "nightly-1", `{"indices":"books","rename_pattern":"(.+)","rename_replacement":"restored_$1"}`, true)
    println opensearch.DeleteSnapshot(c, "backups", "nightly-1"), opensearch.DeleteRepository(c, "backups")

    mut procs := Vector {} as Vector<str>
    procs.push(opensearch.Processor("lowercase", `{"field":"tag"}`))
    procs.push(opensearch.Processor("set", `{"field":"seen","value":true}`))
    println opensearch.PutPipeline(c, "clean", opensearch.Pipeline("tidy incoming books", procs))
    mut docs := Vector {} as Vector<str>
    docs.push(`{"tag":"POETRY"}`)
    println opensearch.SimulatePipeline(c, "clean", docs), opensearch.GetPipeline(c, "clean").len() > 0
    println opensearch.DeletePipeline(c, "clean")

    println opensearch.PutScript(c, "double", "doc['stock'].value * 2"), opensearch.GetScript(c, "double")
    println opensearch.PutSearchTemplate(c, "by_tag", `{"query":{"term":{"tag":"{{tag}}"}}}`), opensearch.DeleteScript(c, "by_tag"), opensearch.DeleteScript(c, "double")
end

AuthInfo

struct AuthInfo
Who the security plugin says you are.
NameTypeDescription
okbool = falseThe request succeeded.
userstr = ""The user name.
rolesVectorThe security roles.
backend_rolesVectorThe backend roles.
tenantsVectorThe tenants the user may use.
errorstr = ""What went wrong.
db-opensearch-PutPolicy.salam
import db.opensearch

func main:
    c := opensearch.ConnectInsecure("https://localhost:9200", "admin", "S3cret-pass!")
    mut patterns := Vector {} as Vector<str>
    patterns.push("logs-*")
    println opensearch.PutPolicy(c, "logs-30d", opensearch.DeleteAfterPolicy("drop old logs", "30d", patterns))
    println opensearch.GetPolicy(c, "logs-30d").len() > 0
    println opensearch.UpdatePolicy(c, "logs-30d", opensearch.DeleteAfterPolicy("drop old logs", "60d", patterns), 0 as i64, 1 as i64)
    println opensearch.AddPolicy(c, "logs-000001", "logs-30d"), opensearch.PolicyIdOf(c, "logs-000001")
    println opensearch.ChangePolicy(c, "logs-000001", "logs-30d", "hot"), opensearch.RetryPolicy(c, "logs-000001")
    println opensearch.ExplainPolicy(c, "logs-000001"), opensearch.RemovePolicy(c, "logs-000001"), opensearch.DeletePolicy(c, "logs-30d")

    me := opensearch.WhoAmI(c)
    println me.ok, me.user, me.roles, me.backend_roles, me.tenants, me.error
    println opensearch.SecurityHealth(c)
    mut perms := Vector {} as Vector<str>
    perms.push("cluster_monitor")
    mut actions := Vector {} as Vector<str>
    actions.push("read")
    println opensearch.PutRole(c, "logs_reader", opensearch.RoleBody(perms, patterns, actions)), opensearch.GetRole(c, "logs_reader")
    println opensearch.PutUser(c, "maryam", "Strong-Pass-1!", Vector {} as Vector<str>, `{"team":"ops"}`), opensearch.GetUser(c, "maryam")
    mut users := Vector {} as Vector<str>
    users.push("maryam")
    println opensearch.PutRoleMapping(c, "logs_reader", users, Vector {} as Vector<str>), opensearch.GetRoleMapping(c, "logs_reader")
    println opensearch.Users(c), opensearch.ChangePassword(c, "S3cret-pass!", "N3w-secret-pass!")
    println opensearch.DeleteRoleMapping(c, "logs_reader"), opensearch.DeleteUser(c, "maryam"), opensearch.DeleteRole(c, "logs_reader")

    monitor := `{"type":"monitor","name":"errors","enabled":true,"schedule":{"period":{"interval":5,"unit":"MINUTES"}},"inputs":[{"search":{"indices":["logs-*"],"query":{"size":0,"query":{"match":{"level":"error"}}}}}],"triggers":[]}`
    id := opensearch.CreateMonitor(c, monitor)
    println id, opensearch.GetMonitor(c, id).len() > 0, opensearch.UpdateMonitor(c, id, monitor)
    println opensearch.ExecuteMonitor(c, id, true).len() > 0, opensearch.SearchMonitors(c, opensearch.MatchAll()).total
    println opensearch.DeleteMonitor(c, id)
end

KnnMethod

struct KnnMethod
How a knn_vector field is indexed.
NameTypeDescription
namestr = "hnsw"The algorithm, hnsw or ivf.
enginestr = "lucene"lucene, faiss or nmslib.
space_typestr = "l2"The distance: l2, cosinesimil, innerproduct and others, depending on the engine.
mint = 0The HNSW link count; 0 for the default.
ef_constructionint = 0The HNSW build quality; 0 for the default.
db-opensearch-Knn.salam
import db.opensearch

func main:
    c := opensearch.Connect("http://localhost:9200")
    method := opensearch.KnnMethod { name = "hnsw", engine = "lucene", space_type = "cosinesimil", m = 16, ef_construction = 128 }
    mut extra := Vector {} as Vector<str>
    extra.push(opensearch.Property("text", "text"))
    println opensearch.KnnIndexSettings(1, 0), opensearch.KnnVectorField(3, method)
    println opensearch.CreateIndex(c, "places", opensearch.KnnIndexBody("embedding", 3, method, extra))
    opensearch.Index(c, "places", "1", `{"text":"a cafe","embedding":[0.1,0.9,0.2]}`)
    opensearch.Refresh(c, "places")
    mut v := Vector {} as Vector<f64>
    v.push(0.1)
    v.push(0.8)
    v.push(0.3)
    r := opensearch.Search(c, "places", opensearch.Knn("embedding", v, 5))
    println r.total
    println opensearch.KnnWarmup(c, "places"), opensearch.KnnClearCache(c, "places"), opensearch.KnnStats(c).len() > 0
    println opensearch.KnnTrainModel(c, "pq-model", `{"training_index":"train","training_field":"v","dimension":3,"method":{"name":"ivf","engine":"faiss"}}`)
    println opensearch.KnnGetModel(c, "pq-model"), opensearch.KnnDeleteModel(c, "pq-model")

    mut w := Vector {} as Vector<f64>
    w.push(0.3)
    w.push(0.7)
    println opensearch.PutSearchPipeline(c, "hybrid", opensearch.NormalizationPipeline("min_max", "arithmetic_mean", w))
    println opensearch.GetSearchPipeline(c, "hybrid"), opensearch.DeleteSearchPipeline(c, "hybrid")

    task := opensearch.MlRegisterModel(c, `{"name":"huggingface/sentence-transformers/all-MiniLM-L6-v2","version":"1.0.1","model_format":"TORCH_SCRIPT"}`)
    println opensearch.MlGetTask(c, task)
    println opensearch.MlDeployModel(c, "model-1"), opensearch.MlGetModel(c, "model-1").len() > 0
    println opensearch.MlPredict(c, "text_embedding", "model-1", `{"text_docs":["salam"]}`)
    println opensearch.MlUndeployModel(c, "model-1"), opensearch.MlDeleteModel(c, "model-1")
end

ByQueryResult

struct ByQueryResult
The result of a delete by query, update by query or reindex.
NameTypeDescription
okbool = falseIt finished with no failures.
statusint = 0The HTTP status.
tooki64 = 0How long it took, in milliseconds.
timed_outbool = falseIt ran out of time.
totali64 = 0How many documents it looked at.
createdi64 = 0How many it created.
updatedi64 = 0How many it updated.
deletedi64 = 0How many it deleted.
batchesi64 = 0How many scroll batches it took.
version_conflictsi64 = 0How many hit a version conflict.
noopsi64 = 0How many a script left unchanged.
failuresstr = ""The failures as raw JSON; empty when there were none.
taskstr = ""The task id, when it runs in the background.
errorstr = ""What went wrong.
db-opensearch-Index.salam
import db.opensearch

func main:
    c := opensearch.Connect("http://localhost:9200")
    w := opensearch.Index(c, "books", "1", `{"title":"The Book of Kings","year":1010,"stock":3}`)
    println w.ok, w.status, w.index, w.id, w.result, w.version, w.seq_no, w.primary_term
    println w.shards_total, w.shards_successful, w.error
    auto := opensearch.IndexWith(c, "books", "", `{"title":"Masnavi"}`, opensearch.Options { refresh = opensearch.REFRESH_WAIT_FOR, routing = "poetry" })
    println auto.id
    dup := opensearch.Create(c, "books", "1", `{"title":"again"}`)
    println dup.ok, dup.status
    piped := opensearch.CreateWith(c, "books", "2", `{"title":"Golestan"}`, opensearch.Options { pipeline = "clean", timeout = "5s", wait_for_active_shards = "1" })
    println piped.result

    d := opensearch.Get(c, "books", "1")
    println d.found, d.index, d.id, d.version, d.seq_no, d.primary_term, d.routing, d.source, d.fields, d.error
    mut only := Vector {} as Vector<str>
    only.push("title")
    println opensearch.GetFields(c, "books", "1", only, "").source
    println opensearch.GetSource(c, "books", "1"), opensearch.Exists(c, "books", "1")

    println opensearch.Update(c, "books", "1", `{"stock":2}`).result
    cas := opensearch.UpdateWith(c, "books", "1", `{"doc":{"stock":1}}`, opensearch.Options { if_seq_no = d.seq_no, if_primary_term = d.primary_term, retry_on_conflict = -1 })
    println cas.ok, opensearch.ErrorType(c)
    println opensearch.Upsert(c, "books", "9", `{"title":"Shahnameh","stock":1}`).result
    println opensearch.UpdateScript(c, "books", "1", opensearch.Script("ctx._source.stock += params.n", `{"n":5}`), `{"stock":5}`).result
    println opensearch.DeleteWith(c, "books", "9", opensearch.Options { refresh = opensearch.REFRESH_TRUE, version = 3, version_type = "external" }).result
    println opensearch.Delete(c, "books", "2").result

    mut ids := Vector {} as Vector<str>
    ids.push("1")
    ids.push("404")
    each doc in opensearch.MGet(c, "books", ids):
        println doc.id, doc.found
    end
    println opensearch.Count(c, "books", ""), opensearch.Count(c, "books", opensearch.Range("year", "1000", ""))

    mut b := opensearch.NewBulk()
    opensearch.BulkIndex(b, "books", "10", `{"title":"Divan"}`)
    opensearch.BulkIndexRouted(b, "books", "11", "poetry", `{"title":"Rubaiyat"}`)
    opensearch.BulkCreate(b, "books", "", `{"title":"Bustan"}`)
    opensearch.BulkUpdate(b, "books", "10", `{"stock":4}`)
    opensearch.BulkUpsert(b, "books", "12", `{"title":"Kalila"}`)
    opensearch.BulkDelete(b, "books", "3")
    println opensearch.BulkLen(b), b.count, b.lines.len()
    print opensearch.BulkBody(b)
    br := opensearch.BulkSendWith(c, b, opensearch.REFRESH_FALSE)
    println br.ok, br.status, br.took, br.errors, br.succeeded, br.failed, br.error
    each it in br.items:
        println it.action, it.index, it.id, it.status, it.ok, it.result, it.version, it.error_type, it.error_reason
    end
    opensearch.BulkReset(b)
    opensearch.BulkIndex(b, "books", "13", `{"title":"Makhzan"}`)
    println opensearch.BulkSend(c, b).ok
    opensearch.BulkFree(b)
    println opensearch.ParseBulk(`{"took":1,"errors":false,"items":[]}`).ok

    ub := opensearch.UpdateByQuery(c, "books", opensearch.Term("stock", "0"), opensearch.Script("ctx._source.out = true", ""))
    println ub.ok, ub.status, ub.took, ub.timed_out, ub.total, ub.updated, ub.batches, ub.version_conflicts, ub.noops, ub.failures
    ub2 := opensearch.UpdateByQueryWith(c, "books", "", "", opensearch.Options { conflicts = "proceed", pipeline = "clean" })
    println ub2.updated
    dq := opensearch.DeleteByQuery(c, "books", opensearch.Term("out", "true"))
    println dq.deleted, opensearch.DeleteByQueryWith(c, "books", opensearch.MatchAll(), opensearch.Options { refresh = "true", conflicts = "proceed" }).deleted
    rx := opensearch.Reindex(c, "books", "books_v2")
    println rx.created, rx.error
    task := opensearch.ReindexBody(c, `{"source":{"index":"books"},"dest":{"index":"books_v3"}}`, false)
    println task.task
end

Config

struct Config
Everything NewClient needs.
NameTypeDescription
nodesVectorNode urls; each entry may hold several separated by commas, and a url may carry user:password@ and a path prefix.
usernamestr = ""The user for basic authentication.
passwordstr = ""The password for basic authentication.
bearerstr = ""A bearer token, sent instead of basic authentication.
ca_filestr = ""A PEM file of the certificate authorities to trust for https.
insecurebool = falseSkip certificate checks; only for a test server with a self signed certificate.
timeout_msint = 30000How long one request may take, in milliseconds; 0 for no limit.
max_retriesint = 3How many more times a request is tried on another node after a failed connection or a 502, 503 or 504.
headersHashMapExtra headers sent with every request.
aws_regionstr = ""Sign every request with AWS SigV4 for this region; empty for no signing.
aws_servicestr = ""The AWS service to sign for, SERVICE_ES (the default) or SERVICE_AOSS.
aws_access_keystr = ""The AWS access key id.
aws_secret_keystr = ""The AWS secret access key.
aws_session_tokenstr = ""The AWS session token for temporary credentials; empty if none.
db-opensearch-Client.salam
import db.opensearch

func main:
    mut cfg := opensearch.DefaultConfig()
    cfg.nodes.push("https://node2.example.com:9200, https://node3.example.com:9200")
    cfg.username = "admin"
    cfg.password = "S3cret-pass!"
    cfg.ca_file = "/etc/ssl/certs/opensearch-ca.pem"
    cfg.timeout_ms = 10000
    cfg.max_retries = 2
    cfg.headers.put("X-Opaque-Id", "shop-api")
    mut c := opensearch.NewClient(cfg)
    if not opensearch.Ok(c):
        println opensearch.Error(c)
        ret 1
    end
    println opensearch.Nodes(c), opensearch.AuthHeader(c).len() > 0, opensearch.VERSION
    println opensearch.Ping(c)

    info := opensearch.GetInfo(c)
    println info.ok, info.name, info.cluster_name, info.cluster_uuid, info.version, info.distribution
    println info.build_type, info.lucene_version, info.minimum_wire_compatibility_version, info.tagline

    r := opensearch.Perform(c, "GET", "/_cat/health?format=json", "")
    println r.ok, r.status, r.body
    if not r.ok:
        println r.error, r.error_type, r.error_reason
    end
    nd := opensearch.PerformNdjson(c, "POST", "/_bulk", "{\"delete\":{\"_index\":\"shop\",\"_id\":\"1\"}}\n")
    println nd.status, opensearch.Status(c), opensearch.ErrorType(c), opensearch.ErrorReason(c)
    txt := opensearch.PerformText(c, "POST", "/_plugins/_sql?format=csv", `{"query":"SELECT 1"}`, "application/json")
    println txt.body
    opensearch.Close(c)

    mut local := opensearch.Connect(opensearch.DEFAULT_URL)
    println opensearch.Ok(local), opensearch.DEFAULT_PORT, opensearch.DEAD_NODE_MS
    opensearch.Close(local)
    mut demo := opensearch.ConnectInsecure("https://localhost:9200", "admin", "S3cret-pass!")
    opensearch.Close(demo)
    mut auth := opensearch.ConnectAuth("https://search.example.com", "reader", "pass")
    println opensearch.EncodeBasic("reader", "pass")
    opensearch.Close(auth)

    mut aws := opensearch.ConnectAWS(
        "https://search-shop.eu-west-1.es.amazonaws.com", "eu-west-1", opensearch.SERVICE_ES,
        "AKIAEXAMPLE", "secret-key", ""
    )
    opensearch.SetSigningTime(aws, 1700000000 as i64)
    println opensearch.ClusterHealth(aws).status
    opensearch.Close(aws)
    mut serverless := opensearch.ConnectAWS(
        "https://abc123.eu-west-1.aoss.amazonaws.com", "eu-west-1", opensearch.SERVICE_AOSS,
        "AKIAEXAMPLE", "secret-key", "session-token"
    )
    opensearch.Close(serverless)
    ret 0
end

Client

struct Client
A connection to an OpenSearch cluster; free it with Close.
NameTypeDescription
handlevoid*The internal state.

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

Response

struct Response
The raw answer to one request.
NameTypeDescription
statusint = 0The HTTP status; 0 when no answer came.
okbool = falseThe status was 2xx.
bodystr = ""The response body.
errorstr = ""What went wrong, with the server's error type and reason when it sent them.
error_typestr = ""The server's error type, such as index_not_found_exception.
error_reasonstr = ""The server's error reason.

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

Options

struct Options
Optional settings for writes. Empty strings and negative numbers are left out.
NameTypeDescription
refreshstr = ""One of the REFRESH_ values.
routingstr = ""The routing value, to place a document on a chosen shard.
pipelinestr = ""An ingest pipeline to run the document through.
timeoutstr = ""How long to wait for shards, such as 5s.
wait_for_active_shardsstr = ""How many shard copies must be active, or all.
conflictsstr = ""For by query calls: proceed keeps going past version conflicts.
if_seq_noi64 = -1Write only if the document still has this sequence number.
if_primary_termi64 = -1Write only if the document still has this primary term.
retry_on_conflictint = -1For updates: how many times to retry on a version conflict.
versioni64 = -1An explicit document version.
version_typestr = ""The version type, such as external.
require_aliasbool = falseThe target must be an alias.

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

WriteResult

struct WriteResult
The result of a write to one document.
NameTypeDescription
okbool = falseThe write succeeded.
statusint = 0The HTTP status.
indexstr = ""The index written to.
idstr = ""The document id; generated when you passed none.
resultstr = ""created, updated, deleted, noop or not_found.
versioni64 = 0The new document version.
seq_noi64 = -1The new sequence number.
primary_termi64 = 0The primary term.
shards_totalint = 0How many shard copies should hold the write.
shards_successfulint = 0How many did.
errorstr = ""What went wrong.

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

Document

struct Document
One document read by id.
NameTypeDescription
foundbool = falseThe document exists.
indexstr = ""Its index.
idstr = ""Its id.
versioni64 = 0Its version.
seq_noi64 = -1Its sequence number, for a later conditional write.
primary_termi64 = 0Its primary term, for a later conditional write.
routingstr = ""Its routing value, if it has one.
sourcestr = ""The document as raw JSON.
fieldsstr = ""Stored fields as raw JSON, when asked for.
errorstr = ""What went wrong; empty when the document simply does not exist.

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

Hit

struct Hit
One search hit.
NameTypeDescription
indexstr = ""The index it came from.
idstr = ""The document id.
scoref64 = 0Its relevance score.
sourcestr = ""The document as raw JSON.
sortstr = ""Its sort values as raw JSON; pass the last hit's to search_after for the next page.
highlightstr = ""The highlighted fragments as raw JSON.
fieldsstr = ""The requested fields as raw JSON.
inner_hitsstr = ""Inner hits of a nested or collapsed query, as raw JSON.
matched_queriesstr = ""Which named queries matched, as raw JSON.
rawstr = ""The whole hit as raw JSON.

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

SearchResult

struct SearchResult
The result of a search.
NameTypeDescription
okbool = falseThe search succeeded.
statusint = 0The HTTP status.
tooki64 = 0How long it took on the server, in milliseconds.
timed_outbool = falseThe server stopped early because of a timeout.
totali64 = 0How many documents matched.
total_relationstr = ""eq when total is exact, gte when it is a lower bound.
max_scoref64 = 0The best score.
hitsVectorThe hits of this page.
aggregationsstr = ""The aggregations as raw JSON; read them with Buckets and AggValue.
suggeststr = ""The suggestions as raw JSON; read them with Suggestions.
scroll_idstr = ""The id for the next Scroll call.
pit_idstr = ""The point in time id the server sent back.
rawstr = ""The whole response.
errorstr = ""What went wrong.

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

SearchRequest

struct SearchRequest
A search. Empty strings, empty lists and negative numbers are left out of the request body.
NameTypeDescription
querystr = ""The query, made with the builders or written as JSON.
fromint = -1How many hits to skip.
sizeint = -1How many hits to return.
sortVectorSort clauses, such as SortDesc("date").
sourceVectorReturn only these source fields.
source_excludesVectorLeave these source fields out.
no_sourcebool = falseReturn no source at all.
fieldsVectorFields to return in Hit.fields.
docvalue_fieldsVectorDoc value fields to return.
aggsstr = ""The aggregations, built with AddAgg.
highlightstr = ""The highlight settings, from Highlight.
post_filterstr = ""A filter applied after the aggregations are counted.
collapsestr = ""Collapse hits on a field, from Collapse.
suggeststr = ""Suggesters, from TermSuggest or CompletionSuggest.
rescorestr = ""A rescore clause as JSON.
script_fieldsstr = ""Script fields as JSON.
search_afterstr = ""The sort values of the last hit, as a JSON array, to fetch the next page.
pit_idstr = ""A point in time id from CreatePit; the search then goes to /_search and the index is not named.
pit_keep_alivestr = ""How much longer to keep the point in time, such as 1m.
track_total_hitsstr = ""true, false or a number: how far to count matches exactly.
track_scoresbool = falseCompute scores even when sorting by a field.
min_scorestr = ""Leave out hits below this score.
timeoutstr = ""Stop searching after this long, such as 2s.
explainbool = falseExplain how each score was computed.
versionbool = falseReturn each hit's version.
seq_no_primary_termbool = falseReturn each hit's sequence number and primary term.
extstr = ""Plugin extensions as JSON, such as retrieval augmented generation settings.
extraVectorMore members written as "key":value, added as they are.

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

Bucket

struct Bucket
One bucket of a bucket aggregation.
NameTypeDescription
keystr = ""Its key as text.
key_as_stringstr = ""The formatted key, for dates and numbers with a format.
doc_counti64 = 0How many documents fell in it.
rawstr = ""The bucket as raw JSON, with any sub aggregations.

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

Bulk

struct Bulk
A batch of index, create, update and delete actions sent in one request.
NameTypeDescription
linesVectorThe NDJSON lines so far.
countint = 0How many actions it holds.

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

BulkItem

struct BulkItem
The result of one bulk action.
NameTypeDescription
actionstr = ""index, create, update or delete.
indexstr = ""The index.
idstr = ""The document id.
statusint = 0The HTTP status of this action.
okbool = falseIt succeeded; deleting a document that is not there counts as success, as it does for OpenSearch.
resultstr = ""The result, such as created.
versioni64 = 0The new document version.
error_typestr = ""The error type when it failed.
error_reasonstr = ""The error reason when it failed.

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

BulkResult

struct BulkResult
The result of a bulk request.
NameTypeDescription
okbool = falseEvery action succeeded.
statusint = 0The HTTP status of the request.
tooki64 = 0How long it took, in milliseconds.
errorsbool = falseThe server reported at least one failed action.
succeededint = 0How many actions succeeded.
failedint = 0How many failed.
itemsVectorOne result per action, in order.
errorstr = ""A summary of what went wrong.

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

Info

struct Info
What a cluster says about itself.
NameTypeDescription
okbool = falseThe request succeeded.
namestr = ""The node name.
cluster_namestr = ""The cluster name.
cluster_uuidstr = ""The cluster id.
versionstr = ""The OpenSearch version, such as 2.17.1.
distributionstr = ""opensearch.
build_typestr = ""How it was packaged, such as tar or rpm.
lucene_versionstr = ""The Lucene version.
minimum_wire_compatibility_versionstr = ""The oldest version it can talk to.
taglinestr = ""The tagline.

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

Health

struct Health
The health of a cluster or an index.
NameTypeDescription
okbool = falseThe request succeeded.
cluster_namestr = ""The cluster name.
statusstr = ""green, yellow or red.
timed_outbool = falseA wait for status ran out of time.
nodesint = 0The number of nodes.
data_nodesint = 0The number of data nodes.
active_primary_shardsint = 0Active primary shards.
active_shardsint = 0All active shards.
relocating_shardsint = 0Shards moving between nodes.
initializing_shardsint = 0Shards starting up.
unassigned_shardsint = 0Shards with no node.
pending_tasksint = 0Cluster tasks waiting.
active_shards_percentf64 = 0The share of active shards, from 0 to 100.

The example for this item is shown with the ones above: db-opensearch-ClusterHealth.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 id.
primariesint = 0The number of primary shards.
replicasint = 0The number of replicas.
docs_counti64 = 0The number of documents.
docs_deletedi64 = 0Deleted documents not merged away yet.
store_sizestr = ""The size on disk, in bytes.
db-opensearch-CreateIndex.salam
import db.opensearch

func main:
    c := opensearch.Connect("http://localhost:9200")
    mut props := Vector {} as Vector<str>
    props.push(opensearch.Property("title", "text"))
    props.push(opensearch.PropertyWith("title_fa", "text", `{"analyzer":"persian"}`))
    props.push(opensearch.Property("tag", "keyword"))
    props.push(opensearch.Property("year", "integer"))
    println opensearch.CreateIndexWith(c, "books", 1, 0, opensearch.Properties(props))
    println opensearch.CreateIndex(c, "logs-000001", `{"aliases":{"logs":{"is_write_index":true}}}`)
    println opensearch.IndexExists(c, "books"), opensearch.GetIndex(c, "books").len() > 0
    println opensearch.PutMapping(c, "books", "{" + opensearch.Property("isbn", "keyword") + "}")
    println opensearch.PutMappingBody(c, "books", `{"dynamic":"strict"}`), opensearch.GetMapping(c, "books")
    println opensearch.PutSettings(c, "books", `{"index":{"refresh_interval":"5s"}}`)
    println opensearch.GetSettings(c, "books").len() > 0, opensearch.GetSetting(c, "books", "index.refresh_interval")
    println opensearch.Refresh(c, "books"), opensearch.Flush(c, "books"), opensearch.ForceMerge(c, "books", 1), opensearch.ClearCache(c, "books")
    println opensearch.CloseIndex(c, "books"), opensearch.OpenIndex(c, "books")
    println opensearch.PutSettings(c, "books", `{"index.blocks.write":true}`)
    println opensearch.CloneIndex(c, "books", "books_clone", ""), opensearch.ShrinkIndex(c, "books", "books_small", ""), opensearch.SplitIndex(c, "books", "books_big", `{"settings":{"index.number_of_shards":2}}`)
    println opensearch.IndexStats(c, "books").len() > 0

    println opensearch.PutAlias(c, "books", "library"), opensearch.AliasExists(c, "library"), opensearch.AliasIndices(c, "library")
    println opensearch.PutAliasFiltered(c, "books", "poetry", opensearch.Term("tag", "poetry"), false)
    println opensearch.GetAliases(c, "books"), opensearch.DeleteAlias(c, "books", "poetry")
    mut acts := Vector {} as Vector<str>
    acts.push(opensearch.AliasAction("add", "books_clone", "library"))
    acts.push(opensearch.AliasAction("remove", "books", "library"))
    println opensearch.UpdateAliases(c, acts), opensearch.SwapAlias(c, "library", "books_clone", "books")

    mut patterns := Vector {} as Vector<str>
    patterns.push("logs-*")
    tpl := opensearch.IndexTemplate(patterns, `{"number_of_replicas":0}`, "{" + opensearch.Property("msg", "text") + "}", 10)
    println opensearch.PutIndexTemplate(c, "logs", tpl), opensearch.IndexTemplateExists(c, "logs"), opensearch.GetIndexTemplate(c, "logs").len() > 0
    println opensearch.PutComponentTemplate(c, "base", `{"template":{"settings":{"number_of_shards":1}}}`), opensearch.GetComponentTemplate(c, "base").len() > 0
    println opensearch.Rollover(c, "logs", `{"max_docs":1000000,"max_age":"7d"}`)
    println opensearch.PutIndexTemplate(c, "events", `{"index_patterns":["events-*"],"data_stream":{}}`)
    println opensearch.CreateDataStream(c, "events-web"), opensearch.DataStreams(c), opensearch.DeleteDataStream(c, "events-web")
    println opensearch.Analyze(c, "", "standard", "Salam to OpenSearch")
    each ix in opensearch.CatIndices(c, "books*"):
        println ix.health, ix.status, ix.index, ix.uuid, ix.primaries, ix.replicas, ix.docs_count, ix.docs_deleted, ix.store_size
    end
    println opensearch.DeleteIndexTemplate(c, "logs"), opensearch.DeleteIndexTemplate(c, "events"), opensearch.DeleteComponentTemplate(c, "base")
    println opensearch.DeleteIndex(c, "books_clone,books_small,books_big"), opensearch.DeleteIndexIfExists(c, "never-made")
end

SqlRows

struct SqlRows
The rows of a SQL or PPL query; it fetches more pages as you go and implements db.Rows.
NameTypeDescription
handlevoid*The internal state.
db-opensearch-Sql.salam
import db
import db.opensearch

func main:
    c := opensearch.Connect("http://localhost:9200")
    conn := opensearch.Conn(c)
    println conn.Kind(), conn.Ok(), conn.Ping(), db.QueryInt(conn, "SELECT COUNT(*) FROM books")
    rows := conn.Query("SELECT title, year, price FROM books WHERE year > 1000 ORDER BY year")
    println rows.Ok(), rows.ColumnCount(), rows.ColumnName(0), rows.ColumnType(1)
    until rows.Next():
        println rows.Text(0), rows.Int(1), rows.Int64(1), rows.Float(2), rows.IsNull(2)
    end
    rows.Close()
    println conn.Exec("DELETE FROM books WHERE year < 0"), conn.Changes(), conn.LastInsertId(), conn.Error(), conn.Quote("it's")
    tx := conn.Begin()
    println tx.Ok(), tx.Exec("SELECT 1"), tx.Query("SELECT 1").Ok(), tx.Commit(), tx.Rollback()

    mut params := Vector {} as Vector<str>
    params.push(opensearch.SqlParam("integer", "1000"))
    mut paged := opensearch.SqlWith(c, "SELECT title FROM books WHERE year > ?", params, 100)
    println paged.Total(), paged.ColumnTypeName(0), paged.Error()
    until paged.Next():
        println paged.Raw(0)
    end
    paged.Close()
    rs := opensearch.Sql(c, "SHOW TABLES LIKE books%")
    rs.Close()
    println opensearch.SqlFormat(c, "SELECT title FROM books", "csv")
    println opensearch.SqlExplain(c, "SELECT title FROM books").len() > 0

    p := opensearch.Ppl(c, "source=books | where year > 1000 | stats count() by tag")
    until p.Next():
        println p.Int(0), p.Text(1)
    end
    p.Close()
    println opensearch.PplFormat(c, "source=books | fields title", "raw"), opensearch.PplExplain(c, "source=books").len() > 0
    d := opensearch.Database { handle = c.handle }
    t := opensearch.Txn {}
    println d.Kind(), t.Ok(), conn.Close()
end

Ok

func Ok(): bool
The query succeeded.

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

Error

func Error(): str
What went wrong.

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

Total

func Total(): i64
The row count the server reported with the last page.

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

Next

func Next(): bool
Moves to the next row, fetching the next page when needed; false at the end.

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

ColumnCount

func ColumnCount(): int
The number of columns.

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

ColumnName

func ColumnName(col: int): str
The name of a column, or its alias.

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

ColumnTypeName

func ColumnTypeName(col: int): str
The OpenSearch type of a column, such as keyword or long.

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

ColumnType

func ColumnType(col: int): int
The type of a column in the current row, one of the TYPE_ constants of db.

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

IsNull

func IsNull(col: int): bool
The value is null.

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

Text

func Text(col: int): str
The value as text.

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

Raw

func Raw(col: int): str
The value as raw JSON.

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

Int

func Int(col: int): int
The value as an integer.

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

Int64

func Int64(col: int): i64
The value as a 64 bit integer.

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

Float

func Float(col: int): f64
The value as a float.

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

Close

func Close(): int
Frees the rows and closes the server cursor if pages are left.

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

Database

struct Database
A client as a db.Connection, from Conn.
NameTypeDescription
handlevoid*The client state.

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

Kind

func Kind(): str
db.OPENSEARCH.

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

Ok

func Ok(): bool
The client is valid.

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

Ping

func Ping(): bool
The cluster answers.

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

Exec

func Exec(sql: str): int
Runs a SQL DELETE and returns how many documents it deleted, if the cluster allows SQL deletes; anything else is -1, since OpenSearch SQL is otherwise read only.

The example for this item is shown with the ones above: db-opensearch-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-opensearch-Sql.salam

Begin

func Begin(): dyn db.Tx
OpenSearch has no transactions; the result is never ok.

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

LastInsertId

func LastInsertId(): i64
Always 0; use the id from Index.

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

Changes

func Changes(): i64
How many documents the last Exec deleted.

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

Error

func Error(): str
The last error.

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

Quote

func Quote(s: str): str
A text value quoted for SQL.

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

Close

func Close(): int
Frees the client.

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

Txn

struct Txn
The transaction Begin returns; every call fails.
NameTypeDescription
handlevoid*Unused.

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

Ok

func Ok(): bool
Always false.

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

Exec

func Exec(_sql: str): int
Always -1.

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

Query

func Query(_sql: str): dyn db.Rows
Rows that are never ok.

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

Commit

func Commit(): int
Always -1.

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

Rollback

func Rollback(): int
Always -1.

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

Constants and variables

VERSION

const VERSION: str = "1.0.0"
The version of this client.

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

DEFAULT_URL

const DEFAULT_URL: str = "http://localhost:9200"
The address used when no node is given: http://localhost:9200.

The example for this item is shown with the ones above: db-opensearch-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-opensearch-Client.salam

DEAD_NODE_MS

const DEAD_NODE_MS: i32 = 60000
How long a node that refused a connection is skipped, in milliseconds.

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

REFRESH_TRUE

const REFRESH_TRUE: str = "true"
Refresh at once, so the change is searchable when the call returns.

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

REFRESH_WAIT_FOR

const REFRESH_WAIT_FOR: str = "wait_for"
Wait for the next scheduled refresh before returning.

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

REFRESH_FALSE

const REFRESH_FALSE: str = "false"
Do not refresh; the default.

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

SERVICE_ES

const SERVICE_ES: str = "es"
The AWS signing service name for an Amazon OpenSearch Service domain.

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

SERVICE_AOSS

const SERVICE_AOSS: str = "aoss"
The AWS signing service name for an OpenSearch Serverless collection.

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

Functions

NewBulk

func NewBulk(): Bulk
An empty bulk batch.

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

BulkIndex

func BulkIndex(b &: Bulk, index: str, id: str, doc: str)
Adds an index action; an empty id lets the server make one.

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

BulkIndexRouted

func BulkIndexRouted(b &: Bulk, index: str, id: str, routing: str, doc: str)
Adds an index action with a routing value.

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

BulkCreate

func BulkCreate(b &: Bulk, index: str, id: str, doc: str)
Adds a create action, which fails if the id exists.

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

BulkUpdate

func BulkUpdate(b &: Bulk, index: str, id: str, partial: str)
Adds an update that merges the given fields.

The example for this item is shown with the ones above: db-opensearch-Index.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-opensearch-Index.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-opensearch-Index.salam

BulkLen

func BulkLen(b: Bulk): int
How many actions the batch holds.

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

BulkBody

func BulkBody(b: Bulk): str
The NDJSON body the batch sends.

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

BulkReset

func BulkReset(b &: Bulk)
Empties the batch so it can be filled again.

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

BulkFree

func BulkFree(b &: Bulk)
Frees the batch.

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

ParseBulk

func ParseBulk(body: str): BulkResult
Reads a bulk response.

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

BulkSend

func BulkSend(c: Client, b: Bulk): BulkResult
Sends the batch.

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

BulkSendWith

func BulkSendWith(c: Client, b: Bulk, refresh: str): BulkResult
Sends the batch with a refresh setting.

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

MatchAll

func MatchAll(): str
Matches every document.

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

MatchNone

func MatchNone(): str
Matches nothing.

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

Match

func Match(field: str, text: str): str
Full text match on a field.

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

MatchAnd

func MatchAnd(field: str, text: str): str
Full text match where every word must be present.

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

MatchFuzzy

func MatchFuzzy(field: str, text: str): str
Full text match that forgives typing mistakes.

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

MatchPhrase

func MatchPhrase(field: str, text: str): str
The words in this order.

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

MatchPhraseSlop

func MatchPhraseSlop(field: str, text: str, slop: int): str
The words in this order, with up to slop words between.

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

MatchPhrasePrefix

func MatchPhrasePrefix(field: str, text: str): str
A phrase whose last word may be a prefix; for search as you type.

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

MatchBoolPrefix

func MatchBoolPrefix(field: str, text: str): str
Every word, the last as a prefix, in any order.

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

MultiMatch

func MultiMatch(text: str, fields: Vector<str>): str
Full text match on several fields; title^2 weighs a field.

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

MultiMatchType

func MultiMatchType(text: str, fields: Vector<str>, kind: str): str
MultiMatch of a type such as best_fields, most_fields, phrase or cross_fields.

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

Term

func Term(field: str, value: str): str
An exact value, for keyword fields.

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

TermInt

func TermInt(field: str, value: i64): str
An exact number.

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

TermBool

func TermBool(field: str, value: bool): str
An exact boolean.

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

TermCaseInsensitive

func TermCaseInsensitive(field: str, value: str): str
An exact value ignoring letter case.

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

Terms

func Terms(field: str, values: Vector<str>): str
Any of these exact values.

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

TermsInt

func TermsInt(field: str, values: Vector<i64>): str
Any of these numbers.

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

TermsLookup

func TermsLookup(field: str, index: str, id: str, path: str): str
Any of the values stored at a path of another document.

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

TermsSet

func TermsSet(field: str, values: Vector<str>, minimum_field: str): str
At least as many of these values as another field says.

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

Range

func Range(field: str, low: str, high: str): str
A range given as text, inclusive; leave one end empty for an open range.

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

RangeExclusive

func RangeExclusive(field: str, low: str, high: str): str
A range given as text, exclusive.

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

RangeNum

func RangeNum(field: str, low: f64, high: f64): str
A range of floats, inclusive.

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

RangeInt

func RangeInt(field: str, low: i64, high: i64): str
A range of integers, inclusive.

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

RangeOp

func RangeOp(field: str, op: str, value: str): str
One bound with an operator: gt, gte, lt or lte.

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

DateRange

func DateRange(field: str, low: str, high: str, format: str, time_zone: str): str
A date range with an optional format and time zone; date math such as now-7d/d works.

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

FieldExists

func FieldExists(field: str): str
The field has a value.

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

Prefix

func Prefix(field: str, value: str): str
The value starts with this.

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

Wildcard

func Wildcard(field: str, pattern: str): str
A pattern with * and ?.

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

Regexp

func Regexp(field: str, pattern: str): str
A regular expression on the whole value.

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

Fuzzy

func Fuzzy(field: str, value: str): str
A value close to this one.

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

Ids

func Ids(ids: Vector<str>): str
Documents with these ids.

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

QueryString

func QueryString(query: str): str
A Lucene query string, such as title:salam AND year:1403.

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

QueryStringFields

func QueryStringFields(query: str, fields: Vector<str>, default_operator: str): str
A query string over given fields with a default operator.

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

SimpleQueryString

func SimpleQueryString(query: str, fields: Vector<str>): str
A forgiving query string that never fails to parse.

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

BoolOf

func BoolOf(q: BoolQuery): str
A bool query from a BoolQuery.

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

Bool

func Bool(must: Vector<str>, filter: Vector<str>, should: Vector<str>, must_not: Vector<str>): str
A bool query from the four clause lists.

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

And

func And(clauses: Vector<str>): str
Every clause must match.

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

Or

func Or(clauses: Vector<str>): str
At least one clause must match.

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

Not

func Not(clause: str): str
The clause must not match.

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

Filtered

func Filtered(query: str, filters: Vector<str>): str
A query plus filters that do not score.

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

ConstantScore

func ConstantScore(filter: str, boost: f64): str
A filter where every match gets the same score.

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

DisMax

func DisMax(queries: Vector<str>, tie_breaker: f64): str
The best scoring of several queries, plus a share of the others.

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

Boosting

func Boosting(positive: str, negative: str, negative_boost: f64): str
Lowers the score of matches of a negative query instead of dropping them.

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

Nested

func Nested(path: str, query: str): str
A query on nested objects.

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

HasChild

func HasChild(child_type: str, query: str): str
Parents with a matching child, for join fields.

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

HasParent

func HasParent(parent_type: str, query: str): str
Children with a matching parent, for join fields.

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

MoreLikeThis

func MoreLikeThis(fields: Vector<str>, like: str): str
Documents like the given text.

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

ScriptQuery

func ScriptQuery(source: str, params: str): str
Documents for which a script is true.

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

Script

func Script(source: str, params: str): str
A painless script with optional parameters as JSON.

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

ScriptScore

func ScriptScore(query: str, source: str, params: str): str
Scores the matches of a query with a script.

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

FunctionScore

func FunctionScore(query: str, functions: Vector<str>, score_mode: str, boost_mode: str): str
Changes the scores of a query with functions such as FieldValueFactor.

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

FieldValueFactor

func FieldValueFactor(field: str, factor: f64, modifier: str): str
A score function from a numeric field.

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

GeoDistance

func GeoDistance(field: str, lat: f64, lon: f64, distance: str): str
Points within a distance, such as 5km, of a place.

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

GeoBoundingBox

func GeoBoundingBox(field: str, top: f64, left: f64, bottom: f64, right: f64): str
Points within a box given by its top, left, bottom and right.

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

Knn

func Knn(field: str, vector: Vector<f64>, k: int): str
The k nearest neighbours of a vector, for a knn_vector field.

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

KnnFiltered

func KnnFiltered(field: str, vector: Vector<f64>, k: int, filter: str): str
The k nearest neighbours among the documents that match a filter.

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

KnnRadial

func KnnRadial(field: str, vector: Vector<f64>, max_distance: f64): str
Every neighbour within a distance.

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

KnnMinScore

func KnnMinScore(field: str, vector: Vector<f64>, min_score: f64): str
Every neighbour with at least this score.

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

Neural

func Neural(field: str, query_text: str, model_id: str, k: int): str
Semantic search: the server turns the text into a vector with a model; needs the neural search plugin.

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

NeuralSparse

func NeuralSparse(field: str, query_text: str, model_id: str): str
Sparse neural search with a model.

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

Hybrid

func Hybrid(queries: Vector<str>): str
Combines several queries, usually a text match and a neural one; run it with a normalization search pipeline.

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

SortAsc

func SortAsc(field: str): str
Sort ascending by a field.

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

SortDesc

func SortDesc(field: str): str
Sort descending by a field.

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

SortScore

func SortScore(): str
Sort by score.

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

SortGeo

func SortGeo(field: str, lat: f64, lon: f64, unit: str): str
Sort by distance from a place.

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

Highlight

func Highlight(fields: Vector<str>): str
Highlight matches in these fields.

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

HighlightTags

func HighlightTags(fields: Vector<str>, pre: str, post: str): str
Highlight with your own tags around each match.

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

Collapse

func Collapse(field: str): str
Return only the top hit for each value of a field.

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

TermSuggest

func TermSuggest(name: str, text: str, field: str): str
A suggester that corrects the words of a text.

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

CompletionSuggest

func CompletionSuggest(name: str, prefix: str, field: str, size: int): str
A suggester that completes a prefix from a completion field.

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

TermsAgg

func TermsAgg(field: str, size: int): str
Buckets for the most common values of a field.

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

AvgAgg

func AvgAgg(field: str): str
The average of a field.

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

SumAgg

func SumAgg(field: str): str
The sum of a field.

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

MinAgg

func MinAgg(field: str): str
The smallest value of a field.

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

MaxAgg

func MaxAgg(field: str): str
The largest value of a field.

The example for this item is shown with the ones above: db-opensearch-Query.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-opensearch-Query.salam

CardinalityAgg

func CardinalityAgg(field: str): str
About how many distinct values a field has.

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

StatsAgg

func StatsAgg(field: str): str
Count, min, max, average and sum of a field.

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

ExtendedStatsAgg

func ExtendedStatsAgg(field: str): str
StatsAgg plus variance and standard deviation.

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

PercentilesAgg

func PercentilesAgg(field: str, percents: Vector<f64>): str
The given percentiles of a field.

The example for this item is shown with the ones above: db-opensearch-Query.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-opensearch-Query.salam

DateHistogramAgg

func DateHistogramAgg(field: str, calendar_interval: str): str
Buckets of a calendar interval, such as day or month.

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

RangeAgg

func RangeAgg(field: str, bounds: Vector<f64>): str
Buckets between the given bounds, plus one below the first and one above the last.

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

FilterAgg

func FilterAgg(query: str): str
One bucket of the documents that match a query.

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

NestedAgg

func NestedAgg(path: str): str
Aggregates nested objects at a path.

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

MissingAgg

func MissingAgg(field: str): str
One bucket of the documents with no value for a field.

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

TopHitsAgg

func TopHitsAgg(size: int): str
The best hits in each bucket.

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

CompositeAgg

func CompositeAgg(fields: Vector<str>, size: int): str
Pages through every combination of the values of several fields.

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

AddAgg

func AddAgg(aggs: str, name: str, agg: str): str
Adds a named aggregation to an aggregations object; start from {}.

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

SubAggs

func SubAggs(agg: str, aggs: str): str
Nests aggregations inside a bucket aggregation.

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

AddMember

func AddMember(obj: str, key: str, raw: str): str
Adds a member to a JSON object.

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

SearchBody

func SearchBody(req: SearchRequest): str
The JSON body of a search request.

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

func Search(c: Client, index: str, query: str): SearchResult
Runs a query against an index; a list or pattern works, and an empty index means all.

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

SearchWith

func SearchWith(c: Client, index: str, req: SearchRequest): SearchResult
Runs a full search request.

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

SearchRaw

func SearchRaw(c: Client, index: str, body: str): SearchResult
Runs a search with a body you wrote.

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

SearchParamsWith

func SearchParamsWith(c: Client, index: str, body: str, p: SearchParams): SearchResult
Runs a search body with url settings, such as a search pipeline.

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

ParseSearch

func ParseSearch(body: str): SearchResult
Reads a search response you already have.

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

SearchScroll

func SearchScroll(c: Client, index: str, req: SearchRequest, keep_alive: str): SearchResult
Starts a scroll: the first page and a scroll id.

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

Scroll

func Scroll(c: Client, scroll_id: str, keep_alive: str): SearchResult
The next page of a scroll; an empty page means the end.

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

ClearScroll

func ClearScroll(c: Client, scroll_id: str): bool
Frees a scroll on the server.

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

CreatePit

func CreatePit(c: Client, index: str, keep_alive: str): str
Opens a point in time on an index, for stable paging with search_after; returns its id.

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

DeletePit

func DeletePit(c: Client, pit_id: str): bool
Closes a point in time.

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

DeleteAllPits

func DeleteAllPits(c: Client): bool
Closes every point in time.

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

ListPits

func ListPits(c: Client): Vector<str>
The ids of all open points in time.

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

MSearch

func MSearch(c: Client, index: str, bodies: Vector<str>): Vector<SearchResult>
Runs several search bodies against one index in one request; one result per body, in order.

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

SearchTemplate

func SearchTemplate(c: Client, index: str, template_id: str, params: str): SearchResult
Runs a stored search template with parameters.

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

SearchInlineTemplate

func SearchInlineTemplate(c: Client, index: str, source: str, params: str): SearchResult
Runs a mustache template given as JSON, with parameters.

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

RenderTemplate

func RenderTemplate(c: Client, source: str, params: str): str
The search body a template makes with the given parameters.

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

Explain

func Explain(c: Client, index: str, id: str, query: str): str
How a document's score for a query was computed, as raw JSON.

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

Validate

func Validate(c: Client, index: str, query: str): bool
The query is valid for the index.

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

FieldCaps

func FieldCaps(c: Client, index: str, fields: Vector<str>): str
What each field can do in an index, as raw JSON.

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

Buckets

func Buckets(aggregations: str, name: str): Vector<Bucket>
The buckets of a bucket aggregation, list or keyed.

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

AggValue

func AggValue(aggregations: str, name: str): f64
The value of a single value aggregation such as avg.

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

AggField

func AggField(aggregations: str, name: str, field: str): f64
One named number of an aggregation, such as max of stats.

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

AggRaw

func AggRaw(aggregations: str, name: str): str
One aggregation as raw JSON.

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

Suggestions

func Suggestions(suggest: str, name: str): Vector<str>
The texts a suggester offered.

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

JsonPath

func JsonPath(text: str, path: str): str
A value at a dotted path, with numbers for array items, such as hits.hits.0._id; strings come back unquoted.

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

JsonPathRaw

func JsonPathRaw(text: str, path: str): str
A value at a dotted path as raw JSON.

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

JsonItems

func JsonItems(raw: str): Vector<str>
The items of a JSON array as raw JSON.

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

GetInfo

func GetInfo(c: Client): Info
What the cluster says about itself.

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

Ping

func Ping(c: Client): bool
The cluster answers.

The example for this item is shown with the ones above: db-opensearch-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-opensearch-ClusterHealth.salam

WaitForStatus

func WaitForStatus(c: Client, index: str, status: str, timeout: str): Health
Waits until the cluster, or one index, reaches a status such as yellow, or until the timeout.

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

ClusterStats

func ClusterStats(c: Client): str
Cluster statistics as raw JSON.

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

ClusterState

func ClusterState(c: Client, metrics: str): str
The cluster state as raw JSON, optionally only some metrics such as metadata.

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

GetClusterSettings

func GetClusterSettings(c: Client): str
The cluster settings as raw JSON, with flat names.

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

PutClusterSettings

func PutClusterSettings(c: Client, persistent: str, transient: str): bool
Changes persistent and transient cluster settings; pass an empty string to leave one alone.

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

AllocationExplain

func AllocationExplain(c: Client, body: str): str
Why a shard is or is not allocated, as raw JSON.

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

NodesInfo

func NodesInfo(c: Client, metrics: str): str
Information about the nodes, optionally only some metrics.

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

NodesStats

func NodesStats(c: Client, metrics: str): str
Statistics of the nodes, optionally only some metrics.

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

HotThreads

func HotThreads(c: Client): str
What the busiest threads are doing, as text.

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

Cat

func Cat(c: Client, what: str): Vector<str>
A cat API, such as shards or nodes, as one JSON object per row.

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

CatText

func CatText(c: Client, what: str): str
A cat API as the aligned text table people read.

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

Plugins

func Plugins(c: Client): Vector<str>
The plugins installed on the cluster, each named once.

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

HasPlugin

func HasPlugin(c: Client, name: str): bool
A plugin, such as opensearch-knn, is installed.

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

WaitTask

func WaitTask(c: Client, task_id: str, timeout: str): TaskInfo
Waits for a task to finish, up to a timeout.

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

ListTasks

func ListTasks(c: Client, actions: str): str
Running tasks as raw JSON, optionally only actions matching a pattern.

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

PutRepository

func PutRepository(c: Client, name: str, kind: str, settings: str): bool
Registers a snapshot repository of a type such as fs or s3.

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

GetRepository

func GetRepository(c: Client, name: str): str
A snapshot repository as raw JSON.

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

VerifyRepository

func VerifyRepository(c: Client, name: str): bool
Checks that every node can use a repository.

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

DeleteRepository

func DeleteRepository(c: Client, name: str): bool
Removes a snapshot repository; the snapshots stay where they are.

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

CreateSnapshot

func CreateSnapshot(c: Client, repo: str, snapshot: str, indices: str, wait: bool): bool
Takes a snapshot of some indices, or all when empty; with wait true it is true only when the snapshot succeeded.

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

GetSnapshot

func GetSnapshot(c: Client, repo: str, snapshot: str): str
A snapshot as raw JSON; a pattern or _all works too.

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

Snapshots

func Snapshots(c: Client, repo: str): Vector<str>
The names of all snapshots in a repository.

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

SnapshotStatus

func SnapshotStatus(c: Client, repo: str, snapshot: str): str
The progress of a snapshot as raw JSON.

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

DeleteSnapshot

func DeleteSnapshot(c: Client, repo: str, snapshot: str): bool
Deletes a snapshot.

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

RestoreSnapshot

func RestoreSnapshot(c: Client, repo: str, snapshot: str, body: str, wait: bool): bool
Restores a snapshot with a restore body, such as which indices and how to rename them.

The example for this item is shown with the ones above: db-opensearch-ClusterHealth.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-opensearch-ClusterHealth.salam

Pipeline

func Pipeline(description: str, processors: Vector<str>): str
An ingest pipeline body from a description and processors.

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

Processor

func Processor(kind: str, config: str): str
One ingest processor, such as Processor("lowercase", `{"field":"tag"}`).

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

GetPipeline

func GetPipeline(c: Client, id: str): str
An ingest pipeline as raw JSON.

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

DeletePipeline

func DeletePipeline(c: Client, id: str): bool
Deletes an ingest pipeline.

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

SimulatePipeline

func SimulatePipeline(c: Client, id: str, docs: Vector<str>): Vector<str>
Runs documents through a pipeline without storing them; returns each result's source.

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

PutScript

func PutScript(c: Client, id: str, source: str): bool
Stores a painless script under an id.

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

PutSearchTemplate

func PutSearchTemplate(c: Client, id: str, source: str): bool
Stores a mustache search template under an id, for SearchTemplate.

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

GetScript

func GetScript(c: Client, id: str): str
The source of a stored script or template.

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

DeleteScript

func DeleteScript(c: Client, id: str): bool
Deletes a stored script or template.

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

KnnIndexSettings

func KnnIndexSettings(shards: int, replicas: int): str
Index settings with k-NN turned on; 0 shards or -1 replicas leaves that setting out.

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

KnnVectorField

func KnnVectorField(dimension: int, method: KnnMethod): str
The mapping of a knn_vector field.

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

KnnIndexBody

func KnnIndexBody(field: str, dimension: int, method: KnnMethod, extra_properties: Vector<str>): str
A whole index body with k-NN turned on, one vector field and more properties.

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

KnnVector

func KnnVector(values: Vector<f64>): str
A vector as a JSON array.

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

KnnStats

func KnnStats(c: Client): str
k-NN plugin statistics as raw JSON.

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

KnnWarmup

func KnnWarmup(c: Client, index: str): bool
Loads the vector indexes of an index into memory before the first search.

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

KnnClearCache

func KnnClearCache(c: Client, index: str): bool
Drops the vector indexes of an index from memory.

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

KnnTrainModel

func KnnTrainModel(c: Client, model_id: str, body: str): bool
Trains a k-NN model, such as one for IVF or PQ.

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

KnnGetModel

func KnnGetModel(c: Client, model_id: str): str
A trained k-NN model as raw JSON.

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

KnnDeleteModel

func KnnDeleteModel(c: Client, model_id: str): bool
Deletes a k-NN model.

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

PutPolicy

func PutPolicy(c: Client, id: str, policy: str): bool
Creates an ISM policy.

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

UpdatePolicy

func UpdatePolicy(c: Client, id: str, policy: str, seq_no: i64, primary_term: i64): bool
Replaces an ISM policy, given the sequence number and primary term of the current one.

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

GetPolicy

func GetPolicy(c: Client, id: str): str
An ISM policy as raw JSON.

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

DeletePolicy

func DeletePolicy(c: Client, id: str): bool
Deletes an ISM policy.

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

AddPolicy

func AddPolicy(c: Client, index: str, policy_id: str): int
Puts indices under a policy; returns how many, -1 on failure.

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

RemovePolicy

func RemovePolicy(c: Client, index: str): int
Takes indices out of their policy.

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

ChangePolicy

func ChangePolicy(c: Client, index: str, policy_id: str, state: str): int
Moves indices to another policy, optionally starting in a given state.

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

RetryPolicy

func RetryPolicy(c: Client, index: str): int
Retries a failed policy step.

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

ExplainPolicy

func ExplainPolicy(c: Client, index: str): str
Where indices are in their policies, as raw JSON.

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

PolicyIdOf

func PolicyIdOf(c: Client, index: str): str
The id of the policy an index is under.

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

DeleteAfterPolicy

func DeleteAfterPolicy(description: str, min_index_age: str, patterns: Vector<str>): str
A policy that deletes an index once it is older than an age such as 30d; with patterns it applies to new matching indices by itself.

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

WhoAmI

func WhoAmI(c: Client): AuthInfo
Who the security plugin says you are.

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

SecurityHealth

func SecurityHealth(c: Client): str
The status of the security plugin, such as UP.

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

PutUser

func PutUser(c: Client, name: str, password: str, backend_roles: Vector<str>, attributes: str): bool
Creates or replaces an internal user with backend roles and attributes as JSON.

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

GetUser

func GetUser(c: Client, name: str): str
An internal user as raw JSON.

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

Users

func Users(c: Client): Vector<str>
The names of all internal users.

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

DeleteUser

func DeleteUser(c: Client, name: str): bool
Deletes an internal user.

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

ChangePassword

func ChangePassword(c: Client, current: str, password: str): bool
Changes the password of the user the client is signed in as.

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

RoleBody

func RoleBody(cluster_permissions: Vector<str>, index_patterns: Vector<str>, allowed_actions: Vector<str>): str
A role body from cluster permissions, index patterns and the actions allowed on them.

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

PutRole

func PutRole(c: Client, name: str, body: str): bool
Creates or replaces a role.

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

GetRole

func GetRole(c: Client, name: str): str
A role as raw JSON.

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

DeleteRole

func DeleteRole(c: Client, name: str): bool
Deletes a role.

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

PutRoleMapping

func PutRoleMapping(c: Client, role: str, users: Vector<str>, backend_roles: Vector<str>): bool
Gives a role to users and backend roles.

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

GetRoleMapping

func GetRoleMapping(c: Client, role: str): str
A role mapping as raw JSON.

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

DeleteRoleMapping

func DeleteRoleMapping(c: Client, role: str): bool
Deletes a role mapping.

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

PutSearchPipeline

func PutSearchPipeline(c: Client, id: str, body: str): bool
Creates or replaces a search pipeline.

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

GetSearchPipeline

func GetSearchPipeline(c: Client, id: str): str
A search pipeline as raw JSON.

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

DeleteSearchPipeline

func DeleteSearchPipeline(c: Client, id: str): bool
Deletes a search pipeline.

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

NormalizationPipeline

func NormalizationPipeline(normalization: str, combination: str, weights: Vector<f64>): str
A search pipeline body for hybrid search: a normalization technique such as min_max, a combination such as arithmetic_mean and optional weights.

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

CreateMonitor

func CreateMonitor(c: Client, body: str): str
Creates an alerting monitor; returns its id.

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

GetMonitor

func GetMonitor(c: Client, id: str): str
A monitor as raw JSON.

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

UpdateMonitor

func UpdateMonitor(c: Client, id: str, body: str): bool
Replaces a monitor.

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

DeleteMonitor

func DeleteMonitor(c: Client, id: str): bool
Deletes a monitor.

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

ExecuteMonitor

func ExecuteMonitor(c: Client, id: str, dry_run: bool): str
Runs a monitor now, optionally as a dry run; returns the result as raw JSON.

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

SearchMonitors

func SearchMonitors(c: Client, query: str): SearchResult
Searches the monitors.

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

MlRegisterModel

func MlRegisterModel(c: Client, body: str): str
Registers an ML Commons model; returns the task id.

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

MlDeployModel

func MlDeployModel(c: Client, model_id: str): str
Deploys a model; returns the task id.

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

MlUndeployModel

func MlUndeployModel(c: Client, model_id: str): bool
Undeploys a model.

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

MlGetModel

func MlGetModel(c: Client, model_id: str): str
A model as raw JSON.

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

MlDeleteModel

func MlDeleteModel(c: Client, model_id: str): bool
Deletes a model.

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

MlGetTask

func MlGetTask(c: Client, task_id: str): str
An ML task as raw JSON.

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

MlPredict

func MlPredict(c: Client, algorithm: str, model_id: str, body: str): str
Runs a model, such as text_embedding, on input as JSON.

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

CreateIndex

func CreateIndex(c: Client, name: str, body: str): bool
Creates an index with a settings and mappings body; an empty body uses the defaults.

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

CreateIndexWith

func CreateIndexWith(c: Client, name: str, shards: int, replicas: int, properties: str): bool
Creates an index from shard and replica counts and the mapping properties; 0 shards or -1 replicas leaves that setting out.

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

DeleteIndex

func DeleteIndex(c: Client, name: str): bool
Deletes an index; a list or pattern works too.

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

DeleteIndexIfExists

func DeleteIndexIfExists(c: Client, name: str): bool
Deletes an index and is true also when it did not exist.

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

IndexExists

func IndexExists(c: Client, name: str): bool
The index exists.

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

GetIndex

func GetIndex(c: Client, name: str): str
The settings, mappings and aliases of an index, as raw JSON.

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

GetMapping

func GetMapping(c: Client, index: str): str
The mappings as raw JSON; an empty index means all.

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

PutMapping

func PutMapping(c: Client, index: str, properties: str): bool
Adds fields to the mapping, given as the members of properties.

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

PutMappingBody

func PutMappingBody(c: Client, index: str, body: str): bool
Changes the mapping with a full body.

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

GetSettings

func GetSettings(c: Client, index: str): str
The settings as raw JSON.

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

GetSetting

func GetSetting(c: Client, index: str, name: str): str
One setting of an index, such as index.refresh_interval.

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

PutSettings

func PutSettings(c: Client, index: str, settings: str): bool
Changes index settings.

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

Refresh

func Refresh(c: Client, index: str): bool
Makes recent writes searchable.

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

Flush

func Flush(c: Client, index: str): bool
Writes the transaction log to disk.

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

ForceMerge

func ForceMerge(c: Client, index: str, max_segments: int): bool
Merges segments, down to the given count when it is above 0.

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

ClearCache

func ClearCache(c: Client, index: str): bool
Clears the caches of an index.

The example for this item is shown with the ones above: db-opensearch-CreateIndex.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-opensearch-CreateIndex.salam

CloseIndex

func CloseIndex(c: Client, index: str): bool
Closes an index; it keeps its data but takes no reads or writes.

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

CloneIndex

func CloneIndex(c: Client, source: str, target: str, body: str): bool
Copies an index whose writes are blocked into a new index.

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

ShrinkIndex

func ShrinkIndex(c: Client, source: str, target: str, body: str): bool
Copies an index into one with fewer shards.

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

SplitIndex

func SplitIndex(c: Client, source: str, target: str, body: str): bool
Copies an index into one with more shards.

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

IndexStats

func IndexStats(c: Client, index: str): str
Statistics of an index as raw JSON.

The example for this item is shown with the ones above: db-opensearch-CreateIndex.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-opensearch-CreateIndex.salam

PutAliasFiltered

func PutAliasFiltered(c: Client, index: str, alias: str, filter: str, is_write_index: bool): bool
Points an alias at an index with a filter, and optionally makes it the write index.

The example for this item is shown with the ones above: db-opensearch-CreateIndex.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-opensearch-CreateIndex.salam

AliasExists

func AliasExists(c: Client, alias: str): bool
The alias exists.

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

GetAliases

func GetAliases(c: Client, index: str): str
The aliases of an index, or all, as raw JSON.

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

AliasIndices

func AliasIndices(c: Client, alias: str): Vector<str>
The indices an alias points at.

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

AliasAction

func AliasAction(action: str, index: str, alias: str): str
One add or remove action for UpdateAliases.

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

UpdateAliases

func UpdateAliases(c: Client, actions: Vector<str>): bool
Applies several alias actions in one atomic step.

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

SwapAlias

func SwapAlias(c: Client, alias: str, old_index: str, new_index: str): bool
Moves an alias from one index to another in one atomic step; the way to rebuild an index with no downtime.

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

PutIndexTemplate

func PutIndexTemplate(c: Client, name: str, body: str): bool
Creates or replaces an index template.

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

IndexTemplate

func IndexTemplate(patterns: Vector<str>, settings: str, properties: str, priority: int): str
An index template body from patterns, settings, mapping properties and a priority.

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

GetIndexTemplate

func GetIndexTemplate(c: Client, name: str): str
An index template as raw JSON.

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

IndexTemplateExists

func IndexTemplateExists(c: Client, name: str): bool
The index template exists.

The example for this item is shown with the ones above: db-opensearch-CreateIndex.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-opensearch-CreateIndex.salam

PutComponentTemplate

func PutComponentTemplate(c: Client, name: str, body: str): bool
Creates or replaces a component template.

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

GetComponentTemplate

func GetComponentTemplate(c: Client, name: str): str
A component template as raw JSON.

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

DeleteComponentTemplate

func DeleteComponentTemplate(c: Client, name: str): bool
Deletes a component template.

The example for this item is shown with the ones above: db-opensearch-CreateIndex.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-opensearch-CreateIndex.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-opensearch-CreateIndex.salam

DataStreams

func DataStreams(c: Client): Vector<str>
The names of all data streams.

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

Rollover

func Rollover(c: Client, alias: str, conditions: str): str
Rolls an alias or data stream over to a new index, optionally only when conditions hold; returns the new index name.

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

Analyze

func Analyze(c: Client, index: str, analyzer: str, text: str): Vector<str>
The tokens an analyzer makes of a text; an empty analyzer means standard.

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

CatIndices

func CatIndices(c: Client, pattern: str): Vector<IndexInfo>
One row per index, sorted by name; an empty pattern means all.

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

Property

func Property(name: str, kind: str): str
One mapping field, "name":{"type":kind}, for Properties.

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

PropertyWith

func PropertyWith(name: str, kind: str, extra: str): str
One mapping field with more settings, such as an analyzer.

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

Properties

func Properties(props: Vector<str>): str
The mapping properties object from fields.

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

Index

func Index(c: Client, index: str, id: str, doc: str): WriteResult
Adds or replaces a document; an empty id lets the server make one.

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

IndexWith

func IndexWith(c: Client, index: str, id: str, doc: str, o: Options): WriteResult
Index with options.

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

Create

func Create(c: Client, index: str, id: str, doc: str): WriteResult
Adds a document only if no document has that id; a 409 otherwise.

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

CreateWith

func CreateWith(c: Client, index: str, id: str, doc: str, o: Options): WriteResult
Create with options.

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

Get

func Get(c: Client, index: str, id: str): Document
Reads a document by id.

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

GetFields

func GetFields(c: Client, index: str, id: str, includes: Vector<str>, routing: str): Document
Reads only some source fields of a document, optionally with a routing value.

The example for this item is shown with the ones above: db-opensearch-Index.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-opensearch-Index.salam

Exists

func Exists(c: Client, index: str, id: str): bool
The document exists.

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

Update

func Update(c: Client, index: str, id: str, partial: str): WriteResult
Merges the given fields into a document.

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

UpdateWith

func UpdateWith(c: Client, index: str, id: str, body: str, o: Options): WriteResult
Sends a full update body, such as {"doc":...} or {"script":...}, with options.

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

Upsert

func Upsert(c: Client, index: str, id: str, doc: str): WriteResult
Merges the fields into a document, creating it when it is missing.

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

UpdateScript

func UpdateScript(c: Client, index: str, id: str, script: str, upsert: str): WriteResult
Changes a document with a script, from Script; the upsert document, if given, is used when it is missing.

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

Delete

func Delete(c: Client, index: str, id: str): WriteResult
Deletes a document.

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

DeleteWith

func DeleteWith(c: Client, index: str, id: str, o: Options): WriteResult
Delete with options.

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

MGet

func MGet(c: Client, index: str, ids: Vector<str>): Vector<Document>
Reads several documents of one index at once, in the order asked.

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

Count

func Count(c: Client, index: str, query: str): i64
How many documents match a query; an empty query counts all, -1 on error.

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

DeleteByQuery

func DeleteByQuery(c: Client, index: str, query: str): ByQueryResult
Deletes every document that matches a query.

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

DeleteByQueryWith

func DeleteByQueryWith(c: Client, index: str, query: str, o: Options): ByQueryResult
DeleteByQuery with options.

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

UpdateByQuery

func UpdateByQuery(c: Client, index: str, query: str, script: str): ByQueryResult
Runs a script on every document that matches a query; an empty query means all.

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

UpdateByQueryWith

func UpdateByQueryWith(c: Client, index: str, query: str, script: str, o: Options): ByQueryResult
UpdateByQuery with options.

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

Reindex

func Reindex(c: Client, source: str, dest: str): ByQueryResult
Copies every document of one index into another.

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

ReindexBody

func ReindexBody(c: Client, body: str, wait: bool): ByQueryResult
Reindexes with a full request body; with wait false it returns at once with a task id.

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

DefaultConfig

func DefaultConfig(): Config
A configuration with the default node, ready to change.

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

NewClient

func NewClient(cfg: Config): Client
Makes a client from a configuration; check it with Ok.

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

Connect

func Connect(url: str): Client
A client for one node url; the url may carry user:password@.

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

ConnectAuth

func ConnectAuth(url: str, username: str, password: str): Client
A client for one node with basic authentication.

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

ConnectInsecure

func ConnectInsecure(url: str, username: str, password: str): Client
A client that does not check the server certificate; for the demo setup and test servers only.

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

ConnectAWS

func ConnectAWS(url: str, region: str, service: str, access_key: str, secret_key: str, session_token: str): Client
A client that signs every request with AWS SigV4, for Amazon OpenSearch Service or Serverless.

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

Ok

func Ok(c: Client): bool
The configuration was valid.

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

Error

func Error(c: Client): str
The error of the last request, or the configuration error.

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

ErrorType

func ErrorType(c: Client): str
The server's error type from the last request.

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

ErrorReason

func ErrorReason(c: Client): str
The server's error reason from the last request.

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

Status

func Status(c: Client): int
The HTTP status of the last request.

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

Nodes

func Nodes(c: Client): Vector<str>
The node urls, as the client will use them.

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

AuthHeader

func AuthHeader(c: Client): str
The Authorization header value sent with each request; empty with AWS signing, which signs each request on its own.

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

SetSigningTime

func SetSigningTime(c: Client, epoch: i64)
Fixes the clock AWS signing uses, as Unix seconds; for tests. 0 goes back to the real clock.

The example for this item is shown with the ones above: db-opensearch-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.

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

PerformNdjson

func PerformNdjson(c: Client, method: str, path: str, body: str): Response
Sends a request with an NDJSON body, as bulk and msearch expect.

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

PerformText

func PerformText(c: Client, method: str, path: str, body: str, content_type: str): Response
Sends a request with a body of the given content type.

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

EncodeBasic

func EncodeBasic(username: str, password: str): str
The base64 of user:password, as basic authentication sends it.

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

SqlParam

func SqlParam(kind: str, value: str): str
One query parameter for SqlWith, such as SqlParam("integer", "5").

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

Sql

func Sql(c: Client, query: str): SqlRows
Runs a SQL query.

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

SqlWith

func SqlWith(c: Client, query: str, params: Vector<str>, fetch_size: int): SqlRows
Runs a SQL query with ? parameters and a page size.

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

SqlFormat

func SqlFormat(c: Client, query: str, format: str): str
A SQL result in another format: csv, raw, json or jdbc.

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

SqlExplain

func SqlExplain(c: Client, query: str): str
How a SQL query will run, as raw JSON.

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

Ppl

func Ppl(c: Client, query: str): SqlRows
Runs a PPL query, such as source=logs | where code > 499 | stats count() by host.

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

PplFormat

func PplFormat(c: Client, query: str, format: str): str
A PPL result in another format.

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

PplExplain

func PplExplain(c: Client, query: str): str
How a PPL query will run, as raw JSON.

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

Conn

func Conn(c: Client): dyn db.Connection
The client as a db.Connection, for code written against db.

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

SignRequest

func SignRequest(method: str, host: str, path: str, body: str, region: str, service: str, access_key: str, secret_key: str, token: str, epoch: i64): str
The AWS SigV4 headers for one request: method, host, path with query, body, region, service, keys, session token and Unix time.
db-opensearch-SignRequest.salam
import db.opensearch

func main:
    headers := opensearch.SignRequest(
        "GET", "example.amazonaws.com", "/", "", "us-east-1", "service", "AKIDEXAMPLE",
        "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "", 1440938160 as i64
    )
    each line in headers.split("\r\n"):
        if line.len() > 0: println line end
    end
end
OutputX-Amz-Date: 20150830T123600Z X-Amz-Content-Sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 Authorization: AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=726c5c4879a6b4ccbbd3b24edbd6b8826d34f87450fbbf4e85546fc7ba9c1642