Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

43.7 KB
Raw Blame
<!DOCTYPE html>
<html lang="en" data-theme="day">
<head>
<!-- ga4:begin — generated by scripts/seo/seo_head.py · do not hand-edit -->
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-Z77ETCDJYL"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-Z77ETCDJYL');
</script>
<!-- ga4:end -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XERJ · Docs · Recipe · Semantic search &amp; RAG</title>
<meta name="description" content="Semantic search and RAG retrieval with XERJ — map a field as semantic_text, auto-embed on ingest, retrieve by meaning, with no separate vector database.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@400;700;800;900&family=Inter:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' fill='%230b0b0d'/><text x='50' y='68' font-size='60' font-family='Big Shoulders Display,sans-serif' font-weight='900' fill='%23ffc400' text-anchor='middle'>X</text></svg>">
<script src="/theme.js"></script>
<link rel="stylesheet" href="/style.css?v=90f643e">
<!-- seo:begin — generated by scripts/seo/fix_heads.py · do not hand-edit -->
<link rel="canonical" href="https://xerj.org/docs/recipes/semantic-search-rag">
<meta property="og:site_name" content="XERJ.ai">
<meta property="og:type" content="article">
<meta property="og:title" content="XERJ · Docs · Recipe · Semantic search &amp; RAG">
<meta property="og:description" content="Semantic search and RAG retrieval with XERJ — map a field as semantic_text, auto-embed on ingest, retrieve by meaning, with no separate vector database.">
<meta property="og:url" content="https://xerj.org/docs/recipes/semantic-search-rag">
<meta property="og:image" content="https://xerj.org/og/xerj-card.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="XERJ.ai — the search engine built for AI agents">
<meta property="og:locale" content="en_US">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="XERJ · Docs · Recipe · Semantic search &amp; RAG">
<meta name="twitter:description" content="Semantic search and RAG retrieval with XERJ — map a field as semantic_text, auto-embed on ingest, retrieve by meaning, with no separate vector database.">
<meta name="twitter:image" content="https://xerj.org/og/xerj-card.png">
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Organization",
  "@id": "https://xerj.org/#organization",
  "name": "XERJ",
  "alternateName": "XERJ.ai",
  "url": "https://xerj.org/",
  "logo": "https://xerj.org/brandbook/xerj-mark.svg",
  "description": "A new way for AI to search for data: one local Rust binary that indexes your code, docs, specs and logs, plus Corpus Hub packs, and returns cited answers.",
  "sameAs": [
    "https://github.com/xerj-org/xerj",
    "https://x.com/xerj_org"
  ]
}
</script>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "WebSite",
  "@id": "https://xerj.org/#website",
  "name": "XERJ.ai",
  "url": "https://xerj.org/",
  "inLanguage": "en",
  "publisher": {
    "@id": "https://xerj.org/#organization"
  }
}
</script>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "TechArticle",
  "headline": "XERJ · Docs · Recipe · Semantic search & RAG",
  "description": "Semantic search and RAG retrieval with XERJ — map a field as semantic_text, auto-embed on ingest, retrieve by meaning, with no separate vector database.",
  "url": "https://xerj.org/docs/recipes/semantic-search-rag",
  "image": "https://xerj.org/og/xerj-card.png",
  "inLanguage": "en",
  "datePublished": "2026-07-08",
  "dateModified": "2026-09-08",
  "author": {
    "@id": "https://xerj.org/#organization"
  },
  "publisher": {
    "@id": "https://xerj.org/#organization"
  },
  "isPartOf": {
    "@id": "https://xerj.org/#website"
  },
  "mainEntityOfPage": {
    "@type": "WebPage",
    "@id": "https://xerj.org/docs/recipes/semantic-search-rag"
  }
}
</script>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {
      "@type": "ListItem",
      "position": 1,
      "name": "Home",
      "item": "https://xerj.org/"
    },
    {
      "@type": "ListItem",
      "position": 2,
      "name": "Docs",
      "item": "https://xerj.org/docs/"
    },
    {
      "@type": "ListItem",
      "position": 3,
      "name": "Recipes",
      "item": "https://xerj.org/docs/recipes/"
    },
    {
      "@type": "ListItem",
      "position": 4,
      "name": "Semantic search & RAG"
    }
  ]
}
</script>
<!-- seo:end -->
</head>
<body>


<nav class="nav" aria-label="Primary">
  <a href="/" class="brand">XERJ</a>
  <a href="/product">PRODUCT</a>
  <a href="/use-cases">USE CASES</a>
  <a href="/answers/">ANSWERS</a>
  <a href="/benchmarks/">BENCHMARKS</a>
  <a href="/blog/">BLOG</a>
  <span class="spacer"></span>
  <a href="/for-agents">FOR AGENTS</a>
  <a href="/docs/" class="active">DOCS</a>
  <a href="/playground">DASHBOARDS</a>
  <a href="https://hub.xerj.org" rel="external">HUB</a>
  <a class="nav-stars" href="https://github.com/xerj-org/xerj" rel="external" title="XERJ on GitHub" aria-label="XERJ on GitHub, 14,225 stars"><svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg><span class="nav-stars-n" data-gh-stars="14225">★ 14.2k</span></a>
  <a href="https://x.com/xerj_org" rel="external" title="XERJ on X" style="display:inline-flex;align-items:center"><svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg></a>
  <a href="https://discord.com/invite/yetXFusXfs" rel="external" title="XERJ on Discord" style="display:inline-flex;align-items:center"><svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M20.317 4.37a19.79 19.79 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.74 19.74 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 00.031.057 19.9 19.9 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.1 13.1 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.3 12.3 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.84 19.84 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg></a>
  <span class="theme">
    <button type="button" data-theme="day" class="active">DAY</button>
    <span class="dash">·</span>
    <button type="button" data-theme="night">NIGHT</button>
  </span>
</nav>

<div class="docs-search" id="docsSearch">
  <input type="text" id="docsSearchInput" placeholder="Search docs · keys, flags, endpoints, playbooks…" aria-label="Search docs" autocomplete="off" spellcheck="false">
  <span class="hint">⌘ K</span>
  <div class="results" id="docsSearchResults" aria-live="polite"></div>
</div>

<div class="docs-shell">
<nav class="docs-nav" aria-label="Docs">  <div class="group">
    <span class="label">START</span>
    <a href="/docs/" class=""><span class="eyebrow">01</span>Overview</a>
      <a href="/docs/quickstart" class=""><span class="eyebrow">02</span>Quickstart</a>
      <a href="/docs/install" class=""><span class="eyebrow">03</span>Install</a>
      <a href="/docs/migration-from-es" class=""><span class="eyebrow">04</span>Migrate from ES</a>
  </div>
  <div class="group">
    <span class="label">REFERENCE</span>
    <a href="/docs/cli" class=""><span class="eyebrow">01</span>CLI</a>
      <a href="/docs/config" class=""><span class="eyebrow">02</span>Config TOML</a>
      <a href="/docs/env" class=""><span class="eyebrow">03</span>Environment</a>
      <a href="/docs/api-native" class=""><span class="eyebrow">04</span>Native REST API</a>
      <a href="/docs/api-es-compat" class=""><span class="eyebrow">05</span>ES-compat API</a>
  </div>
  <div class="group">
    <span class="label">DATA MODEL</span>
    <a href="/docs/queries" class=""><span class="eyebrow">01</span>Query types</a>
      <a href="/docs/aggregations" class=""><span class="eyebrow">02</span>Aggregations</a>
      <a href="/docs/analyzers" class=""><span class="eyebrow">03</span>Analyzers</a>
      <a href="/docs/vectors" class=""><span class="eyebrow">04</span>Vectors & kNN</a>
  </div>
  <div class="group">
    <span class="label">ENGINE</span>
    <a href="/docs/ingest" class=""><span class="eyebrow">01</span>Ingest pipelines</a>
      <a href="/docs/storage" class=""><span class="eyebrow">02</span>Storage & WAL</a>
      <a href="/docs/compression" class=""><span class="eyebrow">03</span>Compression</a>
      <a href="/docs/clustering" class=""><span class="eyebrow">04</span>Clustering</a>
      <a href="/docs/metrics" class=""><span class="eyebrow">05</span>Metrics</a>
      <a href="/docs/security" class=""><span class="eyebrow">06</span>Auth & TLS</a>
  </div>
  <div class="group">
    <span class="label">OPERATIONS</span>
    <a href="/docs/operations" class=""><span class="eyebrow">01</span>Running in production</a>
      <a href="/docs/backup-restore" class=""><span class="eyebrow">02</span>Backup & restore</a>
      <a href="/docs/upgrades" class=""><span class="eyebrow">03</span>Upgrades</a>
      <a href="/docs/troubleshooting" class=""><span class="eyebrow">04</span>Troubleshooting</a>
  </div>
  <div class="group">
    <span class="label">PLAYBOOKS</span>
    <a href="/docs/playbooks/siem" class=""><span class="eyebrow">01</span>SIEM</a>
      <a href="/docs/playbooks/log-analytics" class=""><span class="eyebrow">02</span>Log analytics</a>
      <a href="/docs/playbooks/vector-search" class=""><span class="eyebrow">03</span>Vector · RAG</a>
      <a href="/docs/playbooks/full-text" class=""><span class="eyebrow">04</span>Full-text search</a>
      <a href="/docs/playbooks/observability" class=""><span class="eyebrow">05</span>Observability</a>
  </div>
  <div class="group">
    <span class="label">RECIPES</span>
    <a href="/docs/recipes/" class=""><span class="eyebrow">00</span>All recipes</a>
    <a href="/docs/recipes/semantic-search-rag" class="active"><span class="eyebrow">01</span>Semantic search &amp; RAG</a>
    <a href="/docs/recipes/agentic-memory" class=""><span class="eyebrow">02</span>Agent memory</a>
    <a href="/docs/recipes/passage-retrieval" class=""><span class="eyebrow">03</span>Passage retrieval</a>
    <a href="/docs/recipes/vector-search-knn" class=""><span class="eyebrow">04</span>Vector search &middot; kNN</a>
    <a href="/docs/recipes/vector-quantization" class=""><span class="eyebrow">05</span>Vector quantization</a>
    <a href="/docs/recipes/hybrid-search" class=""><span class="eyebrow">06</span>Hybrid search</a>
    <a href="/docs/recipes/log-analytics" class=""><span class="eyebrow">07</span>Log analytics</a>
    <a href="/docs/recipes/anomaly-detection" class=""><span class="eyebrow">08</span>Anomaly detection</a>
    <a href="/docs/recipes/continuous-anomaly-datafeeds" class=""><span class="eyebrow">09</span>Anomaly datafeeds</a>
    <a href="/docs/recipes/migrate-from-elasticsearch" class=""><span class="eyebrow">10</span>Migrate from ES</a>
  </div>
</nav>

<main class="docs-content">
  <!-- Print-only branded header (hidden on screen, visible in PDF) -->
  <div class="print-header" style="display:none;">XERJ</div>

  <div class="breadcrumb"><a href="/docs/">DOCS</a><span class="sep">·</span><a href="/docs/recipes/">RECIPES</a><span class="sep">·</span>SEMANTIC SEARCH &amp; RAG
    <button class="pdf-btn" onclick="window.print()" title="Save this page as PDF">
      <svg viewBox="0 0 24 24"><path d="M12 3v12M12 15l-4-4M12 15l4-4"/><path d="M4 17v2a2 2 0 002 2h12a2 2 0 002-2v-2"/></svg>
      PDF
    </button>
  </div>
  <div class="kicker"><span>RECIPE · 01</span></div>
  <h1>Semantic search &amp; RAG</h1>


  <p><strong>Goal:</strong> you have a knowledge base (support docs, product FAQs, policy pages) and you want an LLM to answer questions <em>grounded</em> in it. The retrieval half of RAG — "find the passages that mean the same thing as the user's question" — normally means standing up a separate vector database, an embedding service, and glue code to keep them in sync with your search index.</p>

  <p>With XERJ you don't. You map one field as <code class="inline">semantic_text</code>, ingest your docs with a normal <code class="inline">_bulk</code>, and XERJ <strong>embeds each document on ingest</strong> with a built-in, zero-config embedder. Then a <code class="inline">semantic</code> query retrieves by meaning from the same index you already full-text search. One engine, one wire protocol (Elasticsearch 8.x), no extra moving parts.</p>

  <p>This recipe indexes a tiny KB, retrieves passages with paraphrased questions (different words, same meaning), assembles the context bundle you'd hand an LLM, and is honest about where the built-in lexical embedder stops and a real neural endpoint takes over.</p>

  <hr>

  <h2>1. Map one field as <code class="inline">semantic_text</code></h2>
<pre class="code">curl -X PUT localhost:9200/kb -H 'Content-Type: application/json' -d '{
  "mappings": {
    "properties": {
      "title": { "type": "text" },
      "body":  { "type": "semantic_text" }
    }
  }
}'</pre>

  <p><code class="inline">body</code> is now auto-embedded. On ingest XERJ vectorizes the field's text into a companion vector field (<code class="inline">body_vector</code>, 384 dims by default, cosine similarity, served by exact kNN) — you never call an embedding API yourself. No <code class="inline">dense_vector</code> declaration, no dimension bookkeeping, no second datastore.</p>

  <h2>2. Ingest with a plain <code class="inline">_bulk</code></h2>
  <p>Nothing special — the embedding happens under the hood:</p>
<pre class="code">curl -X POST localhost:9200/_bulk -H 'Content-Type: application/x-ndjson' --data-binary '
{"index":{"_index":"kb","_id":"kb-1"}}
{"title":"Rotating an API key","body":"To change your API credentials, open Settings, choose Security, and click Regenerate token. The old token stops working immediately."}
{"index":{"_index":"kb","_id":"kb-2"}}
{"title":"Refund policy","body":"Customers can request their money back within 30 days of purchase. Refunds are issued to the original payment method within five business days."}
'</pre>

  <h2>3. Retrieve by meaning with the <code class="inline">semantic</code> query</h2>
  <p>The user's question rarely uses your doc's exact words. A <code class="inline">match</code> query on <code class="inline">"get my money back after buying"</code> returns <strong>nothing</strong> — none of those tokens are in the "Refund policy" doc analyzed the same way. The <code class="inline">semantic</code> query retrieves it anyway:</p>
<pre class="code">curl localhost:9200/kb/_search -H 'Content-Type: application/json' -d '{
  "size": 2,
  "query": { "semantic": { "field": "body", "query": "how do I regenerate my API token", "k": 2 } }
}'</pre>

  <p>Real response (trimmed):</p>
<pre class="code">{
  "hits": {
    "hits": [
      {
        "_id": "kb-1",
        "_score": 0.6625697,
        "_source": {
          "title": "Rotating an API key",
          "body": "To change your API credentials, open Settings, choose Security, and click Regenerate token. The old token stops working immediately.",
          "body_vector": [ 0.0, 0.0, 0.0, ... ]
        }
      }
    ]
  }
}</pre>

  <p><code class="inline">field</code> is the <code class="inline">semantic_text</code> field, <code class="inline">query</code> is the natural-language question, <code class="inline">k</code> is how many nearest passages to pull from the vector index. Add a <code class="inline">filter</code> (any XERJ query) to constrain candidates, or a <code class="inline">boost</code> to weight it inside a <code class="inline">bool</code>.</p>

  <blockquote>
    <p><strong><code class="inline">_source</code> note.</strong> The companion <code class="inline">body_vector</code> rides along in <code class="inline">_source</code> on semantic hits (source filtering is applied on the lexical path but the vector field is re-attached on the retrieval path). It's just noise for RAG — read the fields you want (<code class="inline">title</code>, <code class="inline">body</code>) and ignore it when you build the LLM prompt.</p>
  </blockquote>

  <h2>4. The RAG context bundle</h2>
  <p>Retrieval done, RAG is just "concatenate the top passages into the prompt." Pull <code class="inline">k</code> hits and format them with their ids so the model can cite them:</p>
<pre class="code">User question: how do I regenerate my API token

Retrieved context:
[kb-1] Rotating an API key
To change your API credentials, open Settings, choose Security, and click
Regenerate token. The old token stops working immediately.

[kb-5] Rate limits
The API permits 600 requests per minute per key. Exceeding the throttle returns
HTTP 429; back off and retry after the reset window.</pre>

  <p>Feed that block to your LLM as grounding context alongside the question. That's the whole retrieval side of RAG — no vector DB in the diagram.</p>

  <h2>5. Results — paraphrases land on the right doc</h2>
  <p>Running five paraphrased questions (none share the doc's full wording) against the 5-doc KB, each returns the correct passage at rank 1:</p>
<pre class="code">Q: 'how do I regenerate my API token'          -&gt; kb-1 Rotating an API key           OK
Q: 'can I get my money back after buying'       -&gt; kb-2 Refund policy                  OK
Q: "I forgot my login and can't sign in"        -&gt; kb-3 Resetting a forgotten password OK
Q: 'which file formats are supported for uploads' -&gt; kb-4 Supported file formats        OK
Q: 'how many calls per minute am I allowed'     -&gt; kb-5 Rate limits                    OK

RESULT: 5/5 semantic retrievals returned the right doc at rank 1</pre>

  <p>For contrast, the same paraphrase through a keyword <code class="inline">match</code>:</p>
<pre class="code">Q: 'get my money back after buying'
   match    top -&gt; NO HITS
   semantic top -&gt; kb-2 Refund policy</pre>

  <h2>Three embedding backends: lexical (default), built-in neural, or bring-your-own</h2>
  <p>The <code class="inline">semantic_text</code> mapping and the <code class="inline">semantic</code> query above are <strong>identical</strong> across all three backends. You choose the backend once, at the server, with <code class="inline">--embed-mode</code> (or <code class="inline">embedding.mode</code> in config, or <code class="inline">XERJ_EMBED_MODE</code>):</p>
  <ul>
    <li><strong><code class="inline">lexical</code> (default)</strong> — built-in feature-hash embedder. Offline, deterministic, zero download. Maps overlapping and related vocabulary into vector space.</li>
    <li><strong><code class="inline">neural</code></strong> — built-in BERT sentence encoder (<code class="inline">all-MiniLM-L6-v2</code>) running in-process via <code class="inline">candle</code>. Pure Rust, no Python, no external service. The model auto-downloads (~90&nbsp;MB) once on first use, or point <code class="inline">embedding.local_model_dir</code> at a pre-staged copy for a fully <strong>air-gapped</strong> install.</li>
    <li><strong><code class="inline">proxy</code></strong> — bring your own model: XERJ calls any OpenAI-compatible <code class="inline">/v1/embeddings</code> service (OpenAI, Cohere, a local vLLM). Set <code class="inline">embedding.default_endpoint</code> in config, or point a field at it in the mapping via <code class="inline">inference_endpoint</code> / <code class="inline">inference_id</code>.</li>
  </ul>

  <h3>The default is lexical — know where it stops</h3>
  <p>The zero-config embedder is a <strong>lexical</strong> model. It shines when the question and the answer share <em>some</em> terms (a synonym here, a rephrase there), which covers a lot of real support/FAQ traffic. It is <strong>not</strong> a neural sentence embedder and won't capture deep semantics with no lexical bridge. Concretely, from this same KB:</p>
<pre class="code">Q: 'how do I rotate my API key'
   semantic top -&gt; kb-5 Rate limits   (expected kb-1)   # --embed-mode lexical</pre>
  <p>The doc is <em>titled</em> "Rotating an API key," but only its <strong>body</strong> is embedded, and the body never uses the word "rotate" — so a pure "rotate" paraphrase misses in lexical mode.</p>

  <h3>Upgrade to real neural semantics — still one binary, still in place</h3>
<pre class="code"># Built-in neural embedder — ships in the binary, no external service.
# Downloads all-MiniLM-L6-v2 (~90 MB) once on first use, then runs in-process.
xerj --insecure --data-dir ./data --embed-mode neural</pre>
  <p>With <code class="inline">--embed-mode neural</code>, that "rotate" paraphrase lands on <code class="inline">kb-1</code>: the BERT encoder captures that <em>rotate&nbsp;≈&nbsp;regenerate&nbsp;≈&nbsp;replace</em> even with no shared term. The mapping and query don't change — only the server flag does.</p>
  <p>Two honest takeaways that apply in every mode:</p>
  <ul>
    <li><strong>Embed the text that carries the meaning.</strong> If titles matter, index them into the <code class="inline">semantic_text</code> field too (or add a second <code class="inline">semantic_text</code> field and combine with <code class="inline">hybrid</code>), so the vocabulary the user might use is actually in the vector.</li>
    <li><strong>Bring your own model when you need a specific one.</strong> <code class="inline">--embed-mode proxy</code> with <code class="inline">embedding.default_endpoint</code> reaches any OpenAI-compatible endpoint. Embedding happens at ingest time (there is no continuous re-embedding).</li>
  </ul>

  <p>Everything shown above the "Upgrade" step is <code class="inline">semantic_text</code> + the built-in lexical embedder — no external service was configured for this recipe.</p>

  <hr>

  <h2>Reproduce it yourself</h2>
  <p>Start XERJ on its default port (<code class="inline">9200</code>) and run the example — no keys, no external services, stdlib Python only:</p>
<pre class="code"># 1. Start a throwaway XERJ (ES-compat wire on :9200 by default)
xerj --insecure --data-dir ./data

# 2. In another shell, run the demo (honors $XERJ_URL, default http://localhost:9200)
python3 docs/examples/semantic-search-rag/rag_demo.py</pre>

  <p>Point it at a non-default host/port with <code class="inline">XERJ_URL=http://host:port</code> (the older <code class="inline">BASE</code> variable still works as an alias). The <a href="https://github.com/xerj-org/xerj/blob/main/docs/examples/semantic-search-rag/rag_demo.py">script</a> (stdlib only — <code class="inline">urllib</code> + <code class="inline">json</code>, no pip) creates the index, bulk-loads the KB, runs the five semantic retrievals with assertions, prints the RAG context bundle, shows the keyword-vs-semantic contrast, demonstrates the lexical-embedder miss, scores the ranking with <code class="inline">_rank_eval</code>, and exits non-zero if any of the five retrievals regress — so it doubles as a CI gate.</p>

  <p>The built-in embedder is deterministic (offline lexical model), so every run prints the same numbers:</p>
<pre class="code">bulk -&gt; errors=False items=5
...
Q: 'how do I regenerate my API token'  top -&gt; kb-1 'Rotating an API key' score=0.6626 OK
Q: 'can I get my money back after buying'  top -&gt; kb-2 'Refund policy' score=0.5771 OK
Q: "I forgot my login and can't sign in"  top -&gt; kb-3 'Resetting a forgotten password' score=0.6710 OK
Q: 'which file formats are supported for uploads'  top -&gt; kb-4 'Supported file formats for upload' score=0.5926 OK
Q: 'how many calls per minute am I allowed'  top -&gt; kb-5 'Rate limits' score=0.6171 OK

RESULT: 5/5 semantic retrievals returned the right doc at rank 1</pre>

  <p>Every score above is emitted by this run (the top <code class="inline">kb-1</code> score is <code class="inline">0.6625697016716003</code>, shown to 4 dp); nothing is hardcoded. Point <code class="inline">XERJ_URL</code> at real Elasticsearch with a <code class="inline">semantic_text</code>/inference setup to compare.</p>

  <hr>

  <h2>Measuring ranking quality with <code class="inline">_rank_eval</code></h2>
  <p>Once you have relevance judgements (which docs <em>should</em> come back for a query), the <code class="inline">_rank_eval</code> API scores your ranking with the standard IR metrics — the same wire API as Elasticsearch. XERJ computes each metric for real (they are <strong>not</strong> aliases for precision): <code class="inline">precision</code>, <code class="inline">recall</code>, <code class="inline">dcg</code> (add <code class="inline">"normalize": true</code> for nDCG), <code class="inline">mean_reciprocal_rank</code>, and <code class="inline">expected_reciprocal_rank</code>. An unknown metric name returns <code class="inline">400</code> rather than a misleading number.</p>
  <p>Scoring the regenerate-token ranking against this KB — <code class="inline">kb-1</code> is the one relevant answer, so with it at rank 1 the ranking is perfect:</p>
<pre class="code">curl -sX POST localhost:9200/kb/_rank_eval -H 'content-type: application/json' -d '{
  "metric": { "dcg": { "k": 3, "normalize": true } },
  "requests": [
    {
      "id": "regen_token_q",
      "request": { "query": { "semantic": { "field": "body",
                    "query": "how do I regenerate my API token", "k": 3 } } },
      "ratings": [
        { "_id": "kb-1", "rating": 3 },
        { "_id": "kb-5", "rating": 0 },
        { "_id": "kb-2", "rating": 0 }
      ]
    }
  ]
}'
# → { "metric_score": 1.0, "details": { "regen_token_q": { "metric_score": 1.0, ... } } }</pre>

  <p>Swap <code class="inline">"dcg"</code> for <code class="inline">"precision"</code>, <code class="inline">"recall"</code>, or <code class="inline">"mean_reciprocal_rank"</code> to score the <em>same</em> ranking a different way — each returns its own value. These are the figures the demo actually measures against this KB:</p>
<pre class="code">dcg (nDCG@3)          metric_score=1.0
precision@3           metric_score=0.3333333333333333
recall@3              metric_score=1.0
mean_reciprocal_rank  metric_score=1.0
unknown-metric -&gt; HTTP 400 (fail-loud, not a misleading number)</pre>

  <p>Track whichever metric your product cares about as you tune embeddings, <code class="inline">k</code>, and hybrid weights.</p>

  <!-- Print-only branded footer (hidden on screen, visible in PDF) -->
  <div class="print-footer" style="display:none;">
    <span>XERJ.AI · V1.0.0-RC.100 · 2026-08-11</span>
    <a href="https://xerj.org/docs/">https://xerj.org/docs/</a>
    <span>Recipe · Semantic search &amp; RAG</span>
  </div>
</main>
</div>

<!-- seo:footer-begin — generated by scripts/seo/fix_links.py · do not hand-edit -->
<nav class="footer-map" aria-label="Site map">
  <div class="fm-col">
    <span class="fm-h">PRODUCT</span>
    <a href="/product">PRODUCT</a>
    <a href="/architecture/">ARCHITECTURE</a>
    <a href="/benchmarks/">BENCHMARKS</a>
    <a href="/pricing/">PRICING</a>
    <a href="/security/">SECURITY</a>
    <a href="/playground">DASHBOARDS</a>
    <a href="/demo/">REAL-DATA DEMO</a>
    <a href="/aise-demo">PRODUCT TOUR</a>
  </div>
  <div class="fm-col">
    <span class="fm-h">LEARN</span>
    <a href="/answers/">ANSWERS</a>
    <a href="/compare/">COMPARE</a>
    <a href="/use-cases">USE CASES</a>
    <a href="/case-studies">CASE STUDIES</a>
    <a href="/industries/">INDUSTRIES</a>
    <a href="/blog/">BLOG</a>
  </div>
  <div class="fm-col">
    <span class="fm-h">SOLUTIONS</span>
    <a href="/solutions/">SOLUTIONS</a>
    <a href="/industries/finserv">FINANCIAL SERVICES</a>
    <a href="/industries/public-sector">PUBLIC SECTOR</a>
    <a href="/industries/healthcare">HEALTHCARE</a>
    <a href="/industries/retail">RETAIL</a>
    <a href="/use-cases/code-security-audit">AI CODE-SECURITY AUDIT</a>
    <a href="/use-cases/semantic-analytics">SEMANTIC ANALYTICS</a>
    <a href="/resources/">SALES KIT</a>
  </div>
  <div class="fm-col">
    <span class="fm-h">DOCS</span>
    <a href="/docs/">DOCUMENTATION</a>
    <a href="/docs/quickstart">QUICKSTART</a>
    <a href="/docs/install">INSTALL</a>
    <a href="/docs/migration-from-es">MIGRATE FROM ELASTICSEARCH</a>
    <a href="/docs/recipes/">RECIPES</a>
    <a href="/docs/agents/">DOCS FOR AI</a>
    <a href="/for-agents">FOR AI AGENTS</a>
    <a href="/agent-search/">AGENTIC SEARCH DEMO</a>
    <a href="/llms.txt">LLMS.TXT</a>
    <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
  </div>
</nav>
<!-- seo:footer-end -->
<footer class="footer">
  <span>XERJ.AI · DOCS · V1.0.0-RC.100</span>
  <span>READ THE SOURCE</span>
  <span><a href="/">HOME</a> · <a href="/product">PRODUCT</a> · <a href="/answers/">ANSWERS</a> · <a href="/playground">DASHBOARDS</a> &middot; <a href="/llms.txt">LLMS.TXT</a></span>
</footer>

<script type="application/json" id="docs-index">[{"title":"Overview","slug":"/docs/","kicker":"START","snip":""},{"title":"Quickstart","slug":"/docs/quickstart","kicker":"START","snip":""},{"title":"Install","slug":"/docs/install","kicker":"START","snip":""},{"title":"Migrate from ES","slug":"/docs/migration-from-es","kicker":"START","snip":""},{"title":"CLI","slug":"/docs/cli","kicker":"REFERENCE","snip":""},{"title":"Config TOML","slug":"/docs/config","kicker":"REFERENCE","snip":""},{"title":"Environment","slug":"/docs/env","kicker":"REFERENCE","snip":""},{"title":"Native REST API","slug":"/docs/api-native","kicker":"REFERENCE","snip":""},{"title":"ES-compat API","slug":"/docs/api-es-compat","kicker":"REFERENCE","snip":""},{"title":"Query types","slug":"/docs/queries","kicker":"DATA MODEL","snip":""},{"title":"Aggregations","slug":"/docs/aggregations","kicker":"DATA MODEL","snip":""},{"title":"Analyzers","slug":"/docs/analyzers","kicker":"DATA MODEL","snip":""},{"title":"Vectors & kNN","slug":"/docs/vectors","kicker":"DATA MODEL","snip":""},{"title":"Ingest pipelines","slug":"/docs/ingest","kicker":"ENGINE","snip":""},{"title":"Storage & WAL","slug":"/docs/storage","kicker":"ENGINE","snip":""},{"title":"Compression","slug":"/docs/compression","kicker":"ENGINE","snip":""},{"title":"Clustering","slug":"/docs/clustering","kicker":"ENGINE","snip":""},{"title":"Metrics","slug":"/docs/metrics","kicker":"ENGINE","snip":""},{"title":"Auth & TLS","slug":"/docs/security","kicker":"ENGINE","snip":""},{"title":"Running in production","slug":"/docs/operations","kicker":"OPERATIONS","snip":""},{"title":"Backup & restore","slug":"/docs/backup-restore","kicker":"OPERATIONS","snip":""},{"title":"Upgrades","slug":"/docs/upgrades","kicker":"OPERATIONS","snip":""},{"title":"Troubleshooting","slug":"/docs/troubleshooting","kicker":"OPERATIONS","snip":""},{"title":"SIEM","slug":"/docs/playbooks/siem","kicker":"PLAYBOOKS","snip":""},{"title":"Log analytics","slug":"/docs/playbooks/log-analytics","kicker":"PLAYBOOKS","snip":""},{"title":"Vector · RAG","slug":"/docs/playbooks/vector-search","kicker":"PLAYBOOKS","snip":""},{"title":"Full-text search","slug":"/docs/playbooks/full-text","kicker":"PLAYBOOKS","snip":""},{"title":"Observability","slug":"/docs/playbooks/observability","kicker":"PLAYBOOKS","snip":""},{"title":"CLI · --config","slug":"/docs/cli#config-flag","kicker":"CLI","snip":"-c, --config <PATH>  Path to the TOML config file."},{"title":"CLI · --data-dir","slug":"/docs/cli#data-dir-flag","kicker":"CLI","snip":"-d, --data-dir <PATH>  Override [server] data_dir at the command line."},{"title":"CLI · --insecure","slug":"/docs/cli#insecure-flag","kicker":"CLI","snip":"-k, --insecure  Disable TLS and API-key auth. Dev only."},{"title":"[server] rest_port","slug":"/docs/config#server","kicker":"CONFIG","snip":"u16 · default 8080 · Native REST API listener port."},{"title":"[server] es_compat_port","slug":"/docs/config#server","kicker":"CONFIG","snip":"u16 · default 9200 · Elasticsearch-wire-format port. 0 = OS-assigned port."},{"title":"[storage] wal_sync","slug":"/docs/config#storage","kicker":"CONFIG","snip":"enum · default batched · sync · batched · async. Durability knob."},{"title":"[vector] hnsw_ef_search","slug":"/docs/config#vector","kicker":"CONFIG","snip":"u32 · default 100 · Accepted but not wired — the beam width comes from the request num_candidates."},{"title":"[vector] default_quantization","slug":"/docs/config#vector","kicker":"CONFIG","snip":"enum · none (default) · scalar8. binary is refused at startup; scalar4 is not accepted."},{"title":"GET /v1/health","slug":"/docs/api-native#health","kicker":"NATIVE API","snip":"Liveness + readiness. {status, uptime_s, version}."},{"title":"GET /v1/metrics","slug":"/docs/api-native#metrics","kicker":"NATIVE API","snip":"Prometheus text format. Scrape-friendly."},{"title":"POST /v1/indices/:name/turbo-ingest","slug":"/docs/api-native#turbo-ingest","kicker":"NATIVE API","snip":"NDJSON bulk path with parallel tokenization."},{"title":"POST /v1/indices/:name/search","slug":"/docs/api-native#search","kicker":"NATIVE API","snip":"Unified query endpoint — full-text, term, range, KNN, hybrid."},{"title":"POST /:index/_bulk","slug":"/docs/api-es-compat#bulk","kicker":"ES API","snip":"NDJSON bulk. Actions: index, create, update, delete."},{"title":"POST /:index/_search","slug":"/docs/api-es-compat#search","kicker":"ES API","snip":"ES query DSL. Drop-in migration path."},{"title":"match_all","slug":"/docs/queries#match-all","kicker":"QUERY","snip":"Everything in the index."},{"title":"bool","slug":"/docs/queries#bool","kicker":"QUERY","snip":"must / should / must_not / filter clauses."},{"title":"knn","slug":"/docs/queries#knn","kicker":"QUERY","snip":"Vector kNN — HNSW-served when unfiltered (exact-rescored); filtered runs the exact scan."},{"title":"semantic","slug":"/docs/queries#semantic","kicker":"QUERY","snip":"Embed the query text at query time and search the vector field."},{"title":"hybrid","slug":"/docs/queries#hybrid","kicker":"QUERY","snip":"RRF / linear fusion of sub-queries."},{"title":"terms aggregation","slug":"/docs/aggregations#terms","kicker":"AGG","snip":"Exact, pre-computed terms histograms over keyword fields."},{"title":"date_histogram","slug":"/docs/aggregations#date-histogram","kicker":"AGG","snip":"Time-bucketed counts."},{"title":"kNN serving","slug":"/docs/vectors#knn-query","kicker":"VECTORS","snip":"Unfiltered kNN via persisted HNSW + exact rescore; filtered kNN exact scan."},{"title":"SQ8 quantization","slug":"/docs/vectors#quantization","kicker":"VECTORS","snip":"8-bit scalar quantization. int8 scoring precision, not a memory saving (#392)."},{"title":"turbo-ingest","slug":"/docs/ingest#turbo","kicker":"INGEST","snip":"NDJSON bulk path. Parallel tokenization across cores."},{"title":"delta-of-delta","slug":"/docs/compression#delta-of-delta","kicker":"COMPRESSION","snip":"Timestamp encoding. Apache/Nginx/ISO auto-detect."},{"title":"dictionary encoding","slug":"/docs/compression#dictionary","kicker":"COMPRESSION","snip":"Up to 256 unique strings per column."},{"title":"api_key","slug":"/docs/security#api-key","kicker":"SECURITY","snip":"Static admin key. Auto-generated on first run."},{"title":"SIEM playbook","slug":"/docs/playbooks/siem","kicker":"PLAYBOOK","snip":"Terms agg over source IPs for SIEM, with detection rules."},{"title":"RAG playbook","slug":"/docs/playbooks/vector-search","kicker":"PLAYBOOK","snip":"Embeddings, kNN, hybrid search, BM25 + kNN fusion."},{"title":"[cluster] enabled","slug":"/docs/config#cluster","kicker":"CONFIG","snip":"bool · default false · Enable multi-node Raft cluster mode."},{"title":"[cluster] peers","slug":"/docs/config#cluster","kicker":"CONFIG","snip":"array · \"host:port=host:port\" · label must equal address (#1171)."},{"title":"[cluster] port","slug":"/docs/config#cluster","kicker":"CONFIG","snip":"u16 · default 9300 · Intra-cluster Raft + search port."},{"title":"[embedding] default_endpoint","slug":"/docs/config#embedding","kicker":"CONFIG","snip":"string · OpenAI-compatible embeddings URL for auto-embedding on ingest."},{"title":"[embedding] default_model","slug":"/docs/config#embedding","kicker":"CONFIG","snip":"string · Model name (e.g. text-embedding-3-small, nomic-embed-text)."},{"title":"Raft","slug":"/docs/clustering","kicker":"CLUSTER","snip":"Embedded Raft — leader election, log replication, metadata only."},{"title":"Node draining","slug":"/docs/clustering","kicker":"CLUSTER","snip":"POST /v1/cluster/nodes/:id/drain before maintenance."},{"title":"Region split/merge","slug":"/docs/clustering","kicker":"CLUSTER","snip":"Range partitions auto-split at byte threshold, merge back when small."},{"title":"Systemd unit","slug":"/docs/operations","kicker":"OPS","snip":"Production unit file with hardening directives."},{"title":"Readiness probe","slug":"/docs/operations","kicker":"OPS","snip":"GET /v1/health/ready — only 200 once WAL replay is complete."},{"title":"Config reload","slug":"/docs/operations","kicker":"OPS","snip":"SIGHUP reloads most keys without restart."},{"title":"Hot backup","slug":"/docs/backup-restore","kicker":"OPS","snip":"rsync the data dir after POST /v1/admin/flush."},{"title":"S3 backup","slug":"/docs/backup-restore","kicker":"OPS","snip":"POST /v1/admin/backup → any S3-compatible endpoint."},{"title":"Rolling upgrade","slug":"/docs/upgrades","kicker":"OPS","snip":"Drain → stop → upgrade → start → activate, per node."},{"title":"Merge pressure","slug":"/docs/troubleshooting","kicker":"OPS","snip":"Segment count climbing → raise merge.max_concurrent + io_rate."},{"title":"Cluster flapping","slug":"/docs/troubleshooting","kicker":"OPS","snip":"Leader changes every few seconds → raise cluster.tick_ms."},{"title":"WAL warnings after a crash","slug":"/docs/troubleshooting","kicker":"OPS","snip":"Repaired on startup; no manual repair command."},{"title": "Recipes", "slug": "/docs/recipes/", "kicker": "RECIPES", "snip": "Task-oriented AI & search recipes, each verified end-to-end against a live XERJ."},{"title": "Semantic search & RAG", "slug": "/docs/recipes/semantic-search-rag", "kicker": "RECIPE", "snip": "Retrieval by meaning with semantic_text — auto-embed on ingest, no separate vector DB."},{"title": "Agent memory", "slug": "/docs/recipes/agentic-memory", "kicker": "RECIPE", "snip": "Long-term memory for agents via /_memory — store, recall, forget, per-agent isolation."},{"title": "Passage retrieval", "slug": "/docs/recipes/passage-retrieval", "kicker": "RECIPE", "snip": "Auto-chunk long docs; best-passage (max-sim) scoring — 98% top-3."},{"title": "Vector search · kNN", "slug": "/docs/recipes/vector-search-knn", "kicker": "RECIPE", "snip": "Nearest-neighbor over dense_vector — HNSW-served unfiltered, exact with filters."},{"title": "Vector quantization", "slug": "/docs/recipes/vector-quantization", "kicker": "RECIPE", "snip": "scalar8 (accepts ES int8_hnsw; exact code scan) — int8 scoring at recall@10 = 0.998. Precision, not memory."},{"title": "Hybrid search", "slug": "/docs/recipes/hybrid-search", "kicker": "RECIPE", "snip": "Keyword + vector in one query — RRF fusion."},{"title": "Log analytics", "slug": "/docs/recipes/log-analytics", "kicker": "RECIPE", "snip": "Raw logs to dashboards — error rates, p95 latency, top services."},{"title": "Anomaly detection", "slug": "/docs/recipes/anomaly-detection", "kicker": "RECIPE", "snip": "Statistical _ml detectors that flag spikes in metrics/logs."},{"title": "Anomaly datafeeds", "slug": "/docs/recipes/continuous-anomaly-datafeeds", "kicker": "RECIPE", "snip": "Live _ml datafeed re-scores an index on a timer, stores anomaly records."},{"title": "Migrate from ES", "slug": "/docs/recipes/migrate-from-elasticsearch", "kicker": "RECIPE", "snip": "Point your existing ES client at XERJ — same wire, change the URL."}]</script>

<script>
  // IIFE — js-auth navigates between decrypted pages in the same
  // JS realm, so const bindings must be lexically scoped.
  (function () {
    const root = document.documentElement;

    // Client-side docs search — filters the inline JSON index.
    const searchEl    = document.getElementById('docsSearch');
    const inputEl     = document.getElementById('docsSearchInput');
    const resultsEl   = document.getElementById('docsSearchResults');
    const indexJson   = document.getElementById('docs-index');
    if (searchEl && inputEl && resultsEl && indexJson) {
      let index = [];
      try { index = JSON.parse(indexJson.textContent || '[]'); } catch {}
      const render = (q) => {
        const query = q.trim().toLowerCase();
        if (!query) { searchEl.classList.remove('active'); resultsEl.innerHTML = ''; return; }
        const scored = [];
        for (const e of index) {
          const hay = (e.title + ' ' + (e.kicker || '') + ' ' + (e.snip || '')).toLowerCase();
          if (hay.includes(query)) {
            let score = 0;
            if (e.title.toLowerCase().includes(query)) score += 10;
            if ((e.kicker || '').toLowerCase() === query.toUpperCase()) score += 5;
            if ((e.snip || '').toLowerCase().includes(query)) score += 1;
            scored.push({ e, score });
          }
        }
        scored.sort((a, b) => b.score - a.score);
        const top = scored.slice(0, 20);
        if (top.length === 0) {
          resultsEl.innerHTML = '<div class="no-results">NO MATCHES — TRY A SHORTER QUERY</div>';
        } else {
          resultsEl.innerHTML = top.map(({e}) => {
            const kicker = e.kicker || '';
            const snip = e.snip ? '<div class="snip">' + escHtml(e.snip) + '</div>' : '';
            return '<a href="' + e.slug + '">' +
              '<span class="kicker">' + escHtml(kicker) + '</span>' +
              '<span class="title">' + escHtml(e.title) + '</span>' +
              snip + '</a>';
          }).join('');
        }
        searchEl.classList.add('active');
      };
      const escHtml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
      inputEl.addEventListener('input', (e) => render(e.target.value));
      inputEl.addEventListener('focus', () => { if (inputEl.value) render(inputEl.value); });
      document.addEventListener('keydown', (e) => {
        if ((e.key === 'k' || e.key === 'K') && (e.metaKey || e.ctrlKey)) {
          e.preventDefault();
          inputEl.focus();
          inputEl.select();
        }
        if (e.key === 'Escape' && document.activeElement === inputEl) {
          inputEl.value = '';
          searchEl.classList.remove('active');
          resultsEl.innerHTML = '';
          inputEl.blur();
        }
      });
    }
  })();
</script>

</body>
</html>