Metadata-Version: 2.4
Name: kohybrid
Version: 0.2.0
Summary: Korean hybrid search for PostgreSQL: morpheme-aware keyword search plus pgvector, fused with RRF
Author: Rion Hwang
License-Expression: MIT
Project-URL: Homepage, https://github.com/RionHwang0/kohybrid
Project-URL: Issues, https://github.com/RionHwang0/kohybrid/issues
Keywords: korean,hybrid search,pgvector,postgresql,rag,full-text search,bm25,kiwi,langchain
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: Korean
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Database
Classifier: Topic :: Text Processing :: Indexing
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: kiwipiepy>=0.18
Requires-Dist: psycopg>=3.1
Provides-Extra: binary
Requires-Dist: psycopg[binary]>=3.1; extra == "binary"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.3; extra == "langchain"
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Requires-Dist: psycopg[binary]>=3.1; extra == "test"
Requires-Dist: langchain-core>=0.3; extra == "test"
Dynamic: license-file

# kohybrid

Korean hybrid search for PostgreSQL: morpheme-aware BM25 keyword search plus
[pgvector](https://github.com/pgvector/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](https://github.com/bab2min/kiwipiepy)
morphological analyzer before it reaches PostgreSQL and stores normalized
lexemes in an ordinary `tsvector` column:

```text
대한민국에서 가장 높은 산은?  ->  대한민국 높다 산
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

```bash
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

```python
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

```python
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:

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

### LangChain

```python
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.

```python
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](https://korquad.github.io/) 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`](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

```bash
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`)도
제공합니다.

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