Best practices

Updated at:

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 name field uses ik_max_word to improve recall, paired with a keyword subfield for exact sorting.

  • Place filter conditions (stock, price range, brand) in the filter clause to benefit from caching.

  • Use aggregations for faceted navigation (brand, price range, category).

  • Set _source to 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_interval to 5s to balance real-time visibility and write performance.

  • Set "index": false on the exception field (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

  1. Question: call an embedding model to generate the query vector.

  2. Send a hybrid search (vector plus full-text) to the Search engine.

  3. Retrieve the top-K relevant document chunks.

  4. Concatenate the retrieved results into the prompt as context.

  5. 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 cosinesimil distance metric, which is suitable for normalized text embeddings.

  • In hybrid search, use the boost parameter to balance the weights of vector and full-text search.

  • Set _source to return only content and metadata, excluding the embedding field to save bandwidth.

  • Use pre-filtering by source or tags to narrow the search scope.

General best practices

Index naming conventions

Scenario

Naming format

Example

Business index

<business>-<environment>

products-prod, users-staging

Log index

<application>-logs-<date>

order-logs-2025.06.01

Vector index

<knowledge-base>-vectors

docs-vectors

Write best practices

  • Always use the _bulk API 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 filter instead of must for filter conditions that do not need scoring.

  • Return only necessary fields (_source filtering).

  • Avoid deep pagination with from > 10000.

  • For high-frequency queries, consider prewarming the cache. Filters are automatically cached after the first query.