Skip to main content

kohybrid

Korean hybrid search for PostgreSQL: morpheme-aware BM25 keyword search plus pgvector vector search, fused with Reciprocal Rank Fusion in a single SQL query.

한국어 설명

Why

PostgreSQL's full-text search splits text on spaces and punctuation. Korean attaches particles and endings directly to words, so 대한민국에서, 대한민국의 and 대한민국은 are three different tokens and a keyword search for one misses the others. Common workarounds are character bigrams (pg_bigm) or sending keyword search to a separate Elasticsearch cluster.

kohybrid analyzes text with the Kiwi morphological analyzer before it reaches PostgreSQL and stores normalized lexemes in an ordinary tsvector column:

대한민국에서 가장 높은 산은?  ->  대한민국 높다 산
PostgreSQL 16에서 벡터를 검색했습니다  ->  postgresql 16 벡터 검색

Keyword results are ranked with BM25, computed inside PostgreSQL from an inverted index that triggers keep current. No PostgreSQL extension beyond pgvector is needed, so it works on managed databases (RDS, Aurora, Cloud SQL, Azure Database for PostgreSQL, Supabase, Neon) where custom text search parsers cannot be installed.

Install

pip install "kohybrid[binary]"              # psycopg binary build included
pip install "kohybrid[binary,langchain]"    # plus the LangChain retriever

Requires Python 3.10+, PostgreSQL with the vector extension available for vector or hybrid search (keyword-only stores need nothing extra).

Quick start

import psycopg
from kohybrid import HybridStore

def embed(texts: list[str]) -> list[list[float]]:
    ...  # any embedding model: OpenAI, Azure OpenAI, BGE-M3, ...

conn = psycopg.connect("postgresql://user:pass@localhost/db")
store = HybridStore(conn, "docs", dimensions=1024, embed=embed)
store.create_table()  # table + GIN (keywords, metadata) + HNSW (vectors)

store.add(
    ["대한민국의 수도는 서울이다.", "한라산은 대한민국에서 가장 높은 산이다."],
    metadatas=[{"source": "wiki"}, {"source": "wiki"}],
)

for hit in store.search("대한민국에서 제일 높은 산", k=3):
    print(hit.score, hit.vector_rank, hit.keyword_rank, hit.content)

Search options

store.search(query, k=5,
             mode="hybrid",          # "hybrid" | "keyword" | "vector"
             filter={"source": "wiki"},  # metadata @> filter
             match="any",            # "any" (OR) | "all" (AND) query words
             candidates=40,          # per-retriever list size before fusion
             rrf_k=60, vector_weight=1.0, keyword_weight=1.0,
             query_embedding=None)   # pass a precomputed embedding

Each result carries vector_rank and keyword_rank, so you can see which retriever found it. When a query has no searchable words (for example only punctuation), hybrid search falls back to vectors.

Keyword ranking

HybridStore(..., ranking="bm25") is the default. BM25 weighs words that are rare in your collection more than common ones (검색 in every document matters less than 형태소분석기 in two). Collection statistics live in three helper tables next to yours (<table>_bm25_terms, _bm25_stats, _bm25_postings), maintained by statement-level triggers, so rows written with plain SQL are counted too. drop_table() removes them.

ranking="ts_rank" uses PostgreSQL's built-in ranking instead: no helper tables and lower latency, slightly lower accuracy (see the benchmark).

Upgrading a table created with kohybrid 0.1:

HybridStore(conn, "docs", dimensions=1024, embed=embed).enable_bm25()  # once

LangChain

from kohybrid import HybridStore
from kohybrid.langchain import KohybridRetriever

store = HybridStore(conn, "docs", dimensions=1536,
                    embed=embeddings.embed_documents, embed_query=embeddings.embed_query)
store.create_table()
retriever = KohybridRetriever(store=store, k=5)      # mode="hybrid" by default
retriever.add_documents(documents)                    # LangChain Document objects
docs = retriever.invoke("대한민국에서 제일 높은 산")
docs = retriever.invoke("서울", mode="keyword", filter={"source": "wiki"})

Returned documents keep their metadata and add kohybrid_score, kohybrid_vector_rank and kohybrid_keyword_rank.

Use the tokenizer on its own

The tokenizer is independent of the store. Use it with your own schema, or feed its lexemes to another keyword engine.

from kohybrid import KoreanTokenizer, tsvector_literal, tsquery_literal

tok = KoreanTokenizer()                      # or KoreanTokenizer(include_predicates=False)
tok.tokenize("아름다운 꽃이 피었다")           # ['아름답다', '꽃', '피다']
tsvector_literal(tok.tokenize(doc))          # "'아름답다':1 '꽃':2 ..." for ::tsvector
tsquery_literal(tok.tokenize(query))         # "'꽃' | '피다'" for ::tsquery

Lexemes are passed as tsvector/tsquery literals rather than through to_tsvector, because PostgreSQL's parser would split them again (C++, hyphenated words). A user dictionary can be added by passing your own kiwipiepy.Kiwi instance: KoreanTokenizer(kiwi=my_kiwi).

Benchmark

Keyword retrieval on KorQuAD 1.0 dev: for each of 5,774 questions, find its source paragraph among 964 paragraphs. All methods run in the same PostgreSQL 16 database and match any query word. Reproduce with benchmarks/korquad_keyword.py.

Method R@1 R@5 R@10 MRR@10
PostgreSQL simple config, ts_rank 0.720 0.848 0.877 0.775
Character bigrams (pg_bigm-style), ts_rank 0.887 0.979 0.989 0.927
kohybrid morphemes, ts_rank 0.882 0.970 0.981 0.921
kohybrid morphemes, BM25 (default) 0.896 0.980 0.988 0.934

Latency and storage on the same data, measured through HybridStore.search(mode="keyword") including tokenization:

Ranking ms/query Extra storage
ts_rank 2.9 none
bm25 9.9 inverted index, about 1.8x the documents table

Character bigrams reach similar accuracy to morphemes under ts_rank but need about twice the index size and were about 4x slower per query in the same database. KorQuAD questions reuse wording from their paragraphs, which favors bigrams; datasets with paraphrased queries are on the roadmap. Timings depend on hardware. Vector and hybrid results depend on your embedding model and are not included here.

Tests

pip install -e ".[test]"
pytest                                   # unit tests
KOHYBRID_TEST_DSN=postgresql://user:pass@localhost/db pytest   # + PostgreSQL integration tests

Roadmap

  • LlamaIndex retriever
  • Async API (psycopg.AsyncConnection)
  • Benchmarks with paraphrased Korean queries and hybrid retrieval

License

MIT. Kiwi (kiwipiepy) is Apache-2.0; KorQuAD is CC BY-ND 2.0 KR and is downloaded by the benchmark script, not redistributed.


한국어

kohybrid는 PostgreSQL에서 한국어 하이브리드 검색(형태소 키워드 검색 + pgvector 벡터 검색)을 한 번의 SQL 쿼리로 수행하는 Python 라이브러리입니다.

PostgreSQL 기본 전문 검색은 띄어쓰기 단위로 단어를 나누기 때문에 대한민국에서와 대한민국의를 서로 다른 단어로 봅니다. kohybrid는 Kiwi 형태소 분석기로 조사·어미를 걷어낸 원형(대한민국, 높다)을 tsvector 컬럼에 저장하고, pgvector 결과와 RRF로 합칩니다. 키워드 순위는 PostgreSQL 안에서 BM25로 계산하고, pgvector 외에 별도 확장이 필요 없어 RDS·Aurora·Cloud SQL·Azure·Supabase 같은 관리형 DB에서도 그대로 쓸 수 있습니다.

KorQuAD 1.0 기준으로 PostgreSQL 기본 설정보다 Recall@1이 0.720에서 0.896으로 올랐습니다. LangChain 리트리버(kohybrid.langchain.KohybridRetriever)도 제공합니다.

버그 제보와 제안은 이슈로 남겨 주세요.

Metadata

Release files for kohybrid 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kohybrid 0.2.0
File Size Uploaded Provenance Actions
kohybrid-0.2.0.tar.gz 25.4 kB With provenance Details for kohybrid-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kohybrid 0.2.0
File Interpreter ABI Platform Actions
kohybrid-0.2.0-py3-none-any.whl Python 3 none any Details for kohybrid-0.2.0-py3-none-any.whl

Total release size: 45.2 kB

Release files / kohybrid-0.2.0.tar.gz

Download URL kohybrid-0.2.0.tar.gz
Size 25.4 kB
Tags Source
SHA-256 checksum
How to use checksums
c0fc94135added73772295a600ea68c803463bada92c88c4cac509bdebc9bc16
BLAKE2b-256 checksum
How to use checksums
64f872c16d46f570395e26bf200b8540c13fd15208c1ae686ed82582cfef34ef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / kohybrid-0.2.0-py3-none-any.whl

Download URL kohybrid-0.2.0-py3-none-any.whl
Size 19.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
af7e28274936fb6888875f672dfa649d0952ffbd62909456f24092e448dea095
BLAKE2b-256 checksum
How to use checksums
f02c759a62578d646fd5be116bcc02e61277888808a560262d78ccf800ef4da3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for kohybrid 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kohybrid-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page