Tenant-level custom fields: Flattened

Updated at:

In multi-tenant knowledge bases or SaaS businesses, different tenants often need to attach their own extension attributes to documents. The flattened field works like a JSON extension column in a data table: no matter how many custom sub-keys each tenant writes, it always occupies only 1 field in the mapping. This avoids hitting the per-table field cap (default 1000), which would cause write failures or memory bloat, and avoids conflicts when different tenants use the same sub-key name with different types. After writing, you can directly run exact filtering by sub-path, vector KNN pre-filtering, and terms group aggregations.

Note

All API examples in this topic provide CONSOLE / CURL / GO / PYTHON / JAVASCRIPT / JAVA code tabs (CONSOLE requests can be copied directly into Kibana Dev Tools). The other SDK examples reuse, as initialized in Quick start, the environment variables and the client instance.

1. What is flattened? (Understand it with a concrete example)

In Agentic ES, all Slices (partitions) under the same Collection share one Mapping (table schema), and the total number of fields per table has a default cap of 1000. Too many fields not only amplify metadata and memory overhead and slow down mapping synchronization and queries; once the cap is exceeded, documents containing new fields fail to write outright. In a multi-tenant scenario, even if 200 tenants each add only 10 custom fields, the total reaches 2000 and blows up the whole table, making it impossible for other tenants to add fields.

image

Suppose you run a multi-tenant knowledge-base platform where all tenants share one table kb-multi-tenant, but each tenant wants completely different custom attributes on its documents:

  • Tenant A (e-commerce customer service) writes:

  {
    "title": "Refund policy guide",
    "metadata": {
      "dept": "after-sales",
      "version": 20,
      "author": { "name": "alice", "region": "hz" },
      "tags": ["vip", "refund"]
    }
  }
  • Tenant B (R&D documentation) writes to the same table:

  {
    "title": "API Auth Guide",
    "metadata": {
      "repo": "sdk-go",
      "version": "v2.1-beta",
      "public": true
    }
  }

Compare defining metadata as a regular object field versus a flattened field:

Comparison aspect

Regular object (dynamic mapping on)

Regular object (with dynamic: strict)

flattened (with top-level dynamic: strict)

Number of Mapping fields

Every new sub-key adds an independent field (the 2 tenants above already add 7 sub-paths); fields keep bloating, and after exceeding the cap (default 1000), writing new fields fails outright

Every sub-key of every tenant must be declared manually in advance; tenants cannot add fields themselves

Always occupies only 1 field, metadata (nesting depth within depth_limit), completely avoiding field bloat; tenants can freely add or remove sub-keys at any time without affecting each other

Same sub-key name with different types

(Tenant A version: 20, Tenant B version: "v2.1-beta")

After Tenant A writes the integer 20 first, metadata.version is locked to a numeric type; Tenant B passing a string fails to write with an error

The same conflict; the two types cannot coexist

Fully compatible: all leaf values are uniformly indexed as strings underneath, so both sides write normally

Reading _source returns

The original JSON is preserved

The original JSON is preserved

The original nested JSON is preserved as-is (reading back Tenant A, version is still 20; reading back Tenant B, still "v2.1-beta")

Recommended modeling pattern: keep "dynamic": "strict" at the top level to guard the core fixed fields shared by all tenants (such as title, created_at, and embedding), and consolidate all tenant-level custom fields into a single flattened field (such as metadata or custom_fields).

Typical use cases:

  • Multi-tenant SaaS custom fields: different tenants freely add extension attributes on tickets, products, or forms — configure and write on the fly with no schema changes, eliminating field bloat and cross-tenant type conflicts.

  • Heterogeneous metadata in AI knowledge bases (RAG): PDFs, web pages, code repositories, and tickets each carry different dept, repo, author, and tags, which can be used directly for vector KNN pre-filtering.

  • Agent memory and session-context tags: dynamically changing environment identifiers, tool-call tags, and status key-values — write and use on the fly, with exact filtering and terms group statistics.

For complete syntax details of flattened and dynamic, also refer to the Elasticsearch documentation: Flattened field type and Dynamic mapping.

2. Which queries does it support? Can it replace all regular fields?

It cannot replace all regular fields.

Because when flattened builds the index, it treats every leaf value in the object (whether the number 20, the boolean true, or the string "after-sales") uniformly as a non-analyzed, case-sensitive exact string (similar to keyword) for indexing. It is designed specifically for exact filtering and group statistics: it does not do text analysis, numeric/date magnitude comparison, or wildcard fuzzy matching.

flattened queries and aggregations supported

Taking the documents written by Tenants A and B above as examples, all of the following operations can be run directly on metadata:

Supported operation

Example syntax

Actual effect (using the two documents above)

Exact match by sub-path (term)

{"term": {"metadata.author.name": "alice"}}

Hits Tenant A "Refund policy guide"; it is case-sensitive, so searching "Alice" returns 0 hits.

Multi-value match by sub-path (terms)

{"terms": {"metadata.tags": ["vip", "urgent"]}}

Hits if the tags array contains any exact value (hits Tenant A "Refund policy guide").

Search the whole object without specifying a sub-key (top-level term)

{"term": {"metadata": "after-sales"}}

Queryable even without knowing which sub-key holds it: hits if any leaf value inside metadata exactly equals "after-sales".

Check whether a sub-key exists (exists)

{"exists": {"field": "metadata.repo"}}

Hits "API Auth Guide" in Tenant B and returns 0 hits in Tenant A (useful for filtering documents that have a tenant-specific attribute).

Exact whole-term match

{"match": {"metadata.dept": "after-sales"}}

Matches the whole string exactly (no analysis): searching "after-sales" hits, while searching only "after" returns 0 hits.

Vector KNN pre-filtering (knn.filter)

"filter": {"term": {"metadata.dept": "after-sales"}}

First narrow the scope by tenant custom attributes, then compute Top-K vector similarity within the matched documents.

Group statistics by sub-key (terms aggregation)

{"terms": {"field": "metadata.dept"}}

Counts documents per department for a tenant (for example, after writing the after-sales and logistics documents in section 3 below, returns after-sales: 1, logistics: 1).

Sort by sub-key (sort)

{"sort": [{"metadata.version": "asc"}]}

Sorted by string lexicographic order (for example, when both version: 20 and version: 5 exist, the string "20" sorts before "5", not by numeric magnitude).

What if you need full-text analysis, numeric ranges, or fuzzy search? (Field-type selection)

One-line rule: put tenant extension attributes that only need "equals / contains one of a few values / exists / group count" into flattened; fields that need analysis, magnitude comparison, range filtering, or fuzzy matching must be defined explicitly at the top level.

Your business need

Recommended field type

Notes and examples

Exact filtering and grouping for tenant-level custom fields, heterogeneous metadata, and dynamic tags

flattened

Occupies only 1 Mapping field; supports all exact queries in the table above, KNN filter, and terms aggregations.

Core fixed tags, categories, or statuses shared by all tenants

keyword

High-frequency shared filter fields should be defined explicitly at the top level — clearer semantics and better performance.

Full-text analyzed search, relevance scoring (BM25), or highlighting

text

For example, searching "return" should hit "Refund policy guide"; define the title/body explicitly as text.

Numeric magnitude comparison, date range filtering (range), numeric sorting, or metric statistics

long / double / date

For example, querying version >= 10 or filtering the last 7 days by created_at — define them as the corresponding strongly typed fields.

AI vector semantic search

dense_vector / sparse_vector

Vector fields must be defined explicitly at the top level.

Wildcard */? and regex matching

wildcard

For example, searching a product code *iph*16* or regex matching (see Wildcard and prefix fuzzy search: wildcard).

Prefix matching (prefix / match_bool_prefix)

A index_prefixes-enabled text

(or search_as_you_type / wildcard)

Complete titles or keywords by prefix (for how to configure, see Wildcard and prefix fuzzy search: wildcard).

Extension JSON that is only returned with document reads/writes and never needs filtering or aggregation

object ("enabled": false)

Not indexed, so writes and storage cost less.

3. Quick start: create, write, and query examples

The following uses the multi-tenant knowledge-base collection kb-multi-tenant as an example to show how to combine tenant-shared fixed fields (title, created_at, embedding) with tenant-level custom fields (metadata).

3.1 Create a Collection with a flattened field

Enable "dynamic": "strict" at the top level to reject undeclared fields, and declare only one metadata (flattened) field for tenant custom attributes:

CONSOLE

PUT /_slice_collection/kb-multi-tenant
{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "title": { "type": "text" },
      "created_at": { "type": "date" },
      "embedding": {
        "type": "dense_vector",
        "dims": 4,
        "index": true,
        "similarity": "cosine",
        "index_options": { "type": "bbq_disk" }
      },
      "metadata": {
        "type": "flattened",
        "depth_limit": 10,
        "ignore_above": 256
      }
    }
  }
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
  "$ES_ENDPOINT/_slice_collection/kb-multi-tenant" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "title": { "type": "text" },
      "created_at": { "type": "date" },
      "embedding": {
        "type": "dense_vector",
        "dims": 4,
        "index": true,
        "similarity": "cosine",
        "index_options": { "type": "bbq_disk" }
      },
      "metadata": {
        "type": "flattened",
        "depth_limit": 10,
        "ignore_above": 256
      }
    }
  }
}
JSON

GO

body := `{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "title": { "type": "text" },
      "created_at": { "type": "date" },
      "embedding": {
        "type": "dense_vector",
        "dims": 4,
        "index": true,
        "similarity": "cosine",
        "index_options": { "type": "bbq_disk" }
      },
      "metadata": {
        "type": "flattened",
        "depth_limit": 10,
        "ignore_above": 256
      }
    }
  }
}`
req, _ := http.NewRequestWithContext(ctx, "PUT", "/_slice_collection/kb-multi-tenant", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Perform(req)
if err != nil {
	log.Fatal(err)
}
resp.Body.Close()

PYTHON

client.perform_request(
    "PUT",
    "/_slice_collection/kb-multi-tenant",
    headers={"content-type": "application/json"},
    body={
        "mappings": {
            "dynamic": "strict",
            "properties": {
                "title": {"type": "text"},
                "created_at": {"type": "date"},
                "embedding": {
                    "type": "dense_vector",
                    "dims": 4,
                    "index": True,
                    "similarity": "cosine",
                    "index_options": {"type": "bbq_disk"},
                },
                "metadata": {
                    "type": "flattened",
                    "depth_limit": 10,
                    "ignore_above": 256,
                },
            },
        }
    },
)

JAVASCRIPT

await client.transport.request({
  method: 'PUT',
  path: '/_slice_collection/kb-multi-tenant',
  body: {
    mappings: {
      dynamic: 'strict',
      properties: {
        title: { type: 'text' },
        created_at: { type: 'date' },
        embedding: {
          type: 'dense_vector',
          dims: 4,
          index: true,
          similarity: 'cosine',
          index_options: { type: 'bbq_disk' },
        },
        metadata: {
          type: 'flattened',
          depth_limit: 10,
          ignore_above: 256,
        },
      },
    },
  },
})

JAVA

Request req = new Request("PUT", "/_slice_collection/kb-multi-tenant");
req.setJsonEntity("""
    {
      "mappings": {
        "dynamic": "strict",
        "properties": {
          "title": { "type": "text" },
          "created_at": { "type": "date" },
          "embedding": {
            "type": "dense_vector",
            "dims": 4,
            "index": true,
            "similarity": "cosine",
            "index_options": { "type": "bbq_disk" }
          },
          "metadata": {
            "type": "flattened",
            "depth_limit": 10,
            "ignore_above": 256
          }
        }
      }
    }
    """);
Response resp = restClient.performRequest(req);
EntityUtils.consumeQuietly(resp.getEntity());
Note

The example above sets depth_limit (maximum nesting depth, default 20) to 10, and ignore_above (maximum indexable value length) to 256 — these two values are examples; adjust them to your actual data. Exceeding the depth limit makes the whole document fail to write (400); oversized values are still kept in _source but are not eligible for filtering or aggregation (see section 4).

3.2 Write tenant-specific custom fields to two tenant Slices

tenant-a and tenant-b write completely different metadata structures, and metadata.version in tenant-a is the integer 20 and in tenant-b the string "v2.1-beta"; all write normally without adding any Mapping fields:

CONSOLE

POST /kb-multi-tenant/_bulk
{"index":{"_id":"1","_slice":"tenant-a"}}
{"title":"Refund policy guide","created_at":"2026-11-20T10:00:00Z","embedding":[0.9,0.1,0.0,0.0],"metadata":{"dept":"after-sales","version":20,"author":{"name":"alice","region":"hz"},"tags":["vip","refund"]}}
{"index":{"_id":"2","_slice":"tenant-a"}}
{"title":"Shipping fee standards","created_at":"2026-11-21T10:00:00Z","embedding":[0.85,0.15,0.0,0.0],"metadata":{"dept":"logistics","version":5,"author":{"name":"bob","region":"sh"},"tags":["normal"]}}
{"index":{"_id":"1","_slice":"tenant-b"}}
{"title":"API Auth Guide","created_at":"2026-11-22T10:00:00Z","embedding":[0.1,0.9,0.0,0.0],"metadata":{"repo":"sdk-go","version":"v2.1-beta","public":true,"env":"prod"}}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/kb-multi-tenant/_bulk" \
  -H 'Content-Type: application/x-ndjson' \
  --data-binary @- <<'NDJSON'
{"index":{"_id":"1","_slice":"tenant-a"}}
{"title":"Refund policy guide","created_at":"2026-11-20T10:00:00Z","embedding":[0.9,0.1,0.0,0.0],"metadata":{"dept":"after-sales","version":20,"author":{"name":"alice","region":"hz"},"tags":["vip","refund"]}}
{"index":{"_id":"2","_slice":"tenant-a"}}
{"title":"Shipping fee standards","created_at":"2026-11-21T10:00:00Z","embedding":[0.85,0.15,0.0,0.0],"metadata":{"dept":"logistics","version":5,"author":{"name":"bob","region":"sh"},"tags":["normal"]}}
{"index":{"_id":"1","_slice":"tenant-b"}}
{"title":"API Auth Guide","created_at":"2026-11-22T10:00:00Z","embedding":[0.1,0.9,0.0,0.0],"metadata":{"repo":"sdk-go","version":"v2.1-beta","public":true,"env":"prod"}}
NDJSON

GO

bulk := client.Bulk()
_ = bulk.IndexOp(
	types.IndexOperation{Index_: some.String("kb-multi-tenant"), Id_: some.String("1"), Routing: some.String("tenant-a")},
	map[string]any{
		"title": "Refund policy guide", "created_at": "2026-11-20T10:00:00Z", "embedding": []float32{0.9, 0.1, 0.0, 0.0},
		"metadata": map[string]any{"dept": "after-sales", "version": 20, "author": map[string]any{"name": "alice", "region": "hz"}, "tags": []string{"vip", "refund"}},
	},
)
_ = bulk.IndexOp(
	types.IndexOperation{Index_: some.String("kb-multi-tenant"), Id_: some.String("2"), Routing: some.String("tenant-a")},
	map[string]any{
		"title": "Shipping fee standards", "created_at": "2026-11-21T10:00:00Z", "embedding": []float32{0.85, 0.15, 0.0, 0.0},
		"metadata": map[string]any{"dept": "logistics", "version": 5, "author": map[string]any{"name": "bob", "region": "sh"}, "tags": []string{"normal"}},
	},
)
_ = bulk.IndexOp(
	types.IndexOperation{Index_: some.String("kb-multi-tenant"), Id_: some.String("1"), Routing: some.String("tenant-b")},
	map[string]any{
		"title": "API Auth Guide", "created_at": "2026-11-22T10:00:00Z", "embedding": []float32{0.1, 0.9, 0.0, 0.0},
		"metadata": map[string]any{"repo": "sdk-go", "version": "v2.1-beta", "public": true, "env": "prod"},
	},
)
bulkRes, err := bulk.Do(ctx)
if err != nil || bulkRes.Errors {
	log.Fatalf("Bulk write failed: err=%v, errors=%v", err, bulkRes != nil && bulkRes.Errors)
}

PYTHON

res = client.bulk(
    operations=[
        {"index": {"_index": "kb-multi-tenant", "_id": "1", "routing": "tenant-a"}},
        {
            "title": "Refund policy guide",
            "created_at": "2026-11-20T10:00:00Z",
            "embedding": [0.9, 0.1, 0.0, 0.0],
            "metadata": {"dept": "after-sales", "version": 20, "author": {"name": "alice", "region": "hz"}, "tags": ["vip", "refund"]},
        },
        {"index": {"_index": "kb-multi-tenant", "_id": "2", "routing": "tenant-a"}},
        {
            "title": "Shipping fee standards",
            "created_at": "2026-11-21T10:00:00Z",
            "embedding": [0.85, 0.15, 0.0, 0.0],
            "metadata": {"dept": "logistics", "version": 5, "author": {"name": "bob", "region": "sh"}, "tags": ["normal"]},
        },
        {"index": {"_index": "kb-multi-tenant", "_id": "1", "routing": "tenant-b"}},
        {
            "title": "API Auth Guide",
            "created_at": "2026-11-22T10:00:00Z",
            "embedding": [0.1, 0.9, 0.0, 0.0],
            "metadata": {"repo": "sdk-go", "version": "v2.1-beta", "public": True, "env": "prod"},
        },
    ]
)
assert not res["errors"]

JAVASCRIPT

const res = await client.bulk({
  operations: [
    { index: { _index: 'kb-multi-tenant', _id: '1', routing: 'tenant-a' } },
    {
      title: 'Refund policy guide',
      created_at: '2026-11-20T10:00:00Z',
      embedding: [0.9, 0.1, 0.0, 0.0],
      metadata: { dept: 'after-sales', version: 20, author: { name: 'alice', region: 'hz' }, tags: ['vip', 'refund'] },
    },
    { index: { _index: 'kb-multi-tenant', _id: '2', routing: 'tenant-a' } },
    {
      title: 'Shipping fee standards',
      created_at: '2026-11-21T10:00:00Z',
      embedding: [0.85, 0.15, 0.0, 0.0],
      metadata: { dept: 'logistics', version: 5, author: { name: 'bob', region: 'sh' }, tags: ['normal'] },
    },
    { index: { _index: 'kb-multi-tenant', _id: '1', routing: 'tenant-b' } },
    {
      title: 'API Auth Guide',
      created_at: '2026-11-22T10:00:00Z',
      embedding: [0.1, 0.9, 0.0, 0.0],
      metadata: { repo: 'sdk-go', version: 'v2.1-beta', public: true, env: 'prod' },
    },
  ],
})
if (res.errors) throw new Error('Bulk has failed items')

JAVA

BulkResponse bulkRes = client.bulk(b -> b
    .operations(op -> op.index(i -> i.index("kb-multi-tenant").id("1").routing("tenant-a")
        .document(Map.of(
            "title", "Refund policy guide",
            "created_at", "2026-11-20T10:00:00Z",
            "embedding", List.of(0.9f, 0.1f, 0.0f, 0.0f),
            "metadata", Map.of("dept", "after-sales", "version", 20, "author", Map.of("name", "alice", "region", "hz"), "tags", List.of("vip", "refund"))
        ))))
    .operations(op -> op.index(i -> i.index("kb-multi-tenant").id("2").routing("tenant-a")
        .document(Map.of(
            "title", "Shipping fee standards",
            "created_at", "2026-11-21T10:00:00Z",
            "embedding", List.of(0.85f, 0.15f, 0.0f, 0.0f),
            "metadata", Map.of("dept", "logistics", "version", 5, "author", Map.of("name", "bob", "region", "sh"), "tags", List.of("normal"))
        ))))
    .operations(op -> op.index(i -> i.index("kb-multi-tenant").id("1").routing("tenant-b")
        .document(Map.of(
            "title", "API Auth Guide",
            "created_at", "2026-11-22T10:00:00Z",
            "embedding", List.of(0.1f, 0.9f, 0.0f, 0.0f),
            "metadata", Map.of("repo", "sdk-go", "version", "v2.1-beta", "public", true, "env", "prod")
        ))))
);
if (bulkRes.errors()) {
    throw new IllegalStateException("Bulk has failed items");
}
Note

After the writes complete, call GET /kb-multi-tenant/_mapping: you can see that properties still contains only the 4 fields title, created_at, embedding, and metadata, with no extra dynamic fields generated; if a document passes an undeclared new field at the top level, it is still rejected by "dynamic": "strict" with 400.

3.3 Exact filtering, vector KNN pre-filtering, and group aggregation

After waiting a few seconds for the automatic background refresh, you can run exact filtering by metadata sub-paths, vector-search pre-filtering, and terms group aggregations:

CONSOLE

// 1. Exact filter by nested sub-path (hits document 1 of tenant-a)
POST /kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false
{
  "query": {
    "term": { "metadata.author.name": "alice" }
  }
}

// 2. Vector KNN search + flattened metadata filter (recalls only after-sales department documents)
POST /kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false
{
  "knn": {
    "field": "embedding",
    "query_vector": [0.9, 0.1, 0.0, 0.0],
    "k": 5,
    "num_candidates": 50,
    "filter": {
      "term": { "metadata.dept": "after-sales" }
    }
  }
}

// 3. Terms aggregation by a flattened sub-key (returns after-sales: 1, logistics: 1)
POST /kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false
{
  "size": 0,
  "aggs": {
    "by_dept": {
      "terms": { "field": "metadata.dept" }
    }
  }
}

CURL

# 1. Exact filter by nested sub-path
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data '{"query":{"term":{"metadata.author.name":"alice"}}}'

# 2. Vector KNN search + flattened metadata filter
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data '{"knn":{"field":"embedding","query_vector":[0.9,0.1,0.0,0.0],"k":5,"num_candidates":50,"filter":{"term":{"metadata.dept":"after-sales"}}}}'

# 3. Terms aggregation by a flattened sub-key
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data '{"size":0,"aggs":{"by_dept":{"terms":{"field":"metadata.dept"}}}}'

GO

// 1. Exact filter by nested sub-path
res1, err := client.Search().
	Index("kb-multi-tenant").
	Routing("tenant-a").
	AllowPartialSearchResults(false).
	Query(&types.Query{Term: map[string]types.TermQuery{"metadata.author.name": {Value: "alice"}}}).
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(len(res1.Hits.Hits))

// 2. Vector KNN search + flattened metadata filter
res2, err := client.Search().
	Index("kb-multi-tenant").
	Routing("tenant-a").
	AllowPartialSearchResults(false).
	Knn(&types.KnnSearch{
		Field:         "embedding",
		QueryVector:   []float32{0.9, 0.1, 0.0, 0.0},
		K:             some.Int(5),
		NumCandidates: some.Int(50),
		Filter:        []types.Query{{Term: map[string]types.TermQuery{"metadata.dept": {Value: "after-sales"}}}},
	}).
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(len(res2.Hits.Hits))

// 3. Terms aggregation by a flattened sub-key
res3, err := client.Search().
	Index("kb-multi-tenant").
	Routing("tenant-a").
	AllowPartialSearchResults(false).
	Size(0).
	Aggregations(map[string]types.Aggregations{
		"by_dept": {Terms: &types.TermsAggregation{Field: some.String("metadata.dept")}},
	}).
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res3.Aggregations["by_dept"])

PYTHON

# 1. Exact filter by nested sub-path
res1 = client.search(
    index="kb-multi-tenant",
    routing="tenant-a",
    allow_partial_search_results=False,
    query={"term": {"metadata.author.name": "alice"}},
)

# 2. Vector KNN search + flattened metadata filter
res2 = client.search(
    index="kb-multi-tenant",
    routing="tenant-a",
    allow_partial_search_results=False,
    knn={
        "field": "embedding",
        "query_vector": [0.9, 0.1, 0.0, 0.0],
        "k": 5,
        "num_candidates": 50,
        "filter": {"term": {"metadata.dept": "after-sales"}},
    },
)

# 3. Terms aggregation by a flattened sub-key
res3 = client.search(
    index="kb-multi-tenant",
    routing="tenant-a",
    allow_partial_search_results=False,
    size=0,
    aggs={"by_dept": {"terms": {"field": "metadata.dept"}}},
)

JAVASCRIPT

// 1. Exact filter by nested sub-path
const res1 = await client.search({
  index: 'kb-multi-tenant',
  routing: 'tenant-a',
  allow_partial_search_results: false,
  query: { term: { 'metadata.author.name': 'alice' } },
})

// 2. Vector KNN search + flattened metadata filter
const res2 = await client.search({
  index: 'kb-multi-tenant',
  routing: 'tenant-a',
  allow_partial_search_results: false,
  knn: {
    field: 'embedding',
    query_vector: [0.9, 0.1, 0.0, 0.0],
    k: 5,
    num_candidates: 50,
    filter: { term: { 'metadata.dept': 'after-sales' } },
  },
})

// 3. Terms aggregation by a flattened sub-key
const res3 = await client.search({
  index: 'kb-multi-tenant',
  routing: 'tenant-a',
  allow_partial_search_results: false,
  size: 0,
  aggs: { by_dept: { terms: { field: 'metadata.dept' } } },
})

JAVA

// 1. Exact filter by nested sub-path
SearchResponse<Map> res1 = client.search(s -> s
    .index("kb-multi-tenant")
    .routing("tenant-a")
    .allowPartialSearchResults(false)
    .query(q -> q.term(t -> t.field("metadata.author.name").value("alice"))),
    Map.class);

// 2. Vector KNN search + flattened metadata filter
SearchResponse<Map> res2 = client.search(s -> s
    .index("kb-multi-tenant")
    .routing("tenant-a")
    .allowPartialSearchResults(false)
    .knn(k -> k
        .field("embedding")
        .queryVector(List.of(0.9f, 0.1f, 0.0f, 0.0f))
        .k(5)
        .numCandidates(50)
        .filter(f -> f.term(t -> t.field("metadata.dept").value("after-sales")))),
    Map.class);

// 3. Terms aggregation by a flattened sub-key
SearchResponse<Void> res3 = client.search(s -> s
    .index("kb-multi-tenant")
    .routing("tenant-a")
    .allowPartialSearchResults(false)
    .size(0)
    .aggregations("by_dept", a -> a.terms(t -> t.field("metadata.dept"))),
    Void.class);

Expected results:

  • Query 1 (filter by metadata.author.name = "alice"): returns 1 document (_id: "1", title: "Refund policy guide"); changing "alice" to "Alice" returns 0 hits because matching is case-sensitive.

  • Query 2 (vector KNN + metadata.dept = "after-sales" filter): recalls only document 1 of the after-sales department and excludes document 2 of the logistics department.

  • Query 3 (group aggregation by metadata.dept): aggregations.by_dept.buckets returns [{"key": "after-sales", "doc_count": 1}, {"key": "logistics", "doc_count": 1}].

Try more in Dev Tools (top-level keyless match, exists, and lexicographic sorting):

// 1. Without specifying a sub-key, match any value inside metadata equal to "after-sales" (hits document 1)
POST /kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false
{
  "query": { "term": { "metadata": "after-sales" } }
}

// 2. Check whether a sub-key exists (hits "API Auth Guide" in tenant-b; returns 0 hits in tenant-a)
POST /kb-multi-tenant/_search?_slice=tenant-b&allow_partial_search_results=false
{
  "query": { "exists": { "field": "metadata.repo" } }
}

// 3. Sort by metadata.version ascending (observe string lexicographic order: version=20 sorts before version=5)
POST /kb-multi-tenant/_search?_slice=tenant-a&allow_partial_search_results=false
{
  "query": { "match_all": {} },
  "sort": [{ "metadata.version": "asc" }],
  "_source": ["title", "metadata.version"]
}

// 4. Clean up the sample collection (optional)
DELETE /_slice_collection/kb-multi-tenant

4. Usage notes

  • Set depth_limit and ignore_above sensibly:

    • depth_limit defaults to 20, the maximum nesting depth allowed per document; exceeding it makes the whole document return 400. When tightening it as needed (e.g. 5-10), make sure it is not lower than the tenants actual maximum nesting depth.

    • ignore_above has no length limit by default; a single leaf value whose key name plus value exceeds 32766 bytes makes the whole document fail to write. Set ignore_above explicitly (e.g. 256 or 1024) to avoid write errors from oversized values and control index size — leaf values longer than this are not indexed (unusable for exact filtering or aggregation) but are still kept in _source and readable by ID.

  • Case-insensitive matching: flattened leaf values are case-sensitive by default; if your business needs case-insensitive filtering, normalize to lowercase on the application side before writing.

  • Move high-frequency aggregation keys to a top-level keyword: the flattened field builds one set of global ordinals for terms aggregations and sorting across the whole field (covering every sub-key of every tenant); for key attributes needing frequent grouping, define them explicitly as top-level keyword fields.

  • Sub-key naming and arrays of objects: avoid dots . in dynamic key names (they are parsed as nested paths in queries), and do not mix scalars with nested objects under the same path; arrays of objects are flattened, so correlations between multiple fields inside one array element are not preserved.