> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/open-webui/open-webui/llms.txt
> Use this file to discover all available pages before exploring further.

# Query Knowledge Bases

> Perform semantic search across knowledge base collections

Query one or more knowledge base collections using semantic search. Returns the most relevant document chunks based on vector similarity and optional reranking.

## Request

### Request Body

<ParamField body="collection_names" type="array" required>
  Array of knowledge base collection IDs to query. Each knowledge base has a unique collection ID.
</ParamField>

<ParamField body="query" type="string" required>
  The search query text. Will be embedded and compared against document embeddings.
</ParamField>

<ParamField body="k" type="integer">
  Number of results to return (default: configured TOP\_K value). For hybrid search, this is the initial retrieval size before reranking.
</ParamField>

<ParamField body="k_reranker" type="integer">
  Number of results after reranking (only applies when hybrid search is enabled). Default: configured TOP\_K\_RERANKER.
</ParamField>

<ParamField body="r" type="float">
  Relevance threshold (0.0 to 1.0). Results below this threshold are filtered out. Default: configured RELEVANCE\_THRESHOLD.
</ParamField>

<ParamField body="hybrid" type="boolean">
  Whether to use hybrid search (vector + BM25 + reranking). Default: based on ENABLE\_RAG\_HYBRID\_SEARCH setting.
</ParamField>

<ParamField body="hybrid_bm25_weight" type="float">
  Weight for BM25 scores in hybrid search (0.0 to 1.0). Default: configured HYBRID\_BM25\_WEIGHT.
</ParamField>

<ParamField body="enable_enriched_texts" type="boolean">
  Whether to include enriched text snippets. Default: ENABLE\_RAG\_HYBRID\_SEARCH\_ENRICHED\_TEXTS.
</ParamField>

### Headers

<ParamField header="Authorization" type="string" required>
  Bearer token for authentication
</ParamField>

## Response

Returns an array of relevant document chunks ranked by relevance score.

<ResponseField name="distances" type="array">
  Array of arrays containing distance scores (lower is more similar). One array per collection queried.
</ResponseField>

<ResponseField name="documents" type="array">
  Array of arrays containing the text content of matching chunks

  Example: `[["Product guide chapter 1...", "Setup instructions..."]]`
</ResponseField>

<ResponseField name="metadatas" type="array">
  Array of arrays containing metadata for each document chunk

  <ResponseField name="file_id" type="string">
    ID of the source file
  </ResponseField>

  <ResponseField name="name" type="string">
    Name of the source document
  </ResponseField>

  <ResponseField name="source" type="string">
    Source identifier or filename
  </ResponseField>

  <ResponseField name="created_by" type="string">
    User ID who uploaded the document
  </ResponseField>

  <ResponseField name="embedding_config" type="object">
    Configuration of the embedding model used
  </ResponseField>
</ResponseField>

<ResponseField name="ids" type="array">
  Array of arrays containing unique chunk IDs
</ResponseField>

<ResponseField name="scores" type="array">
  (Hybrid search only) Relevance scores after reranking (higher is better)
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://your-domain.com/api/v1/retrieval/query/collection" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "collection_names": ["kb_123abc"],
      "query": "How do I install the software?",
      "k": 5,
      "hybrid": true
    }'
  ```

  ```python Python theme={null}
  import requests

  url = "https://your-domain.com/api/v1/retrieval/query/collection"
  headers = {
      "Authorization": "Bearer YOUR_TOKEN",
      "Content-Type": "application/json"
  }
  payload = {
      "collection_names": ["kb_123abc"],
      "query": "How do I install the software?",
      "k": 5,
      "hybrid": True,
      "r": 0.3  # Filter results below 30% relevance
  }

  response = requests.post(url, headers=headers, json=payload)
  results = response.json()

  for i, doc in enumerate(results["documents"][0]):
      print(f"Result {i+1}:")
      print(f"Content: {doc[:100]}...")
      if "scores" in results:
          print(f"Score: {results['scores'][0][i]}")
      print(f"Source: {results['metadatas'][0][i]['name']}")
      print()
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://your-domain.com/api/v1/retrieval/query/collection',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_TOKEN',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        collection_names: ['kb_123abc'],
        query: 'How do I install the software?',
        k: 5,
        hybrid: true
      })
    }
  );

  const results = await response.json();
  results.documents[0].forEach((doc, i) => {
    console.log(`Result ${i+1}: ${doc.substring(0, 100)}...`);
    console.log(`Source: ${results.metadatas[0][i].name}`);
  });
  ```
</RequestExample>

<ResponseExample>
  ```json 200 - Success (Vector Search) theme={null}
  {
    "distances": [[0.234, 0.289, 0.312, 0.445, 0.521]],
    "documents": [[
      "To install the software, follow these steps: 1. Download the installer from our website...",
      "Installation requirements: Operating System: Windows 10 or later, macOS 11+...",
      "For Linux installation, use the following command: sudo apt-get install...",
      "After installation, launch the application from the Start menu or Applications folder...",
      "The setup wizard will guide you through the initial configuration..."
    ]],
    "metadatas": [[
      {
        "file_id": "file_abc123",
        "name": "installation_guide.pdf",
        "source": "installation_guide.pdf",
        "created_by": "user_456def",
        "embedding_config": {
          "engine": "openai",
          "model": "text-embedding-3-small"
        }
      },
      {
        "file_id": "file_abc123",
        "name": "installation_guide.pdf",
        "source": "installation_guide.pdf",
        "created_by": "user_456def",
        "embedding_config": {
          "engine": "openai",
          "model": "text-embedding-3-small"
        }
      }
    ]],
    "ids": [[
      "chunk_uuid_1",
      "chunk_uuid_2",
      "chunk_uuid_3",
      "chunk_uuid_4",
      "chunk_uuid_5"
    ]]
  }
  ```

  ```json 200 - Success (Hybrid Search with Reranking) theme={null}
  {
    "documents": [[
      "To install the software, follow these steps: 1. Download the installer from our website...",
      "Installation requirements: Operating System: Windows 10 or later, macOS 11+...",
      "For Linux installation, use the following command: sudo apt-get install..."
    ]],
    "metadatas": [[...]],
    "ids": [["chunk_uuid_1", "chunk_uuid_2", "chunk_uuid_3"]],
    "scores": [[0.89, 0.76, 0.68]]
  }
  ```

  ```json 400 - Invalid Request theme={null}
  {
    "detail": "Collection kb_invalid not found"
  }
  ```
</ResponseExample>

## Query Single Document Collection

For querying a single file's collection:

```bash theme={null}
POST /api/v1/retrieval/query/doc
```

### Request Body

<ParamField body="collection_name" type="string" required>
  Single collection name (usually `file-{file_id}` for individual files)
</ParamField>

<ParamField body="query" type="string" required>
  Search query text
</ParamField>

<ParamField body="k" type="integer">
  Number of results to return
</ParamField>

<ParamField body="k_reranker" type="integer">
  Number of results after reranking
</ParamField>

<ParamField body="r" type="float">
  Relevance threshold
</ParamField>

<ParamField body="hybrid" type="boolean">
  Enable hybrid search
</ParamField>

## Search Modes

### Vector Search (Default)

* Embeds your query using the configured embedding model
* Performs cosine similarity search against document embeddings
* Fast and efficient for semantic similarity

### Hybrid Search

When `hybrid=true` or `ENABLE_RAG_HYBRID_SEARCH` is enabled:

1. **Vector Search**: Retrieves top `k` results by embedding similarity
2. **BM25 Search**: Retrieves results using keyword matching
3. **Fusion**: Combines results using `hybrid_bm25_weight`
4. **Reranking**: Uses cross-encoder model to rerank to top `k_reranker` results
5. **Filtering**: Removes results below relevance threshold `r`

## Access Control

* Users can only query knowledge bases they have read access to
* Collection names are validated against user permissions
* Access is granted based on:
  * Knowledge base ownership
  * Group membership with read permissions
  * Admin role

## Notes

* Query embedding uses the same model as document embedding for consistency
* Results are returned in order of relevance (most relevant first)
* The `distances` field contains cosine distances (lower = more similar)
* The `scores` field (hybrid search only) contains reranking scores (higher = better)
* Multiple collections are queried in parallel for efficiency
* Results can be filtered by relevance threshold to improve quality
