# Semantic Search

Source: https://docs.rushdb.com/2.x/learn/semantic-search/

`db.records.vectorSearch()` / `POST /api/v1/ai/search` performs semantic vector search across records that have an associated embedding index. Candidates are narrowed by label and `where` filters first, then ranked by cosine or euclidean similarity.

The property referenced by `propertyName` must have a `ready` embedding index. See [Manage Embedding Indexes](/learn/semantic-search/manage-indexes).

If you want RushDB to convert a natural-language request into a `SearchQuery`, use [Smart Search](/learn/search-query/smart-search) with `db.ai.search(prompt)`.

---

## Managed Search (Query Text)

For a **managed** index, pass a natural-language `query` string. The server embeds it using the same model that built the index.

**Python**

```python
response = db.records.vector_search({
    "propertyName": "description",
    "query": "machine learning for beginners",
    "labels": ["Article"],
    "limit": 5,
})

for result in response.data:
    print(f"[{result.score:.3f}] {result.get('title')}")
```

**TypeScript**

```typescript
const { data: results } = await db.records.vectorSearch({
  labels: ['Book'],
  propertyName: 'description',
  query: 'space exploration and interstellar travel',
  limit: 5
})

results.forEach((r) => {
  console.log(`[${r.score!.toFixed(4)}] ${r.data.title}`)
})
```

**Shell**

`POST /api/v1/ai/search`

```bash
curl -X POST https://api.rushdb.com/api/v1/ai/search \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "propertyName": "description",
    "query": "fast delivery and easy returns",
    "labels": ["Product"],
    "limit": 5
  }'
```

---

## External Search (Query Vector)

For an **external** index, pass `queryVector` — a pre-computed embedding from your own model. No text is sent to any embedding model.

**Python**

```python
vec = my_embedder.embed("machine learning for beginners")

response = db.records.vector_search({
    "propertyName": "body",
    "queryVector": vec,
    "labels": ["Article"],
    "limit": 10,
})
```

**TypeScript**

```typescript
const myEmbedder = new MyEmbeddingModel()
const vec = await myEmbedder.embed('space exploration')

const { data: results } = await db.records.vectorSearch({
  labels: ['Article'],
  propertyName: 'body',
  queryVector: vec,
  limit: 10
})
```

**Shell**

```bash
curl -X POST https://api.rushdb.com/api/v1/ai/search \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "propertyName": "body",
    "queryVector": [0.1, 0.2, 0.3],
    "labels": ["Article"],
    "limit": 10
  }'
```

- `query` is **not allowed** with external indexes — the server has no model to embed it.
- `queryVector` is accepted for managed indexes (bypasses server embedding).
- When `queryVector` is supplied, `dimensions` can be omitted — the server infers it from vector length.

---

## Filter + Semantic Search

The `where` clause acts as a **prefilter** — only records satisfying the filter are candidates for similarity ranking. All operators from [Where Operators](/learn/search-query/where-operators) are available.

**Python**

```python
response = db.records.vector_search({
    "propertyName": "description",
    "query": "wireless headphones",
    "labels": ["Product"],
    "where": {
        "category": {"$eq": "electronics"},
        "inStock":  {"$eq": True},
        "price":    {"$lt": 100},
    },
    "limit": 20,
})
```

**TypeScript**

```typescript
const { data: results } = await db.records.vectorSearch({
  labels: ['Product'],
  propertyName: 'description',
  query: 'wireless headphones',
  where: {
    category: { $eq: 'electronics' },
    inStock: { $eq: true },
    price: { $lt: 100 }
  },
  limit: 20
})
```

**Shell**

```bash
curl -X POST https://api.rushdb.com/api/v1/ai/search \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "propertyName": "description",
    "query": "wireless headphones",
    "labels": ["Product"],
    "where": {
      "category": {"$eq": "electronics"},
      "inStock":  {"$eq": true},
      "price":    {"$lt": 100}
    },
    "limit": 20
  }'
```

---

## Multi-Label Search

Search across multiple entity types simultaneously. All listed labels must have an embedding index on the same `propertyName`.

**Python**

```python
response = db.records.vector_search({
    "propertyName": "body",
    "query": "machine learning trends",
    "labels": ["Article", "Post", "Comment"],
    "limit": 10,
})

for result in response.data:
    print(result.get("__label"), f"{result.score:.3f}", result.get("title") or result.get("text"))
```

**TypeScript**

```typescript
const { data: results } = await db.records.vectorSearch({
  labels: ['Article', 'Post', 'Comment'],
  propertyName: 'body',
  query: 'machine learning trends',
  limit: 10
})

results.forEach((r) => console.log(r.data.__label, r.score, r.data.title ?? r.data.text))
```

**Shell**

```bash
curl -X POST https://api.rushdb.com/api/v1/ai/search \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "propertyName": "body",
    "query": "machine learning trends",
    "labels": ["Article", "Post", "Comment"],
    "limit": 10
  }'
```

---

## Result Shape

Results are ordered by `__score` descending — closest match first.

**Python**

```python
# Sample result object (response.data[0]):
# {
#   "__id":          "rec_abc123",
#   "__label":       "Product",
#   "__score":       0.9214,
#   "name":          "ANC Wireless Headphones",
#   "description":   "Same-day shipping with hassle-free returns policy",
#   "price":         89.99
# }

for result in response.data:
    result.id                  # "rec_abc123"  — RushDB record ID
    result.get("__label")      # "Product"     — record label
    result.score      # 0.9214        — similarity score 0–1 (higher = more similar)
    result.get("name")         # your fields via .get()
    result["price"]            # or via [] — raises KeyError if missing
```

**TypeScript**

```typescript
// Sample result (DBRecordInstance):
// {
//   data: {
//     __id:        "rec_abc123",
//     __label:     "Product",
//     __score:     0.9214,
//     name:        "ANC Wireless Headphones",
//     description: "Same-day shipping with hassle-free returns policy",
//     price:       89.99
//   }
// }

results.forEach((r) => {
  r.data.id // "rec_abc123"  — RushDB record ID
  r.data.__label // "Product"     — record label
  r.data.score // 0.9214        — similarity score 0–1 (higher = more similar)
  r.data.name // your properties directly on r.data
  r.data.price
  r.score // same as r.data.score — convenience getter
})
```

**Shell**

```json
{
  "data": [
    {
      "__id": "rec_abc123",
      "__label": "Product",
      "__score": 0.9214,
      "name": "ANC Wireless Headphones",
      "description": "Same-day shipping with hassle-free returns policy",
      "price": 89.99
    }
  ],
  "success": true
}
```

---

## Parameters Reference

| Parameter            | Type                      | Required      | Description                                                                                             |
| -------------------- | ------------------------- | ------------- | ------------------------------------------------------------------------------------------------------- |
| `propertyName`       | `string`                  | **yes**       | The indexed property to search against (e.g. `"description"`)                                           |
| `labels`             | `string \| string[]`      | **yes**       | Label(s) to search within (min 1)                                                                       |
| `query`              | `string`                  | conditionally | Free-text query. Required for managed indexes; **not allowed** for external indexes.                    |
| `queryVector`        | `number[]`                | conditionally | Pre-computed query vector. Required for external indexes. Also accepted for managed indexes.            |
| `similarityFunction` | `"cosine" \| "euclidean"` | no            | Required when multiple indexes target the same `(label, propertyName)`.                                 |
| `dimensions`         | `number`                  | no            | Disambiguates when multiple indexes match. Inferred from `queryVector.length` when `queryVector` given. |
| `where`              | `object`                  | no            | Prefilter — applied before similarity scoring.                                                          |
| `skip`               | `number`                  | no            | Pagination offset (default `0`)                                                                         |
| `limit`              | `number`                  | no            | Maximum results to return (default `20`)                                                                |

---

## Disambiguation

When two indexes exist for the same `(label, propertyName)`, specify `similarityFunction` to select the target index:

**Python**

```python
response = db.records.vector_search({
    "labels": ["Product"],
    "propertyName": "embedding",
    "queryVector": vec,
    "similarityFunction": "cosine",   # required — otherwise 422
})
```

**TypeScript**

```typescript
await db.records.vectorSearch({
  labels: ['Product'],
  propertyName: 'embedding',
  queryVector: vec,
  similarityFunction: 'cosine' // required — otherwise 422 Unprocessable Entity
})
```

**Shell**

```bash
curl -X POST https://api.rushdb.com/api/v1/ai/search \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["Product"],
    "propertyName": "embedding",
    "queryVector": [0.1, 0.2, 0.3],
    "similarityFunction": "cosine"
  }'
```

---

## Pagination

**Python**

```python
PAGE = 20

page1 = db.records.vector_search({
    "propertyName": "description",
    "query": "sustainable packaging",
    "labels": ["Product"],
    "limit": PAGE,
    "skip": 0,
})

page2 = db.records.vector_search({
    "propertyName": "description",
    "query": "sustainable packaging",
    "labels": ["Product"],
    "limit": PAGE,
    "skip": PAGE,
})
```

**TypeScript**

```typescript
const PAGE = 20;

const { data: page1 } = await db.records.vectorSearch({ ..., limit: PAGE, skip: 0 });
const { data: page2 } = await db.records.vectorSearch({ ..., limit: PAGE, skip: PAGE });
```

**Shell**

```bash
curl -X POST https://api.rushdb.com/api/v1/ai/search \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"propertyName": "description", "query": "...", "labels": ["Product"], "limit": 20, "skip": 20}'
```

---

## Error Reference

| HTTP                       | Cause                                                             |
| -------------------------- | ----------------------------------------------------------------- |
| `404 Not Found`            | No enabled embedding index found for `(label, propertyName)`      |
| `422 Unprocessable Entity` | Multiple indexes match and `similarityFunction` was not specified |
| `422 Unprocessable Entity` | `query` text supplied for an external index                       |
| `422 Unprocessable Entity` | Vector length does not match index `dimensions`                   |
| `503 Service Unavailable`  | Embedding model unavailable (managed indexes only)                |

---

## See also

- [Manage Embedding Indexes](/learn/semantic-search/manage-indexes) — create, list, delete, and monitor indexes
- [Write Records with Vectors](/learn/semantic-search/write-with-vectors) — attach vectors when storing records
- [Bring Your Own Vectors](/learn/semantic-search/bring-your-own-vectors) — use external embedding models
- [Smart Search](/learn/search-query/smart-search) — generate and execute SearchQuery from natural language
- [Find & Query](/learn/records-and-queries/find-and-query) — keyword / graph-only search without AI
