Skip to main content

Elasticsearch-Compatible API Gateway

LakeSoul ships lakesoul-es-gateway, a small HTTP service that exposes the Elasticsearch REST surface retrieval clients speak, backed by LakeSoul tables with Tantivy full-text and IVF+RaBitQ vector indexes. Clients keep their Elasticsearch driver and point it at the gateway:

  • keyword retrieval runs against the text index with BM25 scores;
  • vector retrieval runs against the vector index with cosine similarity;
  • document writes, delete-by-query and partial updates map onto LakeSoul upserts (merge-on-read plus CDC tombstones), and the indexes are maintained synchronously — a document is searchable when the write request returns.

Indexes are declared in a TOML configuration; the gateway provisions the declared tables at startup. With defaults.dynamic_indexes (on by default) an index the client creates through PUT /{index} is provisioned on its first write, so a RAG client can manage its own indexes without editing the gateway configuration.

Quick start​

cargo build --release -p lakesoul-es-gateway

lakesoul-es-gateway.toml:

[server]
listen = "0.0.0.0:9200"
version = "8.19.6" # reported by GET /; 7.x binds clients to keyword-only

[lakesoul]
namespace = "default"
warehouse_prefix = "s3://bucket/lakesoul"
# S3 credentials can be set here or via the environment
# endpoint = "http://minio:9000"
# s3_bucket = "bucket"
# s3_access_key = "..."
# s3_secret_key = "..."

[defaults]
hash_bucket_num = 4
tokenizer = "jieba"
nprobe = 64
dynamic_indexes = true # provision indexes created by PUT /{index}

# Optional: pre-declare indexes (a dynamic index needs no entry).
[[indexes]]
name = "my_index" # Elasticsearch index name
table = "my_docs" # LakeSoul table (defaults to the index name)
dim = 1536 # embedding dimension; omit for keyword-only
# Additional vector columns are declared explicitly and indexed the same way:
# vectors = [
# { column = "image_embedding", dim = 1024 },
# ]
export LAKESOUL_PG_URL='jdbc:postgresql://127.0.0.1:5432/lakesoul_test?stringtype=unspecified'
export LAKESOUL_PG_USERNAME=lakesoul_test
export LAKESOUL_PG_PASSWORD=lakesoul_test
./target/release/lakesoul-es-gateway --config lakesoul-es-gateway.toml

Document model​

The Elasticsearch index name keeps its case; the underlying LakeSoul table name is folded to lower case (LakeSoul resolves table names case-insensitively), so index WeKnora reads and writes table weknora. Keep index names unique ignoring case when they share a gateway.

Every document is stored with a fixed schema: content (the full-text column), source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id, embedding, is_enabled, is_recommended, plus one field per additional vector column declared in vectors. The internal primary key is generated by the gateway and returned as the string _id. Every vector column is L2-normalized on write and indexed with the inner-product metric, so the indexed similarity is cosine; the embedding field feeds the primary column, and each additional column is read from the document field that carries its column name.

Supported endpoints​

EndpointBehaviour
GET /Version and cluster info; the reported version.number selects the client dialect (7.x keyword-only, otherwise v8).
HEAD /{index}, PUT /{index}Declared indexes exist; an undeclared index is created when dynamic_indexes is on. PUT ignores number_of_shards/number_of_replicas.
DELETE /{index}Drops an index created at runtime (and its table); declared indexes are rejected.
GET /{index}/_mappingFixed mapping, with all filter fields as keyword.
POST /{index}/_doc, PUT /{index}/_doc/{id}/_create, PUT/POST /{index}/_doc/{id}Single-document upsert.
POST /{index}/_bulkNDJSON index/create actions (v7 _id and v8 server-generated forms).
POST /{index}/_delete_by_queryterms/term/bool filters; matching rows are rewritten as CDC tombstones.
POST /{index}/_update_by_queryThe fixed scripts for enable/disable, tag updates and moving a knowledge base.
POST/GET /{index}/_searchKeyword, vector and filter-only queries.
POST /{index}/_refreshNo-op: writes are visible immediately.

All responses carry X-Elastic-Product: Elasticsearch, and errors use the {"error":{"type","reason"},"status"} shape.

Search semantics​

Keyword search (match on the content column) returns hits ordered by BM25 with a numeric _score. Candidates are verified against the current rows, so updated or deleted documents never leak into the response.

Plain (no explicit syntax) keyword queries are scored with corpus-wide BM25 statistics: the gateway collects each shard's document count, average field length and query-term document frequencies, then computes one score per matching row against the merged numbers — the dfs_query_then_fetch semantics of a distributed search engine. Ordering therefore no longer depends on the number of hash buckets: measured on the same 20K-document corpus, the one-bucket and four-bucket configurations return identical nDCG@10 and Recall@100. Queries with explicit syntax (phrases, AND/OR) keep Tantivy's per-shard scoring.

When verification under-fills the requested size (stale candidates consumed the per-shard budget), the search retries with a four-times larger candidate budget before returning fewer hits. Rank fusion (RRF) stays on the client side.

A match query can also carry a query-time analyzer override:

{"query":{"bool":{"must":[{"match":{"content":{"query":"机器 学习","analyzer":"whitespace"}}}]}}}

Documents stay analyzed by the index-time tokenizer; the override only analyzes the query text for candidate selection, exact verification and BM25 scoring, so whitespace can match a jieba-indexed Chinese corpus whose words are separated by spaces in the query. Supported names are the index tokenizers (jieba, default, en_stem, whitespace, raw); an unknown analyzer, or an override combined with query syntax, is rejected with a 400. An override equal to the index-time analyzer is ignored.

A match query can request ES highlighting; the response then carries a highlight object per hit with fragments around the analyzed query terms:

{"query":{"bool":{"must":[{"match":{"content":"apple"}}]}},
"highlight":{"fields":{"content":{}},"pre_tags":["<em>"],"post_tags":["</em>"]},
"size":10}

The fragments are cut from the current row text (after merge-on-read), so highlighting works without stored=true; the exact verification pass already fetches that text.

Vector search uses the script_score form the clients send:

{"query":{"script_score":{
"query":{"bool":{"filter":[{"term":{"knowledge_base_id":"kb1"}}]}},
"script":{"source":"Math.max(cosineSimilarity(params.query_vector, 'embedding'), 0.0)",
"params":{"query_vector":[0.1, 0.2]}},
"min_score":0.5}},
"size":10,"_source":{"excludes":["embedding"]}}

Candidates come from the vector index; exact cosine is recomputed over the current rows and clamped to [0, 1] (mirroring the script's Math.max), and min_score filters the clamped score. A filter-only query (no scoring clause) runs as a plain scan and returns the full _source, which is what the index-copy path needs. script_score accepts any declared vector column, not only embedding.

Filter-only queries push from/size into the scan with a stable primary-key order, so one page costs one page of rows instead of the whole match set — a knowledge-base copy that pages through a large index stays linear. hits.total on that path reports a lower bound ({"value": from + hits, "relation": "gte"}) rather than scanning the complete match set for a count the client usually ignores. delete_by_query and update_by_query stream their match set in batches, so enabling, disabling, re-tagging, moving or deleting a whole knowledge base stays memory-bounded (each batch is one LakeSoul commit).

Multi-vector knn​

Several declared vector columns can be searched in one request with the Elasticsearch 8.7+ top-level knn form — one clause object, or an array of clauses that each carry their own field, query_vector, k and boost:

{"knn":[{"field":"embedding","query_vector":[0.1,0.2],"k":10,"boost":1.0},
{"field":"image_embedding","query_vector":[0.3,0.4],"k":10,"boost":0.5,
"filter":{"term":{"knowledge_base_id":"kb1"}}}],
"size":10}

By default the clauses are combined the way Elasticsearch combines multiple knn clauses: every clause contributes its own index candidates (a row only needs to be near one of the query vectors) and a hit's _score is the best boosted similarity, max(boost * cosine). A clause min_score drops that clause's contribution; a body-level min_score filters the combined score.

Setting "knn_fusion":"sum" switches to the LakeSoul fusion semantics: the per-clause candidate sets are intersected — a row must be a plausible match in every column — and the score is the weighted sum Σ boost * cosine, e.g. a text+image retrieval where both embeddings should match:

{"knn":[{"field":"embedding","query_vector":[...],"boost":0.7},
{"field":"image_embedding","query_vector":[...],"boost":0.3}],
"knn_fusion":"sum","size":10}

k is the per-clause neighbour count (defaults to size) and num_candidates overrides the per-clause candidate budget; candidates are always re-ranked exactly, so the index distances only guide candidate selection. knn cannot be combined with match or script_score in one request, and a clause naming an undeclared column, or with a mismatched dimension, is rejected with a 400.

Performance tuning​

Each hash bucket is an independent data file and index shard, so hash_bucket_num is the main trade-off between write parallelism and per-request overhead. Measured with the same 20,000-document MS MARCO corpus and 500-document bulk batches:

BucketsBulk writeSearch p50Search QPSRecall@100
4~1,200 docs/s~237 ms~585.7%
1~2,900 docs/s~76 ms~1585.7%

Start with one bucket per partition and raise it only when concurrent writers need more parallelism. Other knobs:

  • nprobe (vector, default 64) — clusters probed per shard; lower it for latency, raise it for recall.
  • Write-path index GC — with the default gc_grace_seconds = 3600 a fresh write cannot make any index file collectible, so GC is amortized: it runs on every 16th write and can be tuned with LAKESOUL_INDEX_GC_EVERY (set 1 for the old per-write behavior; a grace of 0 always runs it per write).
  • index_build — inline (default) builds index deltas before the write response returns; deferred commits data only and a background task builds the pending shards every index_build_interval_secs (default 15). While shards are pending, searches scan the not-yet-indexed data files exactly, so every write is searchable immediately at the cost of reading the backlog. On the 20K-document corpus above (1 bucket, 500-document batches) deferred writes reached ~12,900 docs/s against ~3,100 docs/s inline, with identical recall@100; search p50 was ~160 ms while a backlog existed and ~46 ms once the background build caught up. The mode is a table property set at provisioning; existing tables keep inline and the gateway logs a warning when the configuration differs.
  • Per-phase timings — start the gateway with LAKESOUL_ES_GATEWAY_TIMING=1 and RUST_LOG=lakesoul_es_gateway::timing=info to log write (parse, upsert) and search (files, resolve, lease, shard_search, fetch, verify) phase timings per request.

Sorting and aggregations​

_search accepts an Elasticsearch sort on document fields, _score and _id:

{"query":{"match_all":{}},
"sort":[{"source_type":"desc"},{"chunk_id":{"order":"asc"}}],
"size":10}

A bare field name or {"field":"asc"} is shorthand for ascending order, while _score defaults to descending. Ties fall back to the primary key, and missing: "_first" / "_last" (the default) controls where documents without the field go; other sort options are rejected so the response cannot contradict the request. Sorting uses the current row values independently of the _source projection, and every hit of an explicitly sorted response carries its resolved sort values.

Sorting is exact on the filter-only path, which scans every matching row. A match or script_score query only searches its relevance/ANN candidate budget, so any sort that needs the complete match set (_id, a document field, _score ascending) is rejected with a 400 instead of silently dropping the true top hits; _score descending — the default order — is accepted.

The aggs (or aggregations) object supports terms buckets plus the avg, sum, min, max, value_count, cardinality and stats metrics, including nested aggregations under a terms bucket:

{"query":{"match_all":{}},"size":0,
"aggs":{
"by_kb":{"terms":{"field":"knowledge_base_id","size":10,
"order":{"_count":"desc"}},
"aggs":{"avg_type":{"avg":{"field":"source_type"}}}},
"chunks":{"value_count":{"field":"chunk_id"}}}}

terms buckets default to ten buckets ordered by _count descending (with _key ascending as the tie-break), carry doc_count_error_upper_bound: 0 and sum_other_doc_count, and use Elasticsearch's 1/0 plus key_as_string form for boolean keys. terms.size must be an integer between 1 and 10000 and min_doc_count a non-negative integer, otherwise the request is rejected. The avg, sum, min, max and stats metrics require a numeric field and reject others; value_count, cardinality and terms accept any field. Aggregations run over the verified merge-on-read match set before from/size cuts the page, so size: 0 returns only aggregations. On the keyword and vector paths that set is the candidate budget the shard search returned — the same bound that applies to the returned hits — while the filter-only path scans every matching row.

Limitations​

  • Delete/update resolve their filters with a streaming table scan; only primary keys have a fast path. They apply batch by batch, so a failure mid-way leaves the earlier batches applied (like Elasticsearch's delete_by_query).
  • hits.total reports a lower bound (relation: "gte"), not an exact count, for queries that page inside the scan.
  • number_of_shards/number_of_replicas are ignored at index creation; the bucket count and nprobe come from the gateway configuration.
  • Authentication and RBAC are not implemented.
  • sort and aggregations cover the subset above: sorting allows _score, _id and document fields on filter-only queries, while a match or script_score query accepts _score descending (the default order) only. Aggregations allow terms and the listed metrics. Custom missing values, search_after, histogram, date_histogram, range, filters and pipeline aggregations are not implemented, and terms buckets skip documents missing the field.
  • Highlighting supports fields (the content column or *), pre_tags, post_tags, fragment_size and number_of_fragments; the other ES highlight options (encoder, fragmenter, require_field_match, custom number of fragments per field) are ignored. Spans come from the index analyzer and the source text is returned unescaped.
  • The _search query subset is match, terms, term, bool.filter/must/must_not and script_score with cosineSimilarity.

Running WeKnora against the gateway​

WeKnora speaks to the gateway through its Elasticsearch v7/v8 vector-store drivers, so RETRIEVE_DRIVER=elasticsearch_v8 (or elasticsearch_v7) works against LakeSoul without client changes.

  1. Gateway — with dynamic indexes (the default) no [[indexes]] entry is needed: WeKnora's PUT /{index} creates the index and its first document fixes the embedding dimension. To pin the dimension (or use object storage), declare it:

    [server]
    listen = "0.0.0.0:9200" # containers reach it through host.docker.internal
    version = "8.19.6"

    [lakesoul]
    namespace = "default"
    provision_on_start = true

    [defaults]
    hash_bucket_num = 4
    tokenizer = "jieba"
    dynamic_indexes = true

    [[indexes]] # optional
    name = "WeKnora" # ELASTICSEARCH_INDEX
    table = "weknora_docs"
    path = "file:///data/weknora_docs"
    dim = 1024 # must equal the embedding model dimension
  2. WeKnora .env — point the driver at the gateway and configure the embedding model (any OpenAI-compatible endpoint, e.g. DashScope):

    RETRIEVE_DRIVER=elasticsearch_v8
    ELASTICSEARCH_ADDR=http://host.docker.internal:9200
    ELASTICSEARCH_INDEX=WeKnora

    EMBEDDING_PROVIDER=openai
    EMBEDDING_MODEL_NAME=text-embedding-v4
    EMBEDDING_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
    EMBEDDING_API_KEY=sk-...

    # If the Docker daemon injects HTTP(S)_PROXY into containers, exclude the
    # gateway: otherwise the driver's requests to host.docker.internal are sent
    # to the proxy and fail with 502.
    NO_PROXY=localhost,127.0.0.1,host.docker.internal,.aliyuncs.com
    no_proxy=localhost,127.0.0.1,host.docker.internal,.aliyuncs.com

    FRONTEND_PORT may need a free port if 80 is taken on the host.

  3. API flow — create the embedding model with the same dimension as the gateway dim, create a knowledge base with that model, upload documents, then search:

    curl -X POST "$WEKNORA/api/v1/models" -H "Authorization: Bearer $TOKEN" -d '{"name":"text-embedding-v4","type":"Embedding","source":"remote",
    "parameters":{"base_url":"https://dashscope.aliyuncs.com/compatible-mode/v1",
    "api_key":"sk-...","provider":"aliyun",
    "embedding_parameters":{"dimension":1024}}}'
    curl -X POST "$WEKNORA/api/v1/knowledge-bases" -H "Authorization: Bearer $TOKEN" -d '{"name":"docs","embedding_model_id":"<model id>"}'
    curl -X POST "$WEKNORA/api/v1/knowledge-search" -H "Authorization: Bearer $TOKEN" -d '{"query":"全文检索","knowledge_base_id":"<kb id>"}'

    The search response fuses the keyword (BM25) and vector (script_score) result lists; both run through the gateway over the same LakeSoul table.

Driver harness​

script/weknora-es-harness/ replays the driver request sequence with the same Go clients, without deploying WeKnora:

go run ./script/weknora-es-harness --client v8 --addr http://127.0.0.1:9200 --index WeKnora --dim 1024
go run ./script/weknora-es-harness --client v7 --addr http://127.0.0.1:9200 --index WeKnora --dim 1024

It covers the version handshake, mapping-based .keyword detection, single/bulk writes, keyword and vector search, the four fixed update_by_query scripts, index-copy paging and delete_by_query, asserting the response fields the driver dereferences (_score, total == updated, no conflicts or failures).

The same flow was replayed through WeKnora's own v8 repository (internal/application/repository/retriever/elasticsearch/v8) against a gateway configured with dynamic_indexes = true and no [[indexes]]: the driver creates the index, indexes documents, retrieves by vector and BM25, disables/tags chunks, moves a knowledge item, copies a knowledge base (paging) and deletes by chunk id. That run is what the dynamic-index and paging behaviour above is tested against.

Known WeKnora v0.8.0 issues​

  • Unclamped script_score. v0.8.0 images send cosineSimilarity(params.query_vector, 'embedding') without the Math.max(..., 0.0) wrapper current main uses. The gateway accepts both spellings and clamps the score either way.
  • CopyIndices loses is_enabled. The v0.8.0 copy path builds its documents without is_enabled, so reuse_vectors knowledge moves and knowledge-base clones land disabled and are filtered out of search — on real Elasticsearch too. Current main carries is_enabled over (sourceDoc.IsEnabled, nil ⇒ true), so this only affects v0.8.0 images.