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

# Synonyms Quickstart

> Define synonym rules and run your first synonym search

> [!NOTE]
>
> Synonyms are available in ParadeDB versions `0.27.0` and above.

First, create a table defining synonym rules, which use the `pdb.synonym_rule` type and follow the Solr syntax.

```sql SQL theme={null}
CREATE TABLE shop_synonyms (id serial PRIMARY KEY, rule pdb.synonym_rule NOT NULL);
INSERT INTO shop_synonyms (rule) VALUES
    ('couch, sofa, divan'), -- all three are synonyms
    ('sneakers => running shoes'); -- replace sneakers with "running shoes"
```

```ts Drizzle theme={null}
import { sql } from "drizzle-orm";
import { pgTable, serial, text } from "drizzle-orm/pg-core";

await db.execute(sql`
  CREATE TABLE shop_synonyms (id serial PRIMARY KEY, rule pdb.synonym_rule NOT NULL);
`);

await db.execute(sql`
  INSERT INTO shop_synonyms (rule) VALUES
      ('couch, sofa, divan'),
      ('sneakers => running shoes');
`);

const shopSynonyms = pgTable("shop_synonyms", {
  id: serial("id").primaryKey(),
  rule: text("rule").notNull(),
});
```

```python Django theme={null}
from django.db import connection, models

with connection.cursor() as cursor:
    cursor.execute("""
        CREATE TABLE shop_synonyms (id serial PRIMARY KEY, rule pdb.synonym_rule NOT NULL);
    """)
    cursor.execute("""
        INSERT INTO shop_synonyms (rule) VALUES
            ('couch, sofa, divan'),
            ('sneakers => running shoes');
    """)

class ShopSynonym(models.Model):
    id = models.AutoField(primary_key=True)
    rule = models.TextField()

    class Meta:
        app_label = 'myapp'
        db_table = 'shop_synonyms'
        managed = False
```

```python SQLAlchemy theme={null}
from sqlalchemy import Integer, Text, text
from sqlalchemy.orm import Mapped, mapped_column
from models import Base

with engine.begin() as conn:
    conn.execute(text("""
        CREATE TABLE shop_synonyms (id serial PRIMARY KEY, rule pdb.synonym_rule NOT NULL);
    """))
    conn.execute(text("""
        INSERT INTO shop_synonyms (rule) VALUES
            ('couch, sofa, divan'),
            ('sneakers => running shoes');
    """))

class ShopSynonym(Base):
    __tablename__ = "shop_synonyms"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    rule: Mapped[str] = mapped_column(Text, nullable=False)
```

```ruby Rails theme={null}
ActiveRecord::Base.connection.execute <<~SQL
  CREATE TABLE shop_synonyms (id serial PRIMARY KEY, rule pdb.synonym_rule NOT NULL);
SQL

ActiveRecord::Base.connection.execute <<~SQL
  INSERT INTO shop_synonyms (rule) VALUES
      ('couch, sofa, divan'),
      ('sneakers => running shoes');
SQL

class ShopSynonym < ApplicationRecord
  self.table_name = "shop_synonyms"
end
```

```cs EF Core theme={null}
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

await dbContext.Database.ExecuteSqlRawAsync("""
    CREATE TABLE shop_synonyms (id serial PRIMARY KEY, rule pdb.synonym_rule NOT NULL);
    """);

await dbContext.Database.ExecuteSqlRawAsync("""
    INSERT INTO shop_synonyms (rule) VALUES
        ('couch, sofa, divan'),
        ('sneakers => running shoes');
    """);

// Add to AppDbContext: public DbSet<ShopSynonym> ShopSynonyms => Set<ShopSynonym>();
[Table("shop_synonyms")]
public sealed class ShopSynonym
{
    [Column("id")]
    public int Id { get; set; }

    [Column("rule")]
    public string Rule { get; set; } = "";
}
```

Next, create an index over the synonym rules.

```sql SQL theme={null}
CREATE INDEX shop_synonyms_idx ON shop_synonyms
USING paradedb (rule);
```

```ts Drizzle theme={null}
import { sql } from "drizzle-orm";

await db.execute(sql`
  CREATE INDEX shop_synonyms_idx ON shop_synonyms
  USING paradedb (rule);
`);
```

```python Django theme={null}
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("""
        CREATE INDEX shop_synonyms_idx ON shop_synonyms
        USING paradedb (rule);
    """)
```

```python SQLAlchemy theme={null}
from sqlalchemy import text

with engine.begin() as conn:
    conn.execute(text("""
        CREATE INDEX shop_synonyms_idx ON shop_synonyms
        USING paradedb (rule);
    """))
```

```ruby Rails theme={null}
ActiveRecord::Base.connection.execute <<~SQL
  CREATE INDEX shop_synonyms_idx ON shop_synonyms
  USING paradedb (rule);
SQL
```

```cs EF Core theme={null}
using Microsoft.EntityFrameworkCore;

await dbContext.Database.ExecuteSqlRawAsync("""
    CREATE INDEX shop_synonyms_idx ON shop_synonyms
    USING paradedb (rule);
    """);
```

Finally, run a query searching for all defined synonyms of `couch`:

```sql SQL theme={null}
SELECT description FROM mock_items
WHERE description ||| (SELECT pdb.expand('couch', rule) FROM shop_synonyms);
```

```ts Drizzle theme={null}
import { search } from "@paradedb/drizzle-paradedb";

await db
  .select({ description: mockItems.description })
  .from(mockItems)
  .where(
    search.matchAny(
      mockItems.description,
      search.expand("couch", shopSynonyms.rule),
    ),
  );
```

```python Django theme={null}
from paradedb import Expand, MatchAny, ParadeDB

results = MockItem.objects.filter(
    description=ParadeDB(MatchAny(Expand('couch', ShopSynonym, 'rule')))
).values('description')
list(results)
```

```python SQLAlchemy theme={null}
from sqlalchemy import select
from sqlalchemy.orm import Session
from paradedb.sqlalchemy import search

rules = search.expand("couch", ShopSynonym.rule)

stmt = (
    select(MockItem.description)
    .where(search.match_any(MockItem.description, rules))
)

with Session(engine) as session:
    session.execute(stmt).all()
```

```ruby Rails theme={null}
MockItem.search(:description)
        .match_any(ParadeDB.expand("couch", ShopSynonym, :rule))
        .select(:description)
        .to_a
```

```cs EF Core theme={null}
await dbContext
    .MockItems.Where(item =>
        EF.Functions.MatchAny(
            item.Description,
            Pdb.Expand("couch", dbContext.ShopSynonyms.Select(s => s.Rule))
        )
    )
    .Select(item => new { item.Description })
    .ToListAsync();
```

This returns `Classic leather sofa`, even though its description doesn't contain `couch`:

```csv Expected Response theme={null}
     description
----------------------
 Classic leather sofa
(1 row)
```

## Synonym Rules

Every rule must be parseable Solr syntax, otherwise the `INSERT` will fail.

* `couch, sofa, divan` is an equivalence rule. A search for any of these words finds all of them.
* `sneakers => running shoes` is a directed rule. A search for `sneakers` looks for `running shoes` instead.
* If a word is present in several rules, a search for it uses the alternatives of all of them. However, rules don't chain. With
  `sneakers, shoes, trainers` and `shoes, kicks`, a search for `shoes` finds all four words, but a search for `kicks`
  finds only `kicks` and `shoes`.
* A multi-word term matches as a phrase. For example, `sofa bed, sleeper couch` makes the phrases `sofa bed` and
  `sleeper couch` synonyms. This rule alone does not make their individual words synonyms. Multi-word alternatives
  require [token positions](https://www.paradedb.com/docs/reference/full-text/phrase.md#how-it-works) on the field you search.
* When rules overlap, the longest matching term wins: a rule for `running shoes` takes priority over a rule for `running`.
* Use backslash to escape commas.

## Load a Synonym File

In `psql`, use `\copy` with a delimiter and a quote character that don't exist in the file. The ORM tabs
insert each line as one rule. Both approaches preserve backslashes and allow blank lines and comments in the rules.

```sql SQL theme={null}
\copy shop_synonyms (rule) FROM 'synonyms.txt' WITH (FORMAT csv, DELIMITER E'\x01', QUOTE E'\x02', FORCE_NOT_NULL (rule))
```

```ts Drizzle theme={null}
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
import { sql } from "drizzle-orm";

const lines = createInterface({
  input: createReadStream("synonyms.txt"),
  crlfDelay: Infinity,
});

for await (const rule of lines) {
  await db.execute(sql`INSERT INTO shop_synonyms (rule) VALUES (${rule})`);
}
```

```python Django theme={null}
from django.db import connection

with open('synonyms.txt') as rules, connection.cursor() as cursor:
    cursor.executemany(
        'INSERT INTO shop_synonyms (rule) VALUES (%s)',
        [(line.rstrip('\r\n'),) for line in rules],
    )
```

```python SQLAlchemy theme={null}
from sqlalchemy import text

with open('synonyms.txt') as rules, engine.begin() as conn:
    rows = [{'rule': line.rstrip('\r\n')} for line in rules]
    if rows:
        conn.execute(
            text('INSERT INTO shop_synonyms (rule) VALUES (:rule)'),
            rows,
        )
```

```ruby Rails theme={null}
rules = File.readlines("synonyms.txt", chomp: true)
ShopSynonym.insert_all(rules.map { |rule| { rule: rule } })
```

```cs EF Core theme={null}
using Microsoft.EntityFrameworkCore;

foreach (var rule in File.ReadLines("synonyms.txt"))
{
    await dbContext.Database.ExecuteSqlInterpolatedAsync(
        $"INSERT INTO shop_synonyms (rule) VALUES ({rule})"
    );
}
```

## Tokenizers

For correct results, it is important that the synonym index uses the same tokenizer as the field being searched against.
This is because at query time, the query is tokenized using the field's tokenizer, and then those tokens are used to search
the synonym index.

For example, if the field `description` is configured to use `pdb.simple('stemmer=english')`, the synonym rule should be
indexed using that same tokenizer.

```sql SQL theme={null}
CREATE INDEX shop_synonyms_en_idx ON shop_synonyms
USING paradedb ((rule::pdb.simple('stemmer=english')));
```

```ts Drizzle theme={null}
import { sql } from "drizzle-orm";

await db.execute(sql`
  CREATE INDEX shop_synonyms_en_idx ON shop_synonyms
  USING paradedb ((rule::pdb.simple('stemmer=english')));
`);
```

```python Django theme={null}
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("""
        CREATE INDEX shop_synonyms_en_idx ON shop_synonyms
        USING paradedb ((rule::pdb.simple('stemmer=english')));
    """)
```

```python SQLAlchemy theme={null}
from sqlalchemy import text

with engine.begin() as conn:
    conn.execute(text("""
        CREATE INDEX shop_synonyms_en_idx ON shop_synonyms
        USING paradedb ((rule::pdb.simple('stemmer=english')));
    """))
```

```ruby Rails theme={null}
ActiveRecord::Base.connection.execute <<~SQL
  CREATE INDEX shop_synonyms_en_idx ON shop_synonyms
  USING paradedb ((rule::pdb.simple('stemmer=english')));
SQL
```

```cs EF Core theme={null}
using Microsoft.EntityFrameworkCore;

await dbContext.Database.ExecuteSqlRawAsync("""
    CREATE INDEX shop_synonyms_en_idx ON shop_synonyms
    USING paradedb ((rule::pdb.simple('stemmer=english')));
    """);
```

If your queries require different tokenizers for different fields, create one synonym index for each tokenizer on the same table.

## Configuration

Larger synonym sets are more expensive and slow down query performance. The following settings tune the tradeoff between
synonym expansion and performance.

**paradedb.synonyms\_max\_alternatives** (default: 32)

Caps the alternatives for each matching word or phrase, keeping the original
terms when the rule includes them. It also caps the total number of phrase
combinations searched by a phrase query.

**paradedb.synonyms\_max\_rules\_per\_key** (default: 1024)

Caps the rules read for each synonym key (a word or phrase) in each segment of
the synonym index. Without a matching index, it caps the matching rules read
from the subquery for each key.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.