Standard library · Database

db/typesense

A Typesense client: collections, documents, typo tolerant, faceted, grouped, vector and union search, synonyms, curation, API keys, analytics and clusters.

import db.typesense

Typesense is an open source search engine with typo tolerance, filters, facets, grouping, vector and hybrid search. This package speaks its HTTP API directly with net.http and covers all of it: collections and their fields, documents one at a time or in bulk JSONL imports and exports, every search parameter, multi search and union search, synonym sets and curation sets, presets, stopwords, stemming dictionaries, API keys and scoped search keys signed with no request, analytics rules and events, conversation (RAG) models, natural language search models and the cluster operations. The examples need a running server, so they are only checked.

Every call takes an Error as its last argument and fills it when something fails; check it with Ok, or with IsNotFound and IsConflict for the two answers code usually handles. A client can hold several nodes: a node that does not answer, or answers with a 5xx, is skipped for healthcheck_ms and the request moves to the next one, the same way the official clients behave. Documents and hits come back as raw JSON text; read them into your own structs with GetDocumentAs and HitsAs, and send your structs with ImportOf and CreateDocumentOf. Typesense 30 replaced per collection synonyms and overrides with synonym sets and curation sets; both kinds are here, so the package works with 29 and 30 servers alike. For a route with no function of its own, use Request.

Tutorial: Search with Typesense

Most applications need a search box, and a good one forgives typos, ranks the best match first and answers in milliseconds. The steps below build a small book catalog, from an empty server to a scoped key that a web page can use.

Running a server

Typesense is a separate program that keeps your data in its own index. The quickest way to start one on your machine is Docker. The --api-key value is the admin key your program sends with every request; use your own secret instead of xyz outside your own computer.

docker run -p 8108:8108 typesense/typesense:30.2 --data-dir /tmp --api-key=xyz

The examples in this tutorial talk to that server, so they are checked by the compiler but not run when this site is built. The output under each one is what it printed against a real Typesense 30.2 server. Run them in order, because each example builds on the data the earlier ones left behind.

Connecting

typesense.New takes the server address and the API key and gives back a Client. Nothing is sent yet; every function that talks to the server takes the client first and an Error last. When a call fails the error is filled in: Ok tells you whether it worked, ErrorString gives one readable line, and IsNotFound and IsConflict answer the two questions code asks most often. Release the client with Free when you are done.

search-connect.salam
import db.typesense

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}

    if not typesense.Health(c, err):
        println "Typesense is not ready:", typesense.ErrorString(err)
        ret 1
    end
    println "connected, server", typesense.ServerVersion(c, err)

    _ := typesense.GetCollection(c, "no_such_collection", err)
    if not typesense.Ok(err):
        println "status", err.status, "not found:", typesense.IsNotFound(err)
        println typesense.ErrorString(err)
    end
end
Outputconnected, server 30.2 status 404 not found: true typesense 404: Collection not found

The error has three parts you can use: status is the HTTP status (0 when the server could not be reached at all), kind says what kind of failure it was, and message is the text the server sent.

Collections and fields

Documents live in a collection, and the collection's schema says which fields exist and what type each one has. NewField makes a plain field, FacetField one you can count values of, and a Field literal lets you set everything else: optional for fields some documents leave out, sort, locale for the language of the text, infix for matches in the middle of a word, and more. The types are constants such as TYPE_STRING, TYPE_INT32, TYPE_FLOAT, TYPE_STRING_ARRAY and TYPE_GEOPOINT.

search-schema.salam
import db.typesense

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}
    _ := typesense.DeleteCollection(c, "lesson_books", err)

    mut s := typesense.Schema { name = "lesson_books", default_sorting_field = "year" }
    s.fields.push(typesense.NewField("title", typesense.TYPE_STRING))
    s.fields.push(typesense.NewField("author", typesense.TYPE_STRING))
    s.fields.push(typesense.FacetField("genre", typesense.TYPE_STRING))
    s.fields.push(typesense.NewField("year", typesense.TYPE_INT32))
    s.fields.push(typesense.Field { name = "rating", kind = typesense.TYPE_FLOAT, optional = true })

    col := typesense.CreateCollection(c, s, err)
    if not typesense.Ok(err):
        println typesense.ErrorString(err)
        ret 1
    end
    println "created", col.name, "with", col.fields.len(), "fields"
    each f in col.fields:
        println " ", f.name, f.kind, "facet:", f.facet
    end
end
Outputcreated lesson_books with 5 fields title string facet: false author string facet: false genre string facet: true year int32 facet: false rating float facet: false

A numeric default_sorting_field decides the order when a search does not ask for one. Change a collection later with AddFields and DropFields, look at it with GetCollection and ListCollections, and remove it with DeleteCollection. To rebuild a collection with no downtime, build the new one next to the old one and move an alias with UpsertAlias; programs that search the alias never notice the switch.

Adding documents

A document is a JSON object whose fields match the schema. You can write that JSON yourself, but usually your program already has the data in a struct. ImportOf takes a Vector of any struct, turns each one into JSON with the compiler's own encoder and sends them all in one request. GetDocumentAs does the opposite and reads a stored document back into your struct.

search-import.salam
import db.typesense

struct Book:
    pub id: str = ""
    pub title: str = ""
    pub author: str = ""
    pub genre: str = ""
    pub year: int = 0
end

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}

    mut books := Vector {} as Vector<Book>
    books.push(Book { id = "1", title = "Dune", author = "Frank Herbert", genre = "scifi", year = 1965 })
    books.push(Book { id = "2", title = "Dune Messiah", author = "Frank Herbert", genre = "scifi", year = 1969 })
    books.push(Book { id = "3", title = "Emma", author = "Jane Austen", genre = "novel", year = 1815 })
    books.push(Book { id = "4", title = "Foundation", author = "Isaac Asimov", genre = "scifi", year = 1951 })
    books.push(Book { id = "5", title = "Persuasion", author = "Jane Austen", genre = "novel", year = 1817 })
    r := typesense.ImportOf(c, "lesson_books", books, typesense.WriteOptions { action = typesense.ACTION_UPSERT }, err)
    println "imported", r.success, "failed", r.failed

    _ := typesense.CreateDocument(c, "lesson_books", `{"id": "6", "title": "Walden", "author": "Henry Thoreau", "genre": "essay", "year": "1854"}`, err)
    println "wrong type:", typesense.ErrorString(err)
    println typesense.UpsertDocument(c, "lesson_books", `{"id": "6", "title": "Walden", "author": "Henry Thoreau", "genre": "essay", "year": 1854}`, err)

    mut b := Book {}
    if typesense.GetDocumentAs(c, "lesson_books", "1", b, err):
        println "read back:", b.title, "by", b.author
    end
    println typesense.UpdateDocument(c, "lesson_books", "6", `{"rating": 4.2}`, err)
end
Outputimported 5 failed 0 wrong type: typesense 400: Field `year` must be an int32. {"author":"Henry Thoreau","genre":"essay","id":"6","title":"Walden","year":1854} read back: Dune by Frank Herbert {"author":"Henry Thoreau","genre":"essay","id":"6","rating":4.2,"title":"Walden","year":1854}

An import answers even when some documents fail, so check failed; errors lists every failed line with its reason. WriteOptions chooses what happens to existing documents: ACTION_CREATE refuses them, ACTION_UPSERT replaces them, ACTION_UPDATE and ACTION_EMPLACE change only the fields you send. For one document at a time there are CreateDocument, UpsertDocument, UpdateDocument and DeleteDocument, and DeleteByFilter and UpdateByFilter change many at once.

NewSearch(q, query_by) makes the parameters for a search: the text to look for and the fields to look in. * as the text matches every document, which is useful together with a filter. The result has found, the number of matches, and hits, one per document on this page; hit.document is the document as JSON.

search-query.salam
import db.typesense

func show(label: str, r: typesense.SearchResult):
    println label, "found", r.found
    each h in r.hits:
        println "   ", h.document
    end
end

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}

    show("dune:", typesense.Search(c, "lesson_books", typesense.NewSearch("dune", "title"), err))
    show("typo:", typesense.Search(c, "lesson_books", typesense.NewSearch("persuasoin", "title"), err))

    mut p := typesense.NewSearch("*", "")
    p.filter_by = "genre:=scifi && year:<1966"
    p.sort_by = "year:desc"
    p.include_fields = "title,year"
    show("filtered:", typesense.Search(c, "lesson_books", p, err))

    mut h := typesense.NewSearch("austen", "author,title")
    h.per_page = 1
    r := typesense.Search(c, "lesson_books", h, err)
    println "page", r.page, "of", r.found, "results, highlight:", typesense.Highlight(r.hits.get(0), "author")
end
Outputdune: found 2 {"author":"Frank Herbert","genre":"scifi","id":"1","title":"Dune","year":1965} {"author":"Frank Herbert","genre":"scifi","id":"2","title":"Dune Messiah","year":1969} typo: found 1 {"author":"Jane Austen","genre":"novel","id":"5","title":"Persuasion","year":1817} filtered: found 2 {"title":"Dune","year":1965} {"title":"Foundation","year":1951} page 1 of 2 results, highlight: Jane <mark>Austen</mark>

Three things happened that you did not have to ask for. persuasoin still found Persuasion, because Typesense forgives a typo or two in each word. The best match came first. And Highlight shows which part of a field matched. The other parameters are fields on SearchParams: filter_by and sort_by as in the example, page and per_page for paging, include_fields to return less, num_typos to be stricter. A parameter without a field of its own goes through typesense.Set(p, name, value).

You wantWrite
Only some documentsp.filter_by = "year:>1950 && genre:=[scifi, novel]"
A different orderp.sort_by = "year:desc"
Page three, ten per pagep.page = 3 and p.per_page = 10
No typos at allp.num_typos = "0"
Your structs instead of JSONtypesense.HitsAs(result, books, err)

Facets and groups

A shop search usually shows a sidebar: how many results are shoes and how many are shirts, how many are under 100. Those counts are facets. Name the facet fields in facet_by and every result carries a Facet for each one, with the values and how many hits have them. group_by answers a different question: it keeps the best few hits for each value, here the oldest book of every genre.

search-facets.salam
import str
import db.typesense

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}

    mut p := typesense.NewSearch("*", "")
    p.facet_by = "genre"
    r := typesense.Search(c, "lesson_books", p, err)
    each f in r.facets:
        each fc in f.counts:
            println f.field_name, fc.value, fc.count
        end
    end

    mut g := typesense.NewSearch("*", "")
    g.group_by = "genre"
    g.group_limit = 1
    g.sort_by = "year:asc"
    rg := typesense.Search(c, "lesson_books", g, err)
    each grp in rg.groups:
        println "oldest", str.Join(grp.key, ""), "book:", grp.hits.get(0).document
    end
end
Outputgenre scifi 3 genre novel 2 genre essay 1 oldest novel book: {"author":"Jane Austen","genre":"novel","id":"3","title":"Emma","year":1815} oldest essay book: {"author":"Henry Thoreau","genre":"essay","id":"6","rating":4.2,"title":"Walden","year":1854} oldest scifi book: {"author":"Isaac Asimov","genre":"scifi","id":"4","title":"Foundation","year":1951}

Many searches in one request

A page that searches books and authors at the same time does not need two round trips. MultiSearch sends a list of SearchRequests in one request and returns one result per search; each result has its own code and error, so one bad search does not spoil the others. The parameters you pass as the common ones apply to all of them. UnionSearch goes one step further and merges the hits of all the searches into a single ranked list, and each hit says which search found it.

search-multi.salam
import db.typesense

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}

    mut searches := Vector {} as Vector<typesense.SearchRequest>
    searches.push(typesense.SearchRequest { collection = "lesson_books", params = typesense.NewSearch("dune", "title") })
    searches.push(typesense.SearchRequest { collection = "lesson_books", params = typesense.NewSearch("austen", "author") })
    common := typesense.SearchParams { per_page = 3 }

    each r in typesense.MultiSearch(c, searches, common, err):
        println "search found", r.found
    end
    u := typesense.UnionSearch(c, searches, common, err)
    println "union found", u.found
    each h in u.hits:
        println "  from search", h.search_index, h.document
    end
end
Outputsearch found 2 search found 2 union found 4 from search 0 {"author":"Frank Herbert","genre":"scifi","id":"1","title":"Dune","year":1965} from search 0 {"author":"Frank Herbert","genre":"scifi","id":"2","title":"Dune Messiah","year":1969} from search 1 {"author":"Jane Austen","genre":"novel","id":"5","title":"Persuasion","year":1817}

The union matched four documents but returned three, because the common parameters asked for three per page.

Synonyms and curation

Search engines only know the words in your documents. A synonym set teaches them that some words mean the same thing, so a search for sf also finds books whose genre is scifi. A curation set is for the queries you care about most: when a query matches a rule, the rule can pin documents to positions, hide others, add a filter or change the sort. Both kinds of set are created once and then attached to any collection that should use them.

search-tuning.salam
import db.typesense

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}

    mut words := Vector {} as Vector<str>
    words.push("scifi")
    words.push("science fiction")
    words.push("sf")
    mut syns := Vector {} as Vector<typesense.Synonym>
    syns.push(typesense.Synonym { id = "scifi", synonyms = words })
    _ := typesense.UpsertSynonymSet(c, "lesson_words", syns, err)

    mut pins := Vector {} as Vector<typesense.Pin>
    pins.push(typesense.Pin { id = "4", position = 1 })
    mut rules := Vector {} as Vector<typesense.CurationRule>
    rules.push(typesense.CurationRule { id = "classic-first", query = "dune", match_type = typesense.MATCH_EXACT, includes = pins })
    _ := typesense.UpsertCurationSet(c, "lesson_rules", rules, err)

    _ := typesense.UpdateCollection(c, "lesson_books", `{"synonym_sets": ["lesson_words"], "curation_sets": ["lesson_rules"]}`, err)
    println "sf finds", typesense.Search(c, "lesson_books", typesense.NewSearch("sf", "genre"), err).found, "books"
    r := typesense.Search(c, "lesson_books", typesense.NewSearch("dune", "title"), err)
    println "first hit:", r.hits.get(0).document, "curated:", r.hits.get(0).curated
end
Outputsf finds 3 books first hit: {"author":"Isaac Asimov","genre":"scifi","id":"4","title":"Foundation","year":1951} curated: true

The curated flag tells your page that a hit was placed by a rule, for example to label it as promoted. A search can turn the rules off with typesense.Set(p, "enable_curations", "false"). Typesense 29 and older keep synonyms and rules per collection instead of in sets; for those servers use UpsertSynonym and UpsertOverride.

A key for the browser

The admin key can do anything, so it must never reach a web page. SearchOnlyKey makes a key that may only search the collections you name. A scoped key goes further: ScopedSearchKey signs a search key together with search parameters, such as a filter that keeps every user to their own data. It is made in your program with no request to the server, and the browser cannot remove the filter, because changing it breaks the signature.

search-keys.salam
import db.typesense

func main:
    mut admin := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(admin)
    mut err := typesense.Error {}

    mut cols := Vector {} as Vector<str>
    cols.push("lesson_books")
    k := typesense.SearchOnlyKey(admin, "website search", cols, err)
    println "search key made, may:", k.actions.get(0)

    scoped := typesense.ScopedSearchKey(k.value, typesense.SearchParams { filter_by = "genre:=novel" }, 0)
    mut browser := typesense.New("http://localhost:8108", scoped)
    defer typesense.Free(browser)
    println "the browser sees", typesense.Search(browser, "lesson_books", typesense.NewSearch("*", ""), err).found, "books"
    _ := typesense.DeleteDocument(browser, "lesson_books", "1", err)
    println "and cannot delete:", err.status
    _ := typesense.DeleteKey(admin, k.id, err)
end
Outputsearch key made, may: documents:search the browser sees 2 books and cannot delete: 401

Give the scoped key an expiry time (the last argument, a Unix time) when it is handed out per session, and delete keys you no longer need with DeleteKey.

Vectors and places

Words are not the only way to find things. A TYPE_GEOPOINT field holds a latitude and longitude, and a filter such as location:(35.70, 51.42, 2 km) keeps only what is near a point, while sorting by the same point puts the nearest first. A vector field (VectorField) holds a list of numbers that describes a document, usually made by a machine learning model, and vector_query finds the documents whose vectors are closest to yours. With EmbeddingField, Typesense makes the vectors itself from the text of other fields.

search-vector-geo.salam
import db.typesense

func main:
    mut c := typesense.New("http://localhost:8108", "xyz")
    defer typesense.Free(c)
    mut err := typesense.Error {}
    _ := typesense.DeleteCollection(c, "lesson_places", err)

    mut s := typesense.Schema { name = "lesson_places" }
    s.fields.push(typesense.NewField("name", typesense.TYPE_STRING))
    s.fields.push(typesense.NewField("location", typesense.TYPE_GEOPOINT))
    s.fields.push(typesense.VectorField("style", 2))
    _ := typesense.CreateCollection(c, s, err)
    mut docs := Vector {} as Vector<str>
    docs.push(`{"name": "Quiet library cafe", "location": [35.7019, 51.4223], "style": [0.9, 0.1]}`)
    docs.push(`{"name": "Loud sports bar", "location": [35.6990, 51.4180], "style": [0.1, 0.9]}`)
    docs.push(`{"name": "Garden tea house", "location": [35.8040, 51.4330], "style": [0.8, 0.2]}`)
    _ := typesense.ImportDocuments(c, "lesson_places", docs, typesense.WriteOptions {}, err)

    mut near := typesense.NewSearch("*", "")
    near.filter_by = "location:(35.7000, 51.4200, 2 km)"
    near.sort_by = "location(35.7000, 51.4200):asc"
    near.include_fields = "name"
    each h in typesense.Search(c, "lesson_places", near, err).hits:
        println "near:", h.document, h.geo_distance_meters
    end

    mut like := typesense.NewSearch("*", "")
    like.vector_query = "style:([1.0, 0.0], k: 2)"
    like.include_fields = "name"
    each h in typesense.Search(c, "lesson_places", like, err).hits:
        println "calm:", h.document
    end
    _ := typesense.DeleteCollection(c, "lesson_places", err)
end
Outputnear: {"name":"Loud sports bar"} {"location":212} near: {"name":"Quiet library cafe"} {"location":296} calm: {"name":"Quiet library cafe"} calm: {"name":"Garden tea house"}

Running it for real

  • A Typesense cluster has several nodes. Give NewCluster all of their addresses: a node that does not answer is skipped for healthcheck_ms and the request moves on to the next. SetNearestNode names one to try first.
  • Tune the client with its fields: timeout_ms for a single request, retries and retry_interval_ms for how hard it tries.
  • Use an alias in your searches, not a collection name, so you can rebuild the collection without downtime.
  • Back up with CreateSnapshot, watch the server with Health, Stats and Metrics, and count clicks or popular queries with analytics rules (CreateAnalyticsRule and SendEvent).
  • For an endpoint this package has no function for, Request sends any method and path with a JSON body.

Every function, type and field is listed with its own example in the reference below. The repository also has a complete, tested program for each feature in tests/en/db, in the files that start with tslive_ex_.

Types

SearchParams

struct SearchParams
The parameters of one search. Zero values and empty strings are left out; anything else goes through Set.
NameTypeDescription
qstr = ""The text to search for; * matches every document.
query_bystr = ""The fields to search, comma separated.
query_by_weightsstr = ""The weight of each field in query_by, such as 2,1.
text_match_typestr = ""How field scores combine: max_score, max_weight or sum_score.
prefixstr = ""Whether the last word matches as a prefix, one value per field such as true,false.
infixstr = ""Infix search per field: off, always or fallback.
filter_bystr = ""A filter, such as year:>2000 && genre:=[scifi].
sort_bystr = ""The sort order, such as year:desc,_text_match:desc.
facet_bystr = ""Fields to count values of.
facet_querystr = ""Narrow the facet values, such as genre:sci.
max_facet_valuesint = 0How many values each facet returns.
group_bystr = ""Group the results by these fields.
group_limitint = 0How many hits each group returns.
include_fieldsstr = ""Return only these fields.
exclude_fieldsstr = ""Leave these fields out of the results.
highlight_fieldsstr = ""Highlight only these fields.
highlight_full_fieldsstr = ""Highlight the whole value of these fields, not a snippet.
highlight_start_tagstr = ""The tag before a match; <mark> by default.
highlight_end_tagstr = ""The tag after a match.
snippet_thresholdint = 0Fields shorter than this many words are highlighted whole.
num_typosstr = ""How many typos a word may have, 0 to 2, one value per field.
typo_tokens_thresholdint = 0Look for typo matches only when fewer results than this were found.
drop_tokens_thresholdint = 0Drop words from the query only when fewer results than this were found.
pageint = 0The page, from 1.
per_pageint = 0Hits per page, up to 250.
offsetint = 0Skip this many hits; an alternative to page.
limitint = 0Return this many hits; used with offset.
pinned_hitsstr = ""Pin documents to positions, such as 12:1,3:2.
hidden_hitsstr = ""Ids of documents to hide.
override_tagsstr = ""Apply only the curation rules with these tags.
presetstr = ""Use the parameters saved in this preset.
vector_querystr = ""A nearest neighbour search, such as embedding:([0.1, 0.2], k: 10).
stopwordsstr = ""A stopword set to apply.
exhaustive_searchbool = falseConsider every variation of the query, slower but complete.
search_cutoff_msint = 0Stop searching after this many milliseconds and return what was found.
use_cachebool = falseCache the results on the server.
cache_ttlint = 0How long to cache them, in seconds.
conversationbool = falseAnswer the query with a conversation model (RAG).
conversation_idstr = ""Continue this conversation.
conversation_model_idstr = ""The conversation model to use.
nl_querybool = falseTurn a natural language query into filters and sorting with an NL search model.
nl_model_idstr = ""The NL search model to use.
keysVectorParameter names added with Set.
valuesVectorTheir values.
db-typesense-Search.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import str
import db.typesense

struct Book:
    pub id: str = ""
    pub title: str = ""
    pub year: int = 0
end

func main:
    c := typesense.New("http://localhost:8108", "search-key")
    mut err := typesense.Error {}

    mut p := typesense.NewSearch("dune", "title,description")
    p.query_by_weights = "3,1"
    p.filter_by = "year:>1950 && genres:=[scifi]"
    p.sort_by = "_text_match:desc,year:desc"
    p.facet_by = "genres,year"
    p.max_facet_values = 10
    p.per_page = 20
    p.page = 1
    p.num_typos = "2,1"
    p.highlight_start_tag = "<b>"
    p.highlight_end_tag = "</b>"
    typesense.Set(p, "prioritize_exact_match", "false")
    println typesense.SearchQuery(p)
    println typesense.SearchParamsJSON(p)

    r := typesense.Search(c, "books", p, err)
    if not typesense.Ok(err):
        println typesense.ErrorString(err)
        ret 1
    end
    println r.found, r.out_of, r.page, r.search_time_ms, r.search_cutoff
    each h in r.hits:
        println h.document, h.text_match, h.curated, typesense.Highlight(h, "title")
        println h.highlight, h.highlights, h.text_match_info, h.vector_distance, h.geo_distance_meters, h.hybrid_search_info, h.raw.len()
    end
    each f in r.facets:
        print f.field_name, f.sampled, f.stats, ":"
        each fc in f.counts:
            print " " + fc.value + "=" + fc.count + " " + fc.highlighted
        end
        println ""
    end
    mut books := Vector {} as Vector<Book>
    if typesense.HitsAs(r, books, err):
        println books.len()
    end
    println r.request_params, r.raw.len()

    mut g := typesense.NewSearch("*", "")
    g.group_by = "genres"
    g.group_limit = 3
    g.include_fields = "id,title"
    rg := typesense.Search(c, "books", g, err)
    println rg.found, rg.found_docs
    each grp in rg.groups:
        println str.Join(grp.key, ","), grp.found, grp.hits.len()
    end

    mut v := typesense.NewSearch("*", "")
    v.vector_query = "embedding:([0.12, 0.45, 0.87], k: 10)"
    v.exclude_fields = "embedding"
    println typesense.SearchRaw(c, "books", v, err)

    mut rag := typesense.NewSearch("which books are about deserts?", "title_vector")
    rag.conversation = true
    rag.conversation_model_id = "books-assistant"
    rag.conversation_id = ""
    rag.prefix = "false"
    rag.exhaustive_search = true
    rag.search_cutoff_ms = 200
    rag.use_cache = true
    rag.cache_ttl = 60
    println typesense.Search(c, "books", rag, err).conversation

    mut nl := typesense.NewSearch("science fiction books after 1960 sorted by year", "title")
    nl.nl_query = true
    nl.nl_model_id = "gpt-4o-nl"
    println typesense.Search(c, "books", nl, err).parsed_nl_query

    mut reqs := Vector {} as Vector<typesense.SearchRequest>
    reqs.push(typesense.SearchRequest { collection = "books", params = typesense.NewSearch("dune", "") })
    reqs.push(typesense.SearchRequest { collection = "authors", params = typesense.NewSearch("herbert", "name"), api_key = "scoped-key" })
    common := typesense.NewSearch("", "title")
    each m in typesense.MultiSearch(c, reqs, common, err):
        println m.found, m.code, m.error
    end
    println typesense.MultiSearchRaw(c, reqs, common, err).len()
    u := typesense.UnionSearch(c, reqs, common, err)
    each h in u.hits:
        println h.collection, h.search_index, h.document
    end
    mut rr := typesense.ParseSearchResult(`{"found": 0, "hits": []}`)
    println rr.found, rr.code, rr.error, typesense.MAX_GET_QUERY
    typesense.FreeResult(rr)
end

SearchRequest

struct SearchRequest
One search of a multi search.
NameTypeDescription
collectionstr = ""The collection to search.
paramsSearchParamsIts parameters.
api_keystr = ""A different API key for this search only, such as a scoped key.

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

Hit

struct Hit
One search result.
NameTypeDescription
documentstr = ""The document, as JSON.
text_matchi64 = 0The text relevance score.
highlightstr = ""The highlights by field, as JSON; read one with Highlight.
highlightsstr = ""The highlights in the older list form, as JSON.
text_match_infostr = ""How the score was made, as JSON.
geo_distance_metersstr = ""The distance from a geo sort point, as JSON.
vector_distancef64 = 0The distance from the query vector.
hybrid_search_infostr = ""How a hybrid search ranked it, as JSON.
curatedbool = falseIt was placed by a curation rule.
collectionstr = ""The collection it came from, in a union search.
search_indexint = 0Which search of a union search found it, from 0.
rawstr = ""The whole hit, as JSON.

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

FacetCount

struct FacetCount
One value of a facet.
NameTypeDescription
valuestr = ""The value.
counti64 = 0How many hits have it.
highlightedstr = ""The value with the facet query highlighted.

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

Facet

struct Facet
The value counts of one field.
NameTypeDescription
field_namestr = ""The field.
countsVectorThe values, most common first.
sampledbool = falseThe counts were estimated from a sample.
statsstr = ""Minimum, maximum, sum and average of a number field, as JSON.

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

Group

struct Group
The hits that share a value of group_by.
NameTypeDescription
keyVectorThe values that make the group.
foundi64 = 0How many hits the group has.
hitsVectorIts hits, up to group_limit.

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

SearchResult

struct SearchResult
The result of a search.
NameTypeDescription
foundi64 = 0How many documents matched, or how many groups when grouping.
found_docsi64 = 0How many documents matched, when grouping.
out_ofi64 = 0How many documents were searched.
pageint = 0The page.
search_time_msi64 = 0How long the search took.
search_cutoffbool = falseThe search stopped at search_cutoff_ms.
hitsVectorThe hits.
groupsVectorThe groups, when grouping.
facetsVectorThe facet counts.
request_paramsstr = ""The parameters the server used, as JSON.
conversationstr = ""The conversation answer, as JSON.
parsed_nl_querystr = ""What a natural language query was turned into, as JSON.
codeint = 0In a multi search, the HTTP status of this search when it failed.
errorstr = ""In a multi search, why this search failed.
rawstr = ""The whole answer, as JSON.

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

AnalyticsRule

struct AnalyticsRule
An analytics rule, in the Typesense 30 form.
NameTypeDescription
namestr = ""Its name.
kindstr = ""One of the RULE_ constants.
collectionstr = ""The collection whose events it collects.
event_typestr = ""One of the EVENT_ constants.
rule_tagstr = ""A tag to list rules by.
paramsstr = ""The rule parameters, as JSON, such as {"destination_collection":"pq","limit":100}.
rawstr = ""The whole rule, as JSON; the only place a Typesense 29 rule keeps its source and destination.
db-typesense-CreateAnalyticsRule.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import db.typesense

func main:
    c := typesense.New("http://localhost:8108", "admin-key")
    mut err := typesense.Error {}

    popular := typesense.AnalyticsRule {
        name = "popular-searches", kind = typesense.RULE_POPULAR_QUERIES, collection = "books", event_type = typesense.EVENT_SEARCH,
        params = `{"destination_collection": "popular_queries", "limit": 1000}`
    }
    println typesense.AnalyticsRuleJSON(popular)
    made := typesense.CreateAnalyticsRule(c, popular, err)
    println made.name, made.kind, made.collection, made.event_type, made.params

    clicks := typesense.AnalyticsRule {
        name = "book-clicks", kind = typesense.RULE_COUNTER, collection = "books", event_type = typesense.EVENT_CLICK,
        rule_tag = "homepage", params = `{"destination_collection": "books", "counter_field": "popularity", "weight": 1}`
    }
    println typesense.UpsertAnalyticsRule(c, clicks, err).rule_tag
    println typesense.CreateAnalyticsRuleJSON(c, `{"name": "no-results", "type": "nohits_queries", "collection": "books", "event_type": "search", "params": {"destination_collection": "nohits", "limit": 100}}`, err)
    println typesense.UpsertAnalyticsRuleJSON(c, "old-style", `{"type": "popular_queries", "params": {"source": {"collections": ["books"]}, "destination": {"collection": "pq"}}}`, err)
    println typesense.GetAnalyticsRule(c, "book-clicks", err).raw
    each r in typesense.ListAnalyticsRules(c, "homepage", err):
        println r.name, r.kind
    end

    println typesense.SendEvent(c, "book-clicks", typesense.EVENT_CLICK, `{"doc_id": "42", "user_id": "u-7"}`, err)
    println typesense.SendEventJSON(c, `{"name": "book-clicks", "event_type": "click", "data": {"doc_id": "43", "user_id": "u-7"}}`, err)
    each e in typesense.GetEvents(c, "u-7", "book-clicks", 20, err):
        println e
    end
    println typesense.FlushAnalytics(c, err), typesense.AnalyticsStatus(c, err)
    println typesense.DeleteAnalyticsRule(c, "no-results", err)
    println typesense.RULE_LOG, typesense.EVENT_CONVERSION, typesense.EVENT_VISIT, typesense.EVENT_CUSTOM

    m := typesense.ConversationModel {
        id = "books-assistant", model_name = "openai/gpt-4o-mini", api_key = "sk-...", history_collection = "conversations",
        system_prompt = "You recommend books from our catalog.", max_bytes = 16384, ttl = 86400, account_id = "", vllm_url = "", extra = ""
    }
    println typesense.ConversationModelJSON(m)
    println typesense.CreateConversationModel(c, m, err)
    println typesense.GetConversationModel(c, "books-assistant", err)
    println typesense.ListConversationModels(c, err).len()
    println typesense.UpdateConversationModel(c, "books-assistant", typesense.ConversationModel { system_prompt = "Answer in one sentence." }, err)
    println typesense.DeleteConversationModel(c, "books-assistant", err)

    println typesense.CreateNLSearchModel(c, `{"id": "gpt-4o-nl", "model_name": "openai/gpt-4o-mini", "api_key": "sk-...", "max_bytes": 16000}`, err)
    println typesense.GetNLSearchModel(c, "gpt-4o-nl", err)
    println typesense.ListNLSearchModels(c, err).len()
    println typesense.UpdateNLSearchModel(c, "gpt-4o-nl", `{"temperature": 0.0}`, err)
    println typesense.DeleteNLSearchModel(c, "gpt-4o-nl", err)
end

ConversationModel

struct ConversationModel
A large language model for conversational search (RAG). Only the values you set are sent.
NameTypeDescription
idstr = ""Its id.
model_namestr = ""The model, such as openai/gpt-4o.
api_keystr = ""The key for the model provider.
history_collectionstr = ""The collection that keeps conversation history.
system_promptstr = ""The instructions given to the model.
max_bytesint = 0How much context the model receives.
ttlint = 0How long a conversation is kept, in seconds.
account_idstr = ""The account id, for Cloudflare models.
vllm_urlstr = ""The server URL, for vLLM models.
extrastr = ""More members as a JSON object.

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

Field

struct Field
One field of a collection schema. Only the values you change are sent.
NameTypeDescription
namestr = ""The field name, or a regular expression such as .*_facet.
kindstr = ""Its type, one of the TYPE_ constants.
facetbool = falseCount its values for facets and allow exact filters.
optionalbool = falseDocuments may leave it out.
indexbool = trueIndex it for search and filters; false keeps it stored only.
storebool = trueKeep it on disk; false indexes it without storing it.
sortint = 01 makes it sortable, -1 makes it not sortable, 0 keeps the default (numbers sort, text does not).
infixbool = falseAllow matches in the middle of words.
localestr = ""The language of the text, such as fa or en.
stembool = falseMatch words by their root.
stem_dictionarystr = ""A custom stemming dictionary to use.
range_indexbool = falseIndex it for fast range filters.
referencestr = ""Join to another collection, as collection.field.
async_referencebool = falseAccept a reference to a document that does not exist yet.
num_dimint = 0The size of the vector, for a float[] vector field.
vec_diststr = ""The vector distance, cosine or ip.
embedstr = ""How to make the vector automatically, as JSON; see EmbeddingField.
token_separatorsVectorExtra characters that split words in this field.
symbols_to_indexVectorSpecial characters to keep in this field.
truncate_lenint = 0How many characters of a long string to index.
dropbool = falseRemoves the field in UpdateCollection; used by DropFields.
extrastr = ""More members as a JSON object, such as {"hnsw_params":{"M":16}}.
db-typesense-CreateCollection.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import db.typesense

func main:
    c := typesense.New("http://localhost:8108", "admin-key")
    mut err := typesense.Error {}

    mut s := typesense.Schema { name = "books_v2", default_sorting_field = "year", enable_nested_fields = true }
    s.fields.push(typesense.NewField("title", typesense.TYPE_STRING))
    s.fields.push(typesense.Field { name = "title_fa", kind = typesense.TYPE_STRING, locale = "fa", stem = true, optional = true })
    s.fields.push(typesense.FacetField("year", typesense.TYPE_INT32))
    s.fields.push(typesense.FacetField("genres", typesense.TYPE_STRING_ARRAY))
    s.fields.push(typesense.Field { name = "price", kind = typesense.TYPE_FLOAT, range_index = true })
    s.fields.push(typesense.Field { name = "isbn", kind = typesense.TYPE_STRING, index = false, optional = true })
    s.fields.push(typesense.Field { name = "author_id", kind = typesense.TYPE_STRING, reference = "authors.id" })
    s.fields.push(typesense.Field { name = "location", kind = typesense.TYPE_GEOPOINT, optional = true })
    s.fields.push(typesense.VectorField("embedding", 384))
    mut from := Vector {} as Vector<str>
    from.push("title")
    s.fields.push(typesense.EmbeddingField("title_vector", from, "ts/all-MiniLM-L12-v2"))
    s.fields.push(typesense.Field { name = "meta.*", kind = typesense.TYPE_AUTO, optional = true })
    s.symbols_to_index.push("+")
    s.token_separators.push("-")
    s.metadata = `{"owner": "catalog"}`
    println typesense.SchemaJSON(s)

    col := typesense.CreateCollection(c, s, err)
    if typesense.IsConflict(err):
        println "books_v2 already exists"
    end
    println col.name, col.num_documents, col.created_at, col.fields.len()
    each f in col.fields:
        println f.name, f.kind, f.facet, f.optional, f.sort, f.index, f.store
    end

    if typesense.CollectionExists(c, "books_v2", err):
        println typesense.GetCollection(c, "books_v2", err).default_sorting_field
    end
    each x in typesense.ListCollections(c, err):
        println x.name, x.num_documents
    end
    mut skip := Vector {} as Vector<str>
    skip.push("fields")
    println typesense.ListCollectionsPage(c, 0, 20, skip, err).len()

    mut add := Vector {} as Vector<typesense.Field>
    add.push(typesense.FacetField("publisher", typesense.TYPE_STRING))
    println typesense.AddFields(c, "books_v2", add, err)
    mut drop := Vector {} as Vector<str>
    drop.push("isbn")
    println typesense.DropFields(c, "books_v2", drop, err)
    println typesense.SetCollectionMetadata(c, "books_v2", `{"owner": "search team"}`, err)
    println typesense.UpdateCollection(c, "books_v2", `{"synonym_sets": ["book-words"]}`, err)

    a := typesense.UpsertAlias(c, "books", "books_v2", err)
    println a.name, a.collection_name
    println typesense.GetAlias(c, "books", err).collection_name
    each al in typesense.ListAliases(c, err):
        println al.name, "->", al.collection_name
    end
    println typesense.CloneCollection(c, "books_v2", "books_v3", err).name
    println typesense.TruncateCollection(c, "books_v3", err)
    println typesense.DeleteCollection(c, "books_v3", err).name
    println typesense.DeleteAlias(c, "old_books", err).name
    println typesense.CreateCollectionJSON(c, `{"name": "authors", "fields": [{"name": "name", "type": "string"}]}`, err).name
    println typesense.FieldJSON(typesense.NewField("pages", typesense.TYPE_INT32))
    println typesense.TYPE_STRING_ANY, typesense.TYPE_INT32_ARRAY, typesense.TYPE_INT64, typesense.TYPE_INT64_ARRAY, typesense.TYPE_FLOAT_ARRAY
    println typesense.TYPE_BOOL, typesense.TYPE_BOOL_ARRAY, typesense.TYPE_GEOPOINT_ARRAY, typesense.TYPE_GEOPOLYGON
    println typesense.TYPE_OBJECT, typesense.TYPE_OBJECT_ARRAY, typesense.TYPE_IMAGE
end

Schema

struct Schema
A collection schema for CreateCollection.
NameTypeDescription
namestr = ""The collection name.
fieldsVectorThe fields.
default_sorting_fieldstr = ""A numeric field to sort by when a search gives no sort order.
enable_nested_fieldsbool = falseAllow object fields.
token_separatorsVectorExtra characters that split words.
symbols_to_indexVectorSpecial characters to keep, such as + for C++.
synonym_setsVectorSynonym sets this collection uses (Typesense 30).
curation_setsVectorCuration sets this collection uses (Typesense 30).
metadatastr = ""Any JSON object to keep with the collection.
voice_query_modelstr = ""The speech to text model for voice search, as JSON.
extrastr = ""More members as a JSON object.

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

Collection

struct Collection
A collection, as the server describes it.
NameTypeDescription
namestr = ""Its name.
num_documentsi64 = 0How many documents it holds.
created_ati64 = 0When it was made, as a Unix time.
default_sorting_fieldstr = ""The default sort field.
enable_nested_fieldsbool = falseWhether object fields are allowed.
fieldsVectorIts fields, with every default filled in.
token_separatorsVectorExtra word separators.
symbols_to_indexVectorSpecial characters it keeps.
synonym_setsVectorThe synonym sets it uses.
curation_setsVectorThe curation sets it uses.
metadatastr = ""Its metadata, as JSON.
rawstr = ""The whole answer, as JSON.

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

Alias

struct Alias
An alias: a second name that points to a collection.
NameTypeDescription
namestr = ""The alias.
collection_namestr = ""The collection it points to.

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

Synonym

struct Synonym
A synonym: words that should find each other.
NameTypeDescription
idstr = ""Its id.
synonymsVectorThe words. Without a root they all mean the same thing.
rootstr = ""When set, a search for the root also finds the other words, but not the other way round.
localestr = ""The language of the words, such as fa.
symbols_to_indexVectorSpecial characters the words contain that should be kept.
db-typesense-UpsertSynonymSet.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import db.typesense

func main:
    c := typesense.New("http://localhost:8108", "admin-key")
    mut err := typesense.Error {}

    mut words := Vector {} as Vector<str>
    words.push("book")
    words.push("novel")
    words.push("کتاب")
    mut items := Vector {} as Vector<typesense.Synonym>
    items.push(typesense.Synonym { id = "books", synonyms = words })
    set := typesense.UpsertSynonymSet(c, "book-words", items, err)
    println set.name, set.items.len()
    mut one := Vector {} as Vector<str>
    one.push("paperback")
    s := typesense.Synonym { id = "paper", root = "book", synonyms = one, locale = "en", symbols_to_index = Vector {} as Vector<str> }
    println typesense.SynonymJSON(s)
    println typesense.UpsertSynonymItem(c, "book-words", s, err).root
    println typesense.GetSynonymItem(c, "book-words", "paper", err).synonyms.len()
    println typesense.ListSynonymItems(c, "book-words", err).len(), typesense.GetSynonymSet(c, "book-words", err).items.len(), typesense.ListSynonymSets(c, err).len()
    println typesense.DeleteSynonymItem(c, "book-words", "paper", err)

    println typesense.UpsertSynonym(c, "books", s, err).id
    println typesense.GetSynonym(c, "books", "paper", err).root, typesense.ListSynonyms(c, "books", err).len()
    println typesense.DeleteSynonym(c, "books", "paper", err)

    mut pins := Vector {} as Vector<typesense.Pin>
    pins.push(typesense.Pin { id = "42", position = 1 })
    mut hide := Vector {} as Vector<str>
    hide.push("13")
    mut tags := Vector {} as Vector<str>
    tags.push("summer-sale")
    rule := typesense.CurationRule {
        id = "promote-dune", query = "dune", match_type = typesense.MATCH_EXACT, includes = pins, excludes = hide,
        filter_curated_hits = true, effective_from_ts = 1924992000, metadata = `{"campaign": "summer"}`
    }
    println typesense.CurationJSON(rule)
    mut rules := Vector {} as Vector<typesense.CurationRule>
    rules.push(rule)
    rules.push(typesense.CurationRule {
        id = "sale", tags = tags, rule_filter_by = "on_sale:=true", filter_by = "stock:>0", sort_by = "price:asc",
        match_type = typesense.MATCH_CONTAINS, replace_query = "", remove_matched_tokens = true, stop_processing = false,
        effective_to_ts = 1956528000, extra = ""
    })
    cs := typesense.UpsertCurationSet(c, "promotions", rules, err)
    println cs.name, cs.items.len()
    println typesense.UpsertCurationItem(c, "promotions", rule, err).id
    println typesense.GetCurationItem(c, "promotions", "sale", err).sort_by, typesense.ListCurationItems(c, "promotions", err).len()
    println typesense.GetCurationSet(c, "promotions", err).items.len(), typesense.ListCurationSets(c, err).len()
    println typesense.DeleteCurationItem(c, "promotions", "sale", err)
    println typesense.UpdateCollection(c, "books", `{"synonym_sets": ["book-words"], "curation_sets": ["promotions"]}`, err)

    println typesense.UpsertOverride(c, "books", rule, err).id
    println typesense.GetOverride(c, "books", "promote-dune", err).query, typesense.ListOverrides(c, "books", err).len()
    println typesense.DeleteOverride(c, "books", "promote-dune", err)

    mut listing := typesense.NewSearch("", "title,description")
    listing.per_page = 24
    listing.sort_by = "popularity:desc"
    pr := typesense.UpsertSearchPreset(c, "listing", listing, err)
    println pr.name, pr.value
    println typesense.UpsertPreset(c, "listing-raw", `{"query_by": "title"}`, err).value
    println typesense.GetPreset(c, "listing", err).value
    each x in typesense.ListPresets(c, err):
        println x.name
    end
    println typesense.DeletePreset(c, "listing-raw", err)

    mut sw := Vector {} as Vector<str>
    sw.push("the")
    sw.push("a")
    st := typesense.UpsertStopwords(c, "english", sw, "en", err)
    println st.id, st.locale, st.stopwords.len()
    println typesense.GetStopwords(c, "english", err).stopwords.len(), typesense.ListStopwords(c, err).len()
    println typesense.DeleteStopwords(c, "english", err)

    mut stem := Vector {} as Vector<typesense.StemWord>
    stem.push(typesense.StemWord { word = "mice", root = "mouse" })
    stem.push(typesense.StemWord { word = "geese", root = "goose" })
    println typesense.ImportStemmingDictionary(c, "irregular", stem, err)
    println typesense.ImportStemmingJSONL(c, "irregular", `{"word": "teeth", "root": "tooth"}`, err)
    d := typesense.GetStemmingDictionary(c, "irregular", err)
    println d.id, d.words.len()
    println typesense.ListStemmingDictionaries(c, err).len()
    println typesense.DeleteStemmingDictionary(c, "irregular", err)
    println typesense.DeleteCurationSet(c, "promotions", err), typesense.DeleteSynonymSet(c, "book-words", err)
end

SynonymSet

struct SynonymSet
A named set of synonyms, shared by any collection that lists it (Typesense 30).
NameTypeDescription
namestr = ""Its name.
itemsVectorThe synonyms.

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

Pin

struct Pin
A document pinned to a position in the results.
NameTypeDescription
idstr = ""The document id.
positionint = 0The position, from 1.

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

CurationRule

struct CurationRule
A curation rule (called an override before Typesense 30): when a query matches, pin, hide, filter or sort the results.
NameTypeDescription
idstr = ""Its id.
querystr = ""The query text it matches.
match_typestr = ""MATCH_EXACT or MATCH_CONTAINS.
rule_filter_bystr = ""Apply the rule when the search uses this filter.
tagsVectorApply the rule when the search sends one of these tags in override_tags.
includesVectorDocuments to pin.
excludesVectorIds of documents to hide.
filter_bystr = ""A filter to add to the search.
sort_bystr = ""A sort order to use instead.
replace_querystr = ""A query to search for instead.
remove_matched_tokensbool = falseRemove the matched words from the query.
filter_curated_hitsbool = falseApply the search filter to the pinned documents too.
stop_processingbool = trueStop at this rule when it matches; false lets later rules apply too.
effective_from_tsi64 = 0A Unix time before which the rule does nothing; 0 for always.
effective_to_tsi64 = 0A Unix time after which the rule does nothing; 0 for never.
metadatastr = ""Any JSON object to return with the results when the rule applies.
extrastr = ""More members as a JSON object, merged into the rule as they are.

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

CurationSet

struct CurationSet
A named set of curation rules, shared by any collection that lists it (Typesense 30).
NameTypeDescription
namestr = ""Its name.
itemsVectorThe rules.

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

Preset

struct Preset
Saved search parameters, used with SearchParams.preset.
NameTypeDescription
namestr = ""Its name.
valuestr = ""The parameters, as JSON.

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

Stopwords

struct Stopwords
A set of words to ignore in queries.
NameTypeDescription
idstr = ""Its id, used in SearchParams.stopwords.
stopwordsVectorThe words.
localestr = ""Their language.

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

StemWord

struct StemWord
One word and the root it reduces to.
NameTypeDescription
wordstr = ""The word.
rootstr = ""Its root.

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

StemmingDictionary

struct StemmingDictionary
A custom stemming dictionary, used with Field.stem_dictionary.
NameTypeDescription
idstr = ""Its id.
wordsVectorThe words.

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

KeySpec

struct KeySpec
A new API key.
NameTypeDescription
descriptionstr = ""What the key is for.
actionsVectorWhat it may do, such as documents:search or *.
collectionsVectorWhich collections it may use; * for all, and patterns such as org_.* work.
expires_ati64 = 0A Unix time when it stops working; 0 for never.
valuestr = ""The key text to use; empty lets the server make one.
autodeletebool = falseDelete the key once it expires.
db-typesense-CreateKey.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import db.typesense

func main:
    c := typesense.New("http://localhost:8108", "admin-key")
    mut err := typesense.Error {}

    mut books := Vector {} as Vector<str>
    books.push("books")
    search := typesense.SearchOnlyKey(c, "website search", books, err)
    println search.id, search.value, search.actions.len(), search.collections.get(0)

    mut actions := Vector {} as Vector<str>
    actions.push("documents:*")
    actions.push("collections:get")
    mut orgs := Vector {} as Vector<str>
    orgs.push("org_.*")
    spec := typesense.KeySpec { description = "tenant writer", actions = actions, collections = orgs, expires_at = 1924992000, autodelete = true }
    println typesense.KeySpecJSON(spec)
    k := typesense.CreateKey(c, spec, err)
    println k.value, k.expires_at, k.autodelete

    mut all := Vector {} as Vector<str>
    all.push(typesense.KEY_ACTION_ALL)
    admin := typesense.CreateKey(c, typesense.KeySpec { description = "admin", actions = all, collections = all, value = "my-chosen-admin-key" }, err)
    println admin.id

    g := typesense.GetKey(c, k.id, err)
    println g.value_prefix, g.description
    each key in typesense.ListKeys(c, err):
        println key.id, key.value_prefix, key.description, key.actions.len(), key.collections.len(), key.expires_at
    end
    println typesense.DeleteKey(c, k.id, err)

    scope := typesense.SearchParams { filter_by = "company_id:=124", exclude_fields = "salary" }
    scoped := typesense.ScopedSearchKey(search.value, scope, 1924992000)
    println scoped
    println typesense.GenerateScopedSearchKey(search.value, `{"filter_by":"user_id:=42"}`)
    mut browser := typesense.New("https://search.example.com", scoped)
    defer typesense.Free(browser)
    println typesense.Search(browser, "books", typesense.NewSearch("dune", "title"), err).found
    println typesense.KEY_ACTION_SEARCH
end

Key

struct Key
An API key.
NameTypeDescription
idi64 = 0Its id.
valuestr = ""The full key text; only returned when the key is created.
value_prefixstr = ""The first characters of the key, returned when it is read back.
descriptionstr = ""What it is for.
actionsVectorWhat it may do.
collectionsVectorWhich collections it may use.
expires_ati64 = 0When it stops working, as a Unix time.
autodeletebool = falseWhether it is deleted once it expires.

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

Client

struct Client
A connection to a Typesense server or cluster. Build it with New or NewCluster and release it with Free.
NameTypeDescription
nodesVectorThe node URLs, such as http://localhost:8108; a path after the host is kept as a prefix.
neareststr = ""A node to try before the others, such as the one in the same region; empty for none.
api_keystr = ""The key sent in the X-TYPESENSE-API-KEY header.
timeout_msint = 10000How long one request may take, in milliseconds; 0 waits forever.
retriesint = 3How many more times to try after a node fails.
retry_interval_msint = 100The pause between two tries, in milliseconds.
healthcheck_msint = 60000How long a node that failed is skipped, in milliseconds.
headersVectorExtra header lines added with AddHeader.
stateVectorInternal: the round robin position and when each node may be tried again.
db-typesense-Client.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import db.typesense

func main:
    mut nodes := Vector {} as Vector<str>
    nodes.push("http://ts-1:8108")
    nodes.push("http://ts-2:8108")
    nodes.push("http://ts-3:8108")
    mut c := typesense.NewCluster(nodes, "admin-key")
    defer typesense.Free(c)
    typesense.SetNearestNode(c, "http://ts-local:8108")
    typesense.AddNode(c, "http://ts-4:8108")
    typesense.AddHeader(c, "X-Request-Source", "salam")
    c.timeout_ms = 5000
    c.retries = 2
    c.retry_interval_ms = 200
    c.healthcheck_ms = 30000

    mut err := typesense.Error {}
    if not typesense.Health(c, err):
        println "not ready: " + typesense.ErrorString(err)
        ret 1
    end
    println typesense.IsHealthy(c), typesense.NodeHealthy(c, 0), typesense.NodeHealthy(c, -1)
    println "server", typesense.ServerVersion(c, err), typesense.Debug(c, err)
    st := typesense.Status(c, err)
    println st.state, st.committed_index, st.queued_writes
    println typesense.Stats(c, err)
    println typesense.Metrics(c, err)
    println typesense.CreateSnapshot(c, "/data/snapshots/today", err)
    println typesense.Vote(c, err), typesense.ClearCache(c, err), typesense.CompactDB(c, err), typesense.ResetPeers(c, err)
    println typesense.SchemaChanges(c, err).len()
    println typesense.SetSlowRequestLog(c, 1000, err), typesense.UpdateConfig(c, `{"healthy-read-lag": 1000}`, err)

    body := typesense.Request(c, "GET", "/collections?limit=1", "", err)
    if not typesense.Ok(err):
        println err.status, err.kind, err.message
        println err.kind == typesense.KIND_HTTP, err.kind == typesense.KIND_NETWORK, err.kind == typesense.KIND_INVALID, err.kind == typesense.KIND_DECODE
        println typesense.IsNotFound(err), typesense.IsConflict(err)
        ret 1
    end
    println body
    println typesense.RequestAs(c, "POST", "/stemming/dictionaries/import?id=plurals", "text/plain", `{"word":"mice","root":"mouse"}`, err)
    println typesense.VERSION, c.nodes.len(), c.nearest, c.api_key.len(), c.headers.len(), c.state.len()
    single := typesense.New("localhost:8108", "admin-key")
    println single.nodes.get(0)
end

Error

struct Error
What went wrong in the last call. Empty when the call worked.
NameTypeDescription
statusint = 0The HTTP status, or 0 when there was no answer.
kindstr = ""One of the KIND_ constants, or empty when the call worked.
messagestr = ""The message from the server, or a description of the failure.

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

ClusterStatus

struct ClusterStatus
The raft state of the node that answered.
NameTypeDescription
statestr = ""LEADER, FOLLOWER or another raft state.
committed_indexi64 = 0The last committed raft index.
queued_writesi64 = 0Writes waiting to be applied.

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

WriteOptions

struct WriteOptions
Options for writing documents. Empty fields are left out.
NameTypeDescription
actionstr = ""One of the ACTION_ constants; empty means create.
dirty_valuesstr = ""One of the DIRTY_ constants.
batch_sizeint = 0How many documents the server indexes at once during an import.
return_idbool = falseInclude the id of each document in the import result.
return_docbool = falseInclude each document in the import result.
remote_embedding_batch_sizeint = 0How many documents to send to a remote embedding model at once.
db-typesense-ImportDocuments.salam
/*
 * Salam Programming Language (2024-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 * Born from a decade of language design experience (since 2018)
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import db.typesense

struct Book:
    pub id: str = ""
    pub title: str = ""
    pub year: int = 0
end

func main:
    c := typesense.New("http://localhost:8108", "admin-key")
    mut err := typesense.Error {}

    println typesense.CreateDocument(c, "books", `{"id": "1", "title": "Dune", "year": 1965}`, err)
    println typesense.UpsertDocument(c, "books", `{"id": "1", "title": "Dune", "year": 1965}`, err)
    println typesense.EmplaceDocument(c, "books", `{"id": "2", "title": "Emma"}`, err)
    println typesense.UpdateDocument(c, "books", "2", `{"year": 1815}`, err)
    println typesense.UpdateDocumentWith(c, "books", "2", `{"year": "1815"}`, typesense.DIRTY_COERCE_OR_REJECT, err)
    println typesense.IndexDocument(c, "books", `{"id": "3", "title": "Ulysses", "year": "1922"}`, typesense.WriteOptions { action = typesense.ACTION_UPSERT, dirty_values = typesense.DIRTY_COERCE_OR_DROP }, err)
    println typesense.GetDocument(c, "books", "1", err)
    println typesense.DocumentExists(c, "books", "42", err)

    mut b := Book {}
    if typesense.GetDocumentAs(c, "books", "1", b, err):
        println b.title, b.year
    end
    println typesense.CreateDocumentOf(c, "books", Book { id = "4", title = "Beloved", year = 1987 }, err)
    println typesense.UpsertDocumentOf(c, "books", Book { id = "4", title = "Beloved", year = 1987 }, err)

    mut books := Vector {} as Vector<Book>
    books.push(Book { id = "5", title = "Hamlet", year = 1603 })
    books.push(Book { id = "6", title = "Middlemarch", year = 1871 })
    r := typesense.ImportOf(c, "books", books, typesense.WriteOptions { action = typesense.ACTION_UPSERT, batch_size = 100, return_id = true }, err)
    println r.success, r.failed, r.ids.len(), r.documents.len(), r.lines.len()
    each e in r.errors:
        println e.line, e.id, e.code, e.error, e.document
    end

    mut docs := Vector {} as Vector<str>
    docs.push(`{"id": "7", "title": "Persuasion", "year": 1817}`)
    docs.push(`{"id": "8", "title": "Walden", "year": "1854"}`)
    r2 := typesense.ImportDocuments(c, "books", docs, typesense.WriteOptions { action = typesense.ACTION_CREATE, dirty_values = typesense.DIRTY_REJECT, return_doc = true }, err)
    println r2.success, r2.failed
    r3 := typesense.ImportJSONL(c, "books", "{\"id\": \"9\", \"title\": \"Emma\"}\n", typesense.WriteOptions { action = typesense.ACTION_UPDATE, remote_embedding_batch_size = 50 }, err)
    println r3.success, typesense.ACTION_EMPLACE, typesense.DIRTY_DROP

    println typesense.UpdateByFilter(c, "books", "year:<1900", `{"classic": true}`, err)
    println typesense.DeleteByFilter(c, "books", "year:<1700", 500, err)
    println typesense.DeleteDocument(c, "books", "9", err)

    lines := typesense.ExportDocuments(c, "books", typesense.ExportOptions { filter_by = "year:>1800", include_fields = "id,title,year", exclude_fields = "" }, err)
    mut back := Vector {} as Vector<Book>
    if typesense.DecodeDocuments(lines, back, err):
        println back.len()
    end
    mut one := Book {}
    println typesense.DecodeDocument(`{"id": "1", "title": "Dune", "year": 1965}`, one, err), one.title
    println typesense.ExportJSONL(c, "books", typesense.ExportOptions {}, err).len()
end

ImportError

struct ImportError
One line of an import that failed.
NameTypeDescription
lineint = 0Its position in the import, from 0.
idstr = ""The document id, when return_id was set.
codeint = 0The HTTP status for this line, such as 400 or 409.
errorstr = ""The reason it failed.
documentstr = ""The document text, when return_doc was set.

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

ImportResult

struct ImportResult
The result of an import. Typesense answers 200 even when some lines fail, so check failed.
NameTypeDescription
successint = 0How many documents were written.
failedint = 0How many were not.
idsVectorThe ids of the written documents, with return_id.
documentsVectorThe written documents, with return_doc.
errorsVectorThe lines that failed.
linesVectorThe raw result line of every document.

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

ExportOptions

struct ExportOptions
Which documents to export and which fields.
NameTypeDescription
filter_bystr = ""A filter, such as year:>2000; empty exports all.
include_fieldsstr = ""Export only these fields, comma separated.
exclude_fieldsstr = ""Leave these fields out, comma separated.

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

Constants and variables

MAX_GET_QUERY

const MAX_GET_QUERY: i32 = 4000
A search query string longer than this many bytes is sent through /multi_search instead, as servers limit the length of a URL.

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

const RULE_POPULAR_QUERIES: str = "popular_queries"
A rule that collects the most searched queries into a collection.

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

RULE_NOHITS_QUERIES

const RULE_NOHITS_QUERIES: str = "nohits_queries"
A rule that collects queries that found nothing.

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

RULE_COUNTER

const RULE_COUNTER: str = "counter"
A rule that counts events into a field, such as clicks into a popularity score.

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

TYPE_STRING_ANY

const TYPE_STRING_ANY: str = "string*"
Text or a list of text, whichever each document has.

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

TYPE_INT64

const TYPE_INT64: str = "int64"
A 64 bit integer, such as a Unix time in milliseconds.

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

TYPE_FLOAT_ARRAY

const TYPE_FLOAT_ARRAY: str = "float[]"
A list of floating point numbers; with num_dim it is a vector.

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

TYPE_GEOPOINT

const TYPE_GEOPOINT: str = "geopoint"
A latitude and longitude, written as [lat, lng].

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

TYPE_GEOPOINT_ARRAY

const TYPE_GEOPOINT_ARRAY: str = "geopoint[]"
A list of geopoints.

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

TYPE_GEOPOLYGON

const TYPE_GEOPOLYGON: str = "geopolygon"
An area on the map, for searching which areas contain a point.

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

TYPE_OBJECT

const TYPE_OBJECT: str = "object"
A nested object; needs enable_nested_fields.

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

TYPE_IMAGE

const TYPE_IMAGE: str = "image"
An image, for image search with a CLIP model.

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

TYPE_AUTO

const TYPE_AUTO: str = "auto"
Let Typesense guess the type from the first document, often used with a name pattern such as .*.

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

MATCH_EXACT

const MATCH_EXACT: str = "exact"
A curation rule that applies when the query is exactly its text.

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

MATCH_CONTAINS

const MATCH_CONTAINS: str = "contains"
A curation rule that applies when the query contains its text.

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

KEY_ACTION_ALL

const KEY_ACTION_ALL: str = "*"
Every action, for an admin key.

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

const KEY_ACTION_SEARCH: str = "documents:search"
Searching only, for a key a browser can hold.

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

VERSION

const VERSION: str = "1.0.0"
The version of this client, sent in the User-Agent header.

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

KIND_HTTP

const KIND_HTTP: str = "http"
Error.kind when the server answered with an error status.

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

KIND_NETWORK

const KIND_NETWORK: str = "network"
Error.kind when no node could be reached, or a request timed out.

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

KIND_INVALID

const KIND_INVALID: str = "invalid"
Error.kind when the client itself is unusable, such as having no nodes.

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

KIND_DECODE

const KIND_DECODE: str = "decode"
Error.kind when a document could not be read into your struct.

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

ACTION_CREATE

const ACTION_CREATE: str = "create"
Index a new document; fail when the id exists.

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

ACTION_UPSERT

const ACTION_UPSERT: str = "upsert"
Create the document, or replace the one with the same id.

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

ACTION_UPDATE

const ACTION_UPDATE: str = "update"
Change the given fields of an existing document; fail when it does not exist.

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

ACTION_EMPLACE

const ACTION_EMPLACE: str = "emplace"
Create the document, or update the given fields when it exists.

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

DIRTY_COERCE_OR_REJECT

const DIRTY_COERCE_OR_REJECT: str = "coerce_or_reject"
Turn a value of the wrong type into the field type, and reject the document when that is not possible.

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

DIRTY_COERCE_OR_DROP

const DIRTY_COERCE_OR_DROP: str = "coerce_or_drop"
Turn a value of the wrong type into the field type, and drop the field when that is not possible.

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

DIRTY_DROP

const DIRTY_DROP: str = "drop"
Drop fields whose value has the wrong type.

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

DIRTY_REJECT

const DIRTY_REJECT: str = "reject"
Reject documents with a value of the wrong type.

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

Functions

NewSearch

func NewSearch(q: str, query_by: str): SearchParams
Search parameters with a query and the fields to search.

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

Set

func Set(p &: SearchParams, key: str, value: str)
Sets any parameter by name, replacing an earlier value; for parameters without a field, such as prioritize_exact_match, or enable_curations set to false to switch off curation rules for one search (enable_overrides on Typesense 29).

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

SearchQuery

func SearchQuery(p: SearchParams): str
The parameters as a URL query string.

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

SearchParamsJSON

func SearchParamsJSON(p: SearchParams): str
The parameters as a JSON object.

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

ParseSearchResult

func ParseSearchResult(body: str): SearchResult
Reads a search answer you got some other way.

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

SearchRaw

func SearchRaw(c: Client, collection: str, p: SearchParams, err &: Error): str
Searches a collection and returns the answer as JSON.

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

func Search(c: Client, collection: str, p: SearchParams, err &: Error): SearchResult
Searches a collection.

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

MultiSearchRaw

func MultiSearchRaw(c: Client, searches: Vector<SearchRequest>, common: SearchParams, err &: Error): str
Runs several searches in one request and returns the answer as JSON.

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

MultiSearch

func MultiSearch(c: Client, searches: Vector<SearchRequest>, common: SearchParams, err &: Error): Vector<SearchResult>
Runs several searches in one request; the common parameters apply to all of them, and each result has its own code and error.

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

UnionSearch

func UnionSearch(c: Client, searches: Vector<SearchRequest>, common: SearchParams, err &: Error): SearchResult
Runs several searches and merges their hits into one ranked list.

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

HitsAs

func HitsAs<T>(r: SearchResult, out &: Vector<T>, err &: Error): bool
Reads the hit documents into a list of your structs.

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

Highlight

func Highlight(h: Hit, field: str): str
The highlighted snippet of a field in a hit; snippets of a list field are joined with spaces.

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

FreeResult

func FreeResult(r &: SearchResult)
Releases the lists a search result holds.

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

CreateAnalyticsRuleJSON

func CreateAnalyticsRuleJSON(c: Client, rule: str, err &: Error): str
Creates a rule from JSON, in the form your server expects.

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

UpsertAnalyticsRuleJSON

func UpsertAnalyticsRuleJSON(c: Client, name: str, rule: str, err &: Error): str
Creates or replaces a rule by name, from JSON.

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

CreateAnalyticsRule

func CreateAnalyticsRule(c: Client, r: AnalyticsRule, err &: Error): AnalyticsRule
Creates a rule.

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

UpsertAnalyticsRule

func UpsertAnalyticsRule(c: Client, r: AnalyticsRule, err &: Error): AnalyticsRule
Creates or replaces a rule.

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

GetAnalyticsRule

func GetAnalyticsRule(c: Client, name: str, err &: Error): AnalyticsRule
One rule.

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

ListAnalyticsRules

func ListAnalyticsRules(c: Client, rule_tag: str, err &: Error): Vector<AnalyticsRule>
Every rule, or only those with a tag; reads both the Typesense 29 and 30 answers.

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

DeleteAnalyticsRule

func DeleteAnalyticsRule(c: Client, name: str, err &: Error): str
Deletes a rule and returns its name.

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

SendEventJSON

func SendEventJSON(c: Client, event: str, err &: Error): bool
Sends an event written as JSON.

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

SendEvent

func SendEvent(c: Client, name: str, event_type: str, data: str, err &: Error): bool
Sends an event to the rule with this name, with its data as JSON, such as {"doc_id":"1","user_id":"u1"}.

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

GetEvents

func GetEvents(c: Client, user_id: str, name: str, n: int, err &: Error): Vector<str>
The latest events of a user for a rule, one JSON object each.

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

FlushAnalytics

func FlushAnalytics(c: Client, err &: Error): bool
Writes the collected analytics to their collections now.

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

AnalyticsStatus

func AnalyticsStatus(c: Client, err &: Error): str
Counts of the events waiting to be written, as JSON.

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

ConversationModelJSON

func ConversationModelJSON(m: ConversationModel): str
The JSON of a conversation model.

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

CreateConversationModel

func CreateConversationModel(c: Client, m: ConversationModel, err &: Error): str
Creates a conversation model; the server checks the key with the provider.

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

GetConversationModel

func GetConversationModel(c: Client, id: str, err &: Error): str
One conversation model, as JSON.

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

ListConversationModels

func ListConversationModels(c: Client, err &: Error): Vector<str>
Every conversation model, one JSON object each.

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

UpdateConversationModel

func UpdateConversationModel(c: Client, id: str, m: ConversationModel, err &: Error): str
Changes a conversation model.

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

DeleteConversationModel

func DeleteConversationModel(c: Client, id: str, err &: Error): str
Deletes a conversation model.

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

CreateNLSearchModel

func CreateNLSearchModel(c: Client, model: str, err &: Error): str
Creates a natural language search model from JSON.

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

GetNLSearchModel

func GetNLSearchModel(c: Client, id: str, err &: Error): str
One NL search model, as JSON.

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

ListNLSearchModels

func ListNLSearchModels(c: Client, err &: Error): Vector<str>
Every NL search model, one JSON object each.

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

UpdateNLSearchModel

func UpdateNLSearchModel(c: Client, id: str, model: str, err &: Error): str
Changes an NL search model.

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

DeleteNLSearchModel

func DeleteNLSearchModel(c: Client, id: str, err &: Error): str
Deletes an NL search model.

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

FacetField

func FacetField(name: str, kind: str): Field
A field with facets turned on.

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

VectorField

func VectorField(name: str, num_dim: int): Field
A float[] vector field of the given size.

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

EmbeddingField

func EmbeddingField(name: str, from: Vector<str>, model_name: str): Field
A vector field that Typesense fills by running a model on other fields, such as ts/all-MiniLM-L12-v2.

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

CreateCollection

func CreateCollection(c: Client, schema: Schema, err &: Error): Collection
Creates a collection from a schema.

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

CreateCollectionJSON

func CreateCollectionJSON(c: Client, schema: str, err &: Error): Collection
Creates a collection from a schema written as JSON.

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

CloneCollection

func CloneCollection(c: Client, source: str, name: str, err &: Error): Collection
Makes a new, empty collection with the schema of another.

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

GetCollection

func GetCollection(c: Client, name: str, err &: Error): Collection
One collection.

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

CollectionExists

func CollectionExists(c: Client, name: str, err &: Error): bool
Whether a collection exists.

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

ListCollections

func ListCollections(c: Client, err &: Error): Vector<Collection>
Every collection.

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

ListCollectionsPage

func ListCollectionsPage(c: Client, offset: int, limit: int, exclude_fields: Vector<str>, err &: Error): Vector<Collection>
A page of collections; 0 means no offset or no limit, and exclude_fields such as fields makes the answer smaller.

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

UpdateCollection

func UpdateCollection(c: Client, name: str, changes: str, err &: Error): str
Changes a collection with a JSON body: fields to add or drop, metadata, synonym and curation sets.

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

AddFields

func AddFields(c: Client, name: str, fields: Vector<Field>, err &: Error): str
Adds fields to a collection; existing documents are indexed again.

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

DropFields

func DropFields(c: Client, name: str, fields: Vector<str>, err &: Error): str
Removes fields from a collection by name.

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

SetCollectionMetadata

func SetCollectionMetadata(c: Client, name: str, metadata: str, err &: Error): str
Replaces the metadata of a collection.

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

DeleteCollection

func DeleteCollection(c: Client, name: str, err &: Error): Collection
Deletes a collection and all its documents.

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

TruncateCollection

func TruncateCollection(c: Client, name: str, err &: Error): i64
Deletes every document but keeps the collection, and returns how many were deleted.

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

UpsertAlias

func UpsertAlias(c: Client, name: str, collection: str, err &: Error): Alias
Points an alias at a collection; moving it is the way to switch to a rebuilt collection with no downtime.

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

DeleteAlias

func DeleteAlias(c: Client, name: str, err &: Error): Alias
Deletes an alias, not the collection.

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

CurationJSON

func CurationJSON(r: CurationRule): str
The JSON body of a curation rule.

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

UpsertSynonymSet

func UpsertSynonymSet(c: Client, name: str, items: Vector<Synonym>, err &: Error): SynonymSet
Creates or replaces a synonym set (Typesense 30).

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

GetSynonymSet

func GetSynonymSet(c: Client, name: str, err &: Error): SynonymSet
One synonym set.

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

ListSynonymSets

func ListSynonymSets(c: Client, err &: Error): Vector<SynonymSet>
Every synonym set.

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

DeleteSynonymSet

func DeleteSynonymSet(c: Client, name: str, err &: Error): str
Deletes a synonym set and returns its name.

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

UpsertSynonymItem

func UpsertSynonymItem(c: Client, set: str, item: Synonym, err &: Error): Synonym
Adds or replaces one synonym in a set that exists.

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

GetSynonymItem

func GetSynonymItem(c: Client, set: str, id: str, err &: Error): Synonym
One synonym of a set.

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

ListSynonymItems

func ListSynonymItems(c: Client, set: str, err &: Error): Vector<Synonym>
The synonyms of a set.

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

DeleteSynonymItem

func DeleteSynonymItem(c: Client, set: str, id: str, err &: Error): str
Deletes one synonym of a set and returns its id.

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

UpsertSynonym

func UpsertSynonym(c: Client, collection: str, s: Synonym, err &: Error): Synonym
Adds or replaces a synonym of one collection (Typesense 29 and older).

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

GetSynonym

func GetSynonym(c: Client, collection: str, id: str, err &: Error): Synonym
One synonym of a collection (Typesense 29 and older).

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

ListSynonyms

func ListSynonyms(c: Client, collection: str, err &: Error): Vector<Synonym>
The synonyms of a collection (Typesense 29 and older).

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

DeleteSynonym

func DeleteSynonym(c: Client, collection: str, id: str, err &: Error): str
Deletes a synonym of a collection (Typesense 29 and older).

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

UpsertCurationSet

func UpsertCurationSet(c: Client, name: str, items: Vector<CurationRule>, err &: Error): CurationSet
Creates or replaces a curation set (Typesense 30).

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

GetCurationSet

func GetCurationSet(c: Client, name: str, err &: Error): CurationSet
One curation set.

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

ListCurationSets

func ListCurationSets(c: Client, err &: Error): Vector<CurationSet>
Every curation set.

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

DeleteCurationSet

func DeleteCurationSet(c: Client, name: str, err &: Error): str
Deletes a curation set and returns its name.

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

UpsertCurationItem

func UpsertCurationItem(c: Client, set: str, r: CurationRule, err &: Error): CurationRule
Adds or replaces one rule in a curation set that exists.

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

GetCurationItem

func GetCurationItem(c: Client, set: str, id: str, err &: Error): CurationRule
One rule of a curation set.

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

ListCurationItems

func ListCurationItems(c: Client, set: str, err &: Error): Vector<CurationRule>
The rules of a curation set.

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

DeleteCurationItem

func DeleteCurationItem(c: Client, set: str, id: str, err &: Error): str
Deletes one rule of a curation set and returns its id.

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

UpsertOverride

func UpsertOverride(c: Client, collection: str, r: CurationRule, err &: Error): CurationRule
Adds or replaces an override of one collection (Typesense 29 and older).

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

GetOverride

func GetOverride(c: Client, collection: str, id: str, err &: Error): CurationRule
One override of a collection (Typesense 29 and older).

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

ListOverrides

func ListOverrides(c: Client, collection: str, err &: Error): Vector<CurationRule>
The overrides of a collection (Typesense 29 and older).

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

DeleteOverride

func DeleteOverride(c: Client, collection: str, id: str, err &: Error): str
Deletes an override of a collection (Typesense 29 and older).

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

UpsertPreset

func UpsertPreset(c: Client, name: str, value: str, err &: Error): Preset
Creates or replaces a preset; pass its value as JSON.

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

UpsertSearchPreset

func UpsertSearchPreset(c: Client, name: str, p: SearchParams, err &: Error): Preset
Saves a SearchParams as a preset.

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

DeletePreset

func DeletePreset(c: Client, name: str, err &: Error): str
Deletes a preset and returns its name.

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

UpsertStopwords

func UpsertStopwords(c: Client, id: str, words: Vector<str>, locale: str, err &: Error): Stopwords
Creates or replaces a stopword set.

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

GetStopwords

func GetStopwords(c: Client, id: str, err &: Error): Stopwords
One stopword set.

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

ListStopwords

func ListStopwords(c: Client, err &: Error): Vector<Stopwords>
Every stopword set.

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

DeleteStopwords

func DeleteStopwords(c: Client, id: str, err &: Error): str
Deletes a stopword set and returns its id.

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

ImportStemmingJSONL

func ImportStemmingJSONL(c: Client, id: str, jsonl: str, err &: Error): bool
Imports a stemming dictionary written one {"word","root"} object per line.

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

ImportStemmingDictionary

func ImportStemmingDictionary(c: Client, id: str, words: Vector<StemWord>, err &: Error): bool
Imports a stemming dictionary from a list of words.

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

GetStemmingDictionary

func GetStemmingDictionary(c: Client, id: str, err &: Error): StemmingDictionary
One stemming dictionary.

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

ListStemmingDictionaries

func ListStemmingDictionaries(c: Client, err &: Error): Vector<str>
The ids of every stemming dictionary.

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

DeleteStemmingDictionary

func DeleteStemmingDictionary(c: Client, id: str, err &: Error): str
Deletes a stemming dictionary and returns its id.

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

KeySpecJSON

func KeySpecJSON(spec: KeySpec): str
The JSON body for a key spec.

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

CreateKey

func CreateKey(c: Client, spec: KeySpec, err &: Error): Key
Creates an API key; the returned value is the only time the full key is shown.

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

SearchOnlyKey

func SearchOnlyKey(c: Client, description: str, collections: Vector<str>, err &: Error): Key
Creates a key that may only search the given collections.

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

GetKey

func GetKey(c: Client, id: i64, err &: Error): Key
One key, by id; only its prefix comes back.

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

ListKeys

func ListKeys(c: Client, err &: Error): Vector<Key>
Every key.

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

DeleteKey

func DeleteKey(c: Client, id: i64, err &: Error): i64
Deletes a key and returns its id.

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

GenerateScopedSearchKey

func GenerateScopedSearchKey(search_key: str, embedded_params: str): str
Signs a scoped search key from a search key and embedded search parameters as JSON, with no request to the server. The parameters, such as a filter_by and an expires_at, are applied to every search made with it and cannot be changed by the browser.

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

ScopedSearchKey

func ScopedSearchKey(search_key: str, p: SearchParams, expires_at: i64): str
GenerateScopedSearchKey with the parameters taken from a SearchParams; 0 for no expiry.

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

New

func New(url: str, api_key: str): Client
A client for one node. A URL with no scheme gets http://, and a trailing slash is dropped.

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

NewCluster

func NewCluster(urls: Vector<str>, api_key: str): Client
A client for several nodes, tried in turn.

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

SetNearestNode

func SetNearestNode(c &: Client, url: str)
Sets the node to try first.

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

AddNode

func AddNode(c &: Client, url: str)
Adds one more node to a client.

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

AddHeader

func AddHeader(c &: Client, name: str, value: str)
Adds a header to every request this client sends.

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

Free

func Free(c &: Client)
Releases the memory a client holds.

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

NodeHealthy

func NodeHealthy(c: Client, index: int): bool
Whether the node at this index may be tried now; -1 asks about the nearest node.

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

Ok

func Ok(err: Error): bool
True when the last call worked.

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

IsNotFound

func IsNotFound(err: Error): bool
True when the server answered 404.

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

IsConflict

func IsConflict(err: Error): bool
True when the server answered 409, for example when a collection or document already exists.

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

ErrorString

func ErrorString(err: Error): str
The error as one line of text, or empty when there is none.

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

Request

func Request(c: Client, method: str, path: str, body: str, err &: Error): str
Sends any request with a JSON body and returns the response body; for routes this package has no function for.

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

RequestAs

func RequestAs(c: Client, method: str, path: str, content_type: str, body: str, err &: Error): str
Like Request, with a content type of your choice.

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

Health

func Health(c: Client, err &: Error): bool
True when the node is ready to serve.

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

IsHealthy

func IsHealthy(c: Client): bool
Health without the error argument.

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

Debug

func Debug(c: Client, err &: Error): str
The /debug answer, with the server version, as JSON.

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

ServerVersion

func ServerVersion(c: Client, err &: Error): str
The version of the server, such as 30.2.

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

Stats

func Stats(c: Client, err &: Error): str
Request rates and latencies, as JSON.

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

Metrics

func Metrics(c: Client, err &: Error): str
Memory, disk and CPU numbers, as JSON.

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

Status

func Status(c: Client, err &: Error): ClusterStatus
The raft state of the node.

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

CreateSnapshot

func CreateSnapshot(c: Client, snapshot_path: str, err &: Error): bool
Writes a snapshot of the data to a directory on the server, for backups.

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

Vote

func Vote(c: Client, err &: Error): bool
Asks the node to start a leader election; true when it did.

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

ClearCache

func ClearCache(c: Client, err &: Error): bool
Empties the search result cache.

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

CompactDB

func CompactDB(c: Client, err &: Error): bool
Compacts the on disk database.

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

ResetPeers

func ResetPeers(c: Client, err &: Error): bool
Resets the raft peers of a node that lost its quorum.

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

SchemaChanges

func SchemaChanges(c: Client, err &: Error): Vector<str>
Schema changes still running, one JSON object each.

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

UpdateConfig

func UpdateConfig(c: Client, config: str, err &: Error): bool
Changes server settings at run time; pass them as JSON.

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

SetSlowRequestLog

func SetSlowRequestLog(c: Client, millis: int, err &: Error): bool
Logs requests slower than this many milliseconds; -1 turns the log off.

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

IndexDocument

func IndexDocument(c: Client, collection: str, document: str, opts: WriteOptions, err &: Error): str
Writes one document with the given options.

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

CreateDocument

func CreateDocument(c: Client, collection: str, document: str, err &: Error): str
Indexes a new document and returns it.

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

UpsertDocument

func UpsertDocument(c: Client, collection: str, document: str, err &: Error): str
Creates a document or replaces the one with the same id.

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

EmplaceDocument

func EmplaceDocument(c: Client, collection: str, document: str, err &: Error): str
Creates a document or updates the given fields of the one with the same id.

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

UpdateDocument

func UpdateDocument(c: Client, collection: str, id: str, partial: str, err &: Error): str
Changes some fields of a document.

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

UpdateDocumentWith

func UpdateDocumentWith(c: Client, collection: str, id: str, partial: str, dirty_values: str, err &: Error): str
UpdateDocument with a dirty_values mode.

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

GetDocument

func GetDocument(c: Client, collection: str, id: str, err &: Error): str
One document, by id, as JSON.

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

DocumentExists

func DocumentExists(c: Client, collection: str, id: str, err &: Error): bool
Whether a document with this id exists.

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

DeleteDocument

func DeleteDocument(c: Client, collection: str, id: str, err &: Error): str
Deletes a document and returns it.

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

DeleteByFilter

func DeleteByFilter(c: Client, collection: str, filter_by: str, batch_size: int, err &: Error): i64
Deletes every document that matches a filter and returns how many; 0 for the batch size means the server default.

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

UpdateByFilter

func UpdateByFilter(c: Client, collection: str, filter_by: str, partial: str, err &: Error): i64
Changes the given fields of every document that matches a filter and returns how many.

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

ImportJSONL

func ImportJSONL(c: Client, collection: str, jsonl: str, opts: WriteOptions, err &: Error): ImportResult
Imports documents written one JSON object per line.

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

ImportDocuments

func ImportDocuments(c: Client, collection: str, documents: Vector<str>, opts: WriteOptions, err &: Error): ImportResult
Imports a list of JSON documents; each one is put on a single line first.

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

ImportOf

func ImportOf<T>(c: Client, collection: str, documents: Vector<T>, opts: WriteOptions, err &: Error): ImportResult
Imports a list of your own structs, written with json.Marshal.

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

CreateDocumentOf

func CreateDocumentOf<T>(c: Client, collection: str, document: T, err &: Error): str
Creates one document from your own struct.

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

UpsertDocumentOf

func UpsertDocumentOf<T>(c: Client, collection: str, document: T, err &: Error): str
Upserts one document from your own struct.

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

DecodeDocument

func DecodeDocument<T>(document: str, out &: T, err &: Error): bool
Reads one JSON document into your struct.

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

GetDocumentAs

func GetDocumentAs<T>(c: Client, collection: str, id: str, out &: T, err &: Error): bool
Reads one document by id into your struct.

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

DecodeDocuments

func DecodeDocuments<T>(documents: Vector<str>, out &: Vector<T>, err &: Error): bool
Reads a list of JSON documents into a list of your structs.

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

ExportJSONL

func ExportJSONL(c: Client, collection: str, opts: ExportOptions, err &: Error): str
Exports documents, one JSON object per line.

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

ExportDocuments

func ExportDocuments(c: Client, collection: str, opts: ExportOptions, err &: Error): Vector<str>
Exports documents as a list, one JSON document each.

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