Best practices
This topic describes usage recommendations and solution design references for the PolarDB-X intelligent search in typical business scenarios.
Scenario 1: E-commerce product search
Scenario description
E-commerce product search must support keyword retrieval, attribute filtering, sorting, and faceted statistics, with millisecond-level response times.
Index design
curl -XPUT "http://<Search engine endpoint>:<port>/products" \
-u "<username>:<password>" -k \
-H "Content-Type: application/json" \
-d '{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"product_analyzer": {
"type": "custom",
"tokenizer": "ik_max_word",
"filter": ["lowercase"]
}
}
}
},
"mappings": {
"dynamic": "strict",
"properties": {
"name": { "type": "text", "analyzer": "product_analyzer", "fields": { "keyword": { "type": "keyword" } } },
"description": { "type": "text", "analyzer": "ik_smart" },
"category": { "type": "keyword" },
"brand": { "type": "keyword" },
"tags": { "type": "keyword" },
"price": { "type": "float" },
"sales_count": { "type": "integer" },
"rating": { "type": "float" },
"in_stock": { "type": "boolean" },
"created_at": { "type": "date" },
"image_url": { "type": "keyword", "index": false }
}
}
}'
Search query example
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "wireless noise-cancelling headphones",
"fields": ["name^3", "description", "tags^2"],
"type": "best_fields"
}
}
],
"filter": [
{ "term": { "in_stock": true } },
{ "range": { "price": { "gte": 200, "lte": 2000 } } },
{ "term": { "brand": "Sony" } }
]
}
},
"sort": [ "_score", { "sales_count": "desc" } ],
"_source": ["name", "price", "image_url", "brand", "rating"],
"size": 20,
"aggs": {
"brands": { "terms": { "field": "brand", "size": 20 } },
"categories": { "terms": { "field": "category", "size": 10 } },
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{ "key": "0-200", "to": 200 },
{ "key": "200-500", "from": 200, "to": 500 },
{ "key": "500-1000", "from": 500, "to": 1000 },
{ "key": "1000+", "from": 1000 }
]
}
}
},
"highlight": { "fields": { "name": { "number_of_fragments": 0 } } }
}
Design points
-
The
namefield usesik_max_wordto improve recall, paired with akeywordsubfield for exact sorting. -
Place filter conditions (stock, price range, brand) in the
filterclause to benefit from caching. -
Use aggregations for faceted navigation (brand, price range, category).
-
Set
_sourceto return only fields required for list display to reduce data transfer.
Scenario 2: Log and observability analysis
Scenario description
Application logs are written in real time and support retrieval by time range, keyword search, and statistical analysis.
Index design
Use an index template with daily rollover indexes:
curl -XPUT "http://<Search engine endpoint>:<port>/_index_template/app-logs-template" \
-u "<username>:<password>" -k \
-H "Content-Type: application/json" \
-d '{
"index_patterns": ["app-logs-*"],
"priority": 100,
"template": {
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"refresh_interval": "5s"
},
"mappings": {
"dynamic": "strict",
"properties": {
"@timestamp": { "type": "date" },
"level": { "type": "keyword" },
"service": { "type": "keyword" },
"host": { "type": "keyword" },
"trace_id": { "type": "keyword" },
"message": { "type": "text" },
"logger": { "type": "keyword" },
"exception": { "type": "text", "index": false }
}
}
}
}'
curl -XPUT "http://<Search engine endpoint>:<port>/_plugins/_ism/policies/logs-lifecycle" \
-u "<username>:<password>" -k \
-H "Content-Type: application/json" \
-d '{
"policy": {
"description": "Log lifecycle: 7 days hot, delete after 30 days",
"default_state": "hot",
"states": [
{
"name": "hot",
"actions": [],
"transitions": [
{ "state_name": "warm", "conditions": { "min_index_age": "7d" } }
]
},
{
"name": "warm",
"actions": [
{ "replica_count": { "number_of_replicas": 0 } },
{ "force_merge": { "max_num_segments": 1 } }
],
"transitions": [
{ "state_name": "delete", "conditions": { "min_index_age": "30d" } }
]
},
{
"name": "delete",
"actions": [{ "delete": {} }]
}
],
"ism_template": [
{ "index_patterns": ["app-logs-*"], "priority": 100 }
]
}
}'
Design points
-
Roll indexes over by date (
app-logs-2025.06.01) for easy time-range queries and cleanup. -
Use an ISM policy to automatically manage the lifecycle and avoid unlimited storage growth.
-
Set
refresh_intervalto 5s to balance real-time visibility and write performance. -
Set
"index": falseon theexceptionfield (stored but not indexed) to save space.
Scenario 3: AI vector search and RAG
Scenario description
Split documents into chunks, generate vector embeddings, and store them in the Search engine. Use semantic similarity search to provide context for a large language model (LLM), a pattern known as Retrieval-Augmented Generation (RAG).
Index design
curl -XPUT "http://<Search engine endpoint>:<port>/knowledge-base" \
-u "<username>:<password>" -k \
-H "Content-Type: application/json" \
-d '{
"settings": {
"index.knn": true,
"number_of_shards": 2,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"doc_id": { "type": "keyword" },
"chunk_id": { "type": "integer" },
"title": { "type": "text", "analyzer": "ik_max_word" },
"content": { "type": "text", "analyzer": "ik_max_word" },
"embedding": {
"type": "knn_vector",
"dimension": 1024,
"method": {
"engine": "faiss",
"name": "hnsw",
"space_type": "cosinesimil",
"parameters": { "ef_construction": 256, "m": 16 }
}
},
"source": { "type": "keyword" },
"tags": { "type": "keyword" },
"created_at": { "type": "date" }
}
}
}'
RAG search query (hybrid search)
Combine vector semantic similarity with full-text keyword matching to improve recall quality:
{
"size": 5,
"query": {
"bool": {
"should": [
{ "knn": { "embedding": { "vector": [0.01, -0.03, 0.12], "k": 10 } } },
{ "match": { "content": { "query": "Principles of distributed transactions in PolarDB-X", "boost": 0.3 } } }
],
"filter": [
{ "term": { "source": "technical-docs" } }
]
}
},
"_source": ["title", "content", "doc_id", "chunk_id"]
}
Application-layer RAG workflow
-
Question: call an embedding model to generate the query vector.
-
Send a hybrid search (vector plus full-text) to the Search engine.
-
Retrieve the top-K relevant document chunks.
-
Concatenate the retrieved results into the prompt as context.
-
Call the LLM to generate the final answer.
Design points
-
Split documents into fixed-length chunks (recommended 500-1000 characters), with appropriate overlap between adjacent chunks (10%-20%).
-
Use the
cosinesimildistance metric, which is suitable for normalized text embeddings. -
In hybrid search, use the
boostparameter to balance the weights of vector and full-text search. -
Set
_sourceto return onlycontentand metadata, excluding theembeddingfield to save bandwidth. -
Use pre-filtering by
sourceortagsto narrow the search scope.
General best practices
Index naming conventions
|
Scenario |
Naming format |
Example |
|
Business index |
|
|
|
Log index |
|
|
|
Vector index |
|
|
Write best practices
-
Always use the
_bulkAPI for batch writes. Do not write documents one by one. -
Assign deterministic document IDs (such as a business primary key) for easier deduplication and updates.
-
Implement a retry mechanism for write failures. Handle 429 (throttling) and 503 (unavailable) responses.
Query best practices
-
Use
filterinstead ofmustfor filter conditions that do not need scoring. -
Return only necessary fields (
_sourcefiltering). -
Avoid deep pagination with
from> 10000. -
For high-frequency queries, consider prewarming the cache. Filters are automatically cached after the first query.