Skip to main content

kohybrid

Korean hybrid search for PostgreSQL: morpheme-aware 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 벡터 검색

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

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.

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, match any query word, and rank with ts_rank (normalization 1). Reproduce with benchmarks/korquad_keyword.py.

Method R@1 R@5 R@10 MRR@10 Index size ms/query
PostgreSQL simple config 0.720 0.848 0.877 0.775 — 0.5
Character bigrams (pg_bigm-style) 0.887 0.979 0.989 0.927 6.0 MB 3.0
kohybrid morphemes 0.882 0.970 0.981 0.921 2.9 MB 0.8

Morpheme search matches character bigrams on accuracy with less than half the index size and about 4x faster queries, and is far ahead of PostgreSQL's built-in configuration. 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

  • BM25 ranking with document frequencies (measured +1.4 points R@1 on KorQuAD)
  • LangChain and LlamaIndex retriever adapters
  • 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로 합칩니다. pgvector 외에 별도 확장이 필요 없어 RDS·Aurora·Cloud SQL·Azure·Supabase 같은 관리형 DB에서도 그대로 쓸 수 있습니다.

KorQuAD 1.0 기준으로 PostgreSQL 기본 설정보다 Recall@1이 0.720에서 0.882로 올랐고, 바이그램 방식과 비슷한 정확도를 절반 이하의 인덱스 크기와 약 4배 빠른 속도로 냅니다.

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

Metadata

Release files for kohybrid 0.1.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.1.0
File Size Uploaded Provenance Actions
kohybrid-0.1.0.tar.gz 18.4 kB With provenance Details for kohybrid-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 32.1 kB

Release files / kohybrid-0.1.0.tar.gz

Download URL kohybrid-0.1.0.tar.gz
Size 18.4 kB
Tags Source
SHA-256 checksum
How to use checksums
184acdd38c84bbae0f680da50bf14355e9bb2b733c7d39c8d19aaae4f4c406fd
BLAKE2b-256 checksum
How to use checksums
aa14777768260d17637acd8457c354c1036d250936beef7ffe068d39c3b633a4
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.1.0-py3-none-any.whl

Download URL kohybrid-0.1.0-py3-none-any.whl
Size 13.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
534f37e03cae7e0ca8ec74b64b056d9ff1d2d962cecfa9e171b5f40dcf4fda64
BLAKE2b-256 checksum
How to use checksums
00295c8611004adcc91cec545a49c55577c4f4ed58e233b2611749673fe2f8e1
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.1.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.1.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.1.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