Keyword Search
Rank knowledge documents with a vector database's lexical search implementation.
Keyword search uses the selected vector database's lexical search implementation.
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.pgvector import PgVector, SearchType
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge = Knowledge(
vector_db=PgVector(
table_name="docs",
db_url=db_url,
search_type=SearchType.keyword,
),
)How It Works
With PgVector, keyword search:
- Converts document content to a PostgreSQL
tsvector. - Converts the query with
websearch_to_tsqueryby default. - Orders rows by PostgreSQL's
ts_rank_cdscore.
Each result's metadata includes similarity_score, the ts_rank_cd score mapped to 0 to 1 with rank / (rank + 0.1). Hybrid search uses the same scale for its text component.
Set prefix_match=True to build a prefix query from the query tokens. Other vector databases implement keyword search differently.
When to Use Keyword Search
| Query Pattern | Why Test Keyword Search |
|---|---|
| Product names and technical terms | Lexical ranking retains the query terms |
| Error codes and identifiers | Embedding similarity may not preserve the token |
| Quoted terms or operators | PgVector's default parser accepts PostgreSQL web-search syntax |
Test vector search for conceptual queries. Test hybrid search when both lexical and vector signals affect relevance.
Configuration
Basic Setup
from agno.vectordb.pgvector import PgVector, SearchType
vector_db = PgVector(
table_name="docs",
db_url="postgresql+psycopg://ai:ai@localhost:5532/ai",
search_type=SearchType.keyword,
prefix_match=False,
)A reranker passed to Knowledge reorders keyword search results too. The deprecated PgVector reranker parameter applies to vector and hybrid search only. See Reranking.
Example
Before running, set OPENAI_API_KEY in the same shell:
export OPENAI_API_KEY="your-openai-api-key"On Windows PowerShell, use $env:OPENAI_API_KEY = "your-openai-api-key".
Install the dependencies and start a PostgreSQL instance with pgvector enabled:
uv pip install -U agno openai pgvector psycopg pypdf sqlalchemyfrom agno.knowledge.knowledge import Knowledge
from agno.vectordb.pgvector import PgVector, SearchType
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge = Knowledge(
vector_db=PgVector(
table_name="recipes",
db_url=db_url,
search_type=SearchType.keyword,
),
)
knowledge.insert(
url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf",
)
results = knowledge.search("chicken coconut soup", max_results=5)
for doc in results:
print(doc.content[:200])