Metadata-Version: 2.4
Name: kohybrid
Version: 0.1.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,kiwi
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: test
Requires-Dist: pytest>=7; extra == "test"
Requires-Dist: psycopg[binary]>=3.1; extra == "test"
Dynamic: license-file

# kohybrid

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

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

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.

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

```bash
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배
빠른 속도로 냅니다.

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