fix: use native Milvus lexical search

Signed-off-by: Cheney Zhang <chen.zhang@zilliz.com>
This commit is contained in:
Cheney Zhang
2026-07-01 06:51:35 +00:00
parent 9b395fe9d5
commit 2c81e22e28
5 changed files with 197 additions and 28 deletions
+148 -7
View File
@@ -54,9 +54,18 @@ FIELD_ID = "id"
FIELD_DOCUMENT = "document"
FIELD_METADATA = "metadata"
FIELD_VECTOR = "vector"
FIELD_SPARSE = "sparse"
DOCUMENT_MAX_LENGTH = 65535
DRAWER_ID_MAX_LENGTH = 512
RESERVED_FIELDS = {FIELD_ID, FIELD_DOCUMENT, FIELD_METADATA, FIELD_VECTOR, "distance", "score"}
RESERVED_FIELDS = {
FIELD_ID,
FIELD_DOCUMENT,
FIELD_METADATA,
FIELD_VECTOR,
FIELD_SPARSE,
"distance",
"score",
}
_FIELD_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_TOKEN_RE = re.compile(r"\w{2,}", re.UNICODE)
@@ -339,6 +348,7 @@ class MilvusCollection(BaseCollection):
self._lock = threading.RLock()
self._closed = False
self._known_dimension: Optional[int] = None
self._known_native_lexical: Optional[bool] = None
def _ensure_open(self) -> None:
if self._closed or self._backend._closed:
@@ -396,11 +406,15 @@ class MilvusCollection(BaseCollection):
)
return
if not self._remote_exists():
self._backend._create_remote_collection(
self._client, self._remote_collection, dimension
native_lexical = self._backend._create_remote_collection(
self._client,
self._remote_collection,
dimension,
enable_native_lexical=self._backend._enable_native_lexical(self._config),
)
self._backend._load_remote_collection(self._client, self._remote_collection)
self._known_dimension = dimension
self._known_native_lexical = native_lexical
self._backend._write_marker(self._palace, self._config)
return
remote_dim = self._remote_dimension()
@@ -411,6 +425,26 @@ class MilvusCollection(BaseCollection):
)
self._known_dimension = remote_dim or dimension
def _has_native_lexical(self) -> bool:
if self._known_native_lexical is not None:
return self._known_native_lexical
if not self._remote_exists():
self._known_native_lexical = False
return False
try:
info = self._client.describe_collection(self._remote_collection)
except Exception:
logger.debug("Milvus describe_collection failed", exc_info=True)
self._known_native_lexical = False
return False
fields = []
if isinstance(info, dict):
fields = info.get("fields") or (info.get("schema") or {}).get("fields") or []
self._known_native_lexical = any(
(field.get("name") or field.get("field_name")) == FIELD_SPARSE for field in fields
)
return self._known_native_lexical
def _output_fields(self, spec: _IncludeSpec) -> list[str]:
fields = [FIELD_ID]
if spec.documents:
@@ -515,9 +549,10 @@ class MilvusCollection(BaseCollection):
)
if not rows:
return
existing = self.get(ids=list(ids), include=[])
if existing.ids:
raise ValueError(f"ids already exist in milvus collection: {existing.ids}")
if self._remote_exists():
existing = self.get(ids=list(ids), include=[])
if existing.ids:
raise ValueError(f"ids already exist in milvus collection: {existing.ids}")
self._ensure_remote_collection(dimension)
self._client.insert(collection_name=self._remote_collection, data=rows)
self._flush()
@@ -802,6 +837,14 @@ class MilvusCollection(BaseCollection):
def lexical_search(self, *, query: str, n_results: int = 10, where: Optional[dict] = None):
filter_expr = translate_where(where)
if self._has_native_lexical():
native = self._native_lexical_search(
query=query,
n_results=n_results,
filter_expr=filter_expr,
)
if native is not None:
return native
rows = self._collect_by_filter(
filter_expr=filter_expr,
output_fields=[FIELD_ID, FIELD_DOCUMENT, FIELD_METADATA],
@@ -820,6 +863,43 @@ class MilvusCollection(BaseCollection):
hits.sort(key=lambda hit: hit.score, reverse=True)
return LexicalResult(hits=hits[:n_results])
def _native_lexical_search(
self,
*,
query: str,
n_results: int,
filter_expr: str,
) -> Optional[LexicalResult]:
try:
kwargs = {
"collection_name": self._remote_collection,
"data": [query],
"anns_field": FIELD_SPARSE,
"output_fields": [FIELD_ID, FIELD_DOCUMENT, FIELD_METADATA],
"limit": int(n_results),
"search_params": {"params": {}},
}
if filter_expr:
kwargs["filter"] = filter_expr
raw = self._client.search(**kwargs)
except Exception:
logger.debug(
"Milvus native BM25 search failed; using local BM25 fallback", exc_info=True
)
return None
rows = [self._row_from_search_hit(hit) for hit in (raw[0] if raw else [])]
return LexicalResult(
hits=[
LexicalHit(
id=str(row.get(FIELD_ID, "")),
document=row.get(FIELD_DOCUMENT, ""),
metadata=self._extract_metadata(row),
score=float(row.get("distance", row.get("score", 0.0)) or 0.0),
)
for row in rows
]
)
def close(self) -> None:
self._closed = True
@@ -1005,6 +1085,10 @@ class MilvusBackend(BaseBackend):
self._clients[config] = client
return client
@staticmethod
def _enable_native_lexical(config: _MilvusConfig) -> bool:
return bool(config.uri and _is_server_uri(config.uri))
def get_collection(self, *args, **kwargs) -> MilvusCollection:
palace, collection_name, create, options = self._normalize_args(args, kwargs)
config = self._effective_config(palace, options)
@@ -1094,7 +1178,44 @@ class MilvusBackend(BaseBackend):
)
raise TypeError("get_collection requires palace= or a positional palace_path")
def _create_remote_collection(self, client, collection_name: str, dimension: int) -> None:
def _create_remote_collection(
self,
client,
collection_name: str,
dimension: int,
*,
enable_native_lexical: bool,
) -> bool:
if enable_native_lexical:
try:
self._create_remote_collection_schema(
client,
collection_name,
dimension,
enable_native_lexical=True,
)
return True
except Exception:
logger.debug(
"Milvus native BM25 schema creation failed; retrying dense-only schema",
exc_info=True,
)
self._create_remote_collection_schema(
client,
collection_name,
dimension,
enable_native_lexical=False,
)
return False
def _create_remote_collection_schema(
self,
client,
collection_name: str,
dimension: int,
*,
enable_native_lexical: bool,
) -> None:
from pymilvus import DataType
schema = client.create_schema(auto_id=False, enable_dynamic_field=True)
@@ -1108,6 +1229,7 @@ class MilvusBackend(BaseBackend):
field_name=FIELD_DOCUMENT,
datatype=DataType.VARCHAR,
max_length=DOCUMENT_MAX_LENGTH,
enable_analyzer=enable_native_lexical,
)
schema.add_field(field_name=FIELD_METADATA, datatype=DataType.JSON)
schema.add_field(
@@ -1115,12 +1237,31 @@ class MilvusBackend(BaseBackend):
datatype=DataType.FLOAT_VECTOR,
dim=int(dimension),
)
if enable_native_lexical:
from pymilvus import Function, FunctionType
schema.add_field(field_name=FIELD_SPARSE, datatype=DataType.SPARSE_FLOAT_VECTOR)
schema.add_function(
Function(
name="document_bm25",
input_field_names=[FIELD_DOCUMENT],
output_field_names=[FIELD_SPARSE],
function_type=FunctionType.BM25,
)
)
index_params = client.prepare_index_params()
index_params.add_index(
field_name=FIELD_VECTOR,
index_type="AUTOINDEX",
metric_type="COSINE",
)
if enable_native_lexical:
index_params.add_index(
field_name=FIELD_SPARSE,
index_type="SPARSE_INVERTED_INDEX",
metric_type="BM25",
params={"inverted_index_algo": "DAAT_MAXSCORE"},
)
client.create_collection(
collection_name=collection_name,
schema=schema,
+1 -1
View File
@@ -115,7 +115,7 @@ def test_milvus_lite_upsert_update_delete_get_order_and_multi_collection(tmp_pat
metadatas=[{"wing": "a"}, {"wing": "b"}],
embeddings=[[1, 0], [0, 1]],
)
closets.upsert(
closets.add(
ids=["one"],
documents=["closet document"],
metadatas=[{"wing": "closet"}],
+2 -2
View File
@@ -15,8 +15,8 @@ Located at `~/.mempalace/config.json`:
| Key | Default | Description |
|-----|---------|-------------|
| `palace_path` | `~/.mempalace/palace` | Where ChromaDB stores your drawers |
| `collection_name` | `mempalace_drawers` | ChromaDB collection name |
| `palace_path` | `~/.mempalace/palace` | Where the default local palace stores your drawers |
| `collection_name` | `mempalace_drawers` | Default backend collection name |
| `people_map` | `{}` | Entity name → AAAK code mappings |
| `max_backups` | `10` | How many timestamped palace backups to keep before the oldest are pruned. Applies to `mempalace migrate` (`<palace>.pre-migrate.*`) and `mempalace repair max-seq-id` (`chroma.sqlite3.max-seq-id-backup-*`), which each write a full copy every run. Set to `0` to keep every backup (e.g. when an external retention policy manages cleanup). |
+44 -18
View File
@@ -8,19 +8,20 @@ memory instead of a palace on each laptop.
This is built from three pieces that already ship in MemPalace:
- the **HTTP transport** for the MCP server (`mempalace-mcp --transport http`),
- a **networked storage backend** ([Qdrant](https://qdrant.tech/) or
[Postgres + pgvector](/guide/configuration)),
- a **networked storage backend** ([Milvus / Zilliz Cloud](https://milvus.io/),
[Qdrant](https://qdrant.tech/), or [Postgres + pgvector](/guide/configuration)),
- optional **GPU embedding** on the server.
::: warning This is a deliberate step away from single-machine local-first
By default MemPalace keeps everything on your own machine. A central server is
still **your** infrastructure — no third-party API, no telemetry, nothing
phones home — but your verbatim memory now lives on a server you operate and
travels over your network. Run every component (Qdrant, the MCP host) on
hardware you control, put it on a private network or VPN, and treat the
bearer token and TLS setup below as mandatory, not optional. Embeddings are
still produced locally on the server by MemPalace; only your own storage
backend ever receives the vectors and text.
still **your** infrastructure — no telemetry, nothing phones home — but your
verbatim memory now lives on a server you operate and travels over your
network. If you choose a managed backend such as Zilliz Cloud, that backend
also receives the vectors and text by design. Run every self-hosted component
(Milvus, Qdrant, Postgres, the MCP host) on hardware you control, put it on a
private network or VPN, and treat the bearer token and TLS setup below as
mandatory, not optional. Embeddings are still produced locally on the server by
MemPalace.
:::
## Architecture
@@ -32,14 +33,32 @@ backend ever receives the vectors and text.
└─────────────┬───────────────
│ vectors + verbatim text
▼
Qdrant / pgvector
Milvus / Qdrant / pgvector
(central storage)
```
## 1. Central storage
Pick a networked backend so all clients share one palace. **Qdrant** needs no
extra Python package — MemPalace talks to its REST API directly.
Pick a networked backend so all clients share one palace. **Milvus** can point
at a self-hosted Milvus server or Zilliz Cloud. Milvus Lite is still local to
one palace directory, so use a server URI for team mode.
Install the optional Milvus driver on the server host:
```bash
pip install mempalace[milvus]
```
Point MemPalace at the shared Milvus endpoint:
```bash
export MEMPALACE_BACKEND=milvus
export MEMPALACE_MILVUS_URI=https://your-cluster.api.region.zillizcloud.com
export MEMPALACE_MILVUS_TOKEN=your-token
```
Prefer Qdrant? It needs no extra Python package — MemPalace talks to its REST
API directly.
Run Qdrant (Docker shown; use a managed/self-hosted instance you control):
@@ -59,14 +78,20 @@ export MEMPALACE_QDRANT_API_KEY=your-qdrant-api-key # if your Qdrant requires
| Variable | Default | Purpose |
|---|---|---|
| `MEMPALACE_BACKEND` | `chroma` | Set to `qdrant` (or `pgvector`) to select the backend |
| `MEMPALACE_BACKEND` | `chroma` | Set to `milvus`, `qdrant`, or `pgvector` to select the backend |
| `MEMPALACE_MILVUS_URI` | per-palace Milvus Lite | Milvus server / Zilliz Cloud URI |
| `MEMPALACE_MILVUS_TOKEN` | _(none)_ | Token for Milvus server / Zilliz Cloud |
| `MEMPALACE_MILVUS_DB_NAME` | _(none)_ | Optional Milvus database name |
| `MEMPALACE_MILVUS_NAMESPACE` | _(none)_ | Optional Milvus collection namespace prefix |
| `MEMPALACE_MILVUS_CONSISTENCY_LEVEL` | `Strong` | Milvus consistency level |
| `MEMPALACE_QDRANT_URL` | `http://localhost:6333` | Qdrant REST endpoint |
| `MEMPALACE_QDRANT_API_KEY` | _(none)_ | Sent as the `api-key` header when set |
| `MEMPALACE_QDRANT_NAMESPACE` | _(none)_ | Optional collection namespace prefix |
| `MEMPALACE_QDRANT_TIMEOUT` | backend default | REST request timeout (seconds) |
The backend can also be set with `--backend qdrant` on any `mempalace` /
`mempalace-mcp` command, or with `"backend": "qdrant"` in `config.json`.
The backend can also be set with `--backend milvus` (or `qdrant` /
`pgvector`) on any `mempalace` / `mempalace-mcp` command, or with
`"backend": "milvus"` in `config.json`.
Prefer Postgres? Install `pip install mempalace[pgvector]`, point
`MEMPALACE_BACKEND=pgvector` at a database with the `vector` extension, and
@@ -96,7 +121,7 @@ ready-to-paste client config, and runs in the foreground so Docker/systemd own
the lifecycle.
```bash
mempalace serve --host 0.0.0.0 --port 8765 --backend qdrant
mempalace serve --host 0.0.0.0 --port 8765 --backend milvus
```
Output includes the token and the exact client command. Useful flags:
@@ -159,8 +184,9 @@ whole team.
processes at the same backend collection.
- **Health checks**: `GET /healthz` returns `200 ok` without a token, so it
works as a load-balancer/Kubernetes liveness probe.
- **Backups** are now your storage backend's responsibility (Qdrant snapshots
/ Postgres backups) rather than a single laptop's palace directory.
- **Backups** are now your storage backend's responsibility (Milvus / Zilliz
Cloud backups, Qdrant snapshots, or Postgres backups) rather than a single
laptop's palace directory.
## One-command deployments
+2
View File
@@ -1,6 +1,8 @@
# CLI Commands
All commands accept `--palace <path>` to override the default palace location.
The top-level command also accepts `--backend <name>` to select a storage
backend such as `milvus`, `qdrant`, or `pgvector`.
## `mempalace init`