• 關於 Milvus
  • 開始使用
  • 概念
  • 使用者指南
  • 資料匯入
  • AI 工具
  • 管理指南
  • 工具
  • 整合
  • 教學
  • 常見問題
  • API Reference

RTREECompatible with Milvus 2.6.4+

RTREE 索引是一種以樹狀結構為基礎的資料結構,可加速對 Milvus 中GEOMETRY 欄位的查詢。如果您的資料庫以Well-known text (WKT)格式儲存幾何物件,例如點、線或多邊形,而且您想要加速空間篩選,RTREE 是理想的選擇。

如何運作

Milvus 使用RTREE 索引來有效率地組織和篩選幾何資料,過程分為兩個階段:

階段 1:建立索引

  1. 建立葉節點:對於每個幾何物件,計算其最小邊界矩形(MBR),也就是完全包含該物件的最小矩形,並將其儲存為葉節點。

  2. 群組成較大的方塊:將附近的葉節點聚類在一起,並以新的 MBR 包覆每個群組,形成內部節點。例如,B組包含DEC組包含FG

  3. 新增根節點:新增一個根節點,其 MBR 涵蓋所有內部群組,形成高度平衡的樹狀結構。

How Retree Works Retree 如何運作

第二階段:加速查詢

  1. 形成查詢 MBR:為您的查詢幾何圖形計算 MBR。

  2. 修剪分支:從根部開始,將查詢 MBR 與每個內部節點進行比較。跳過任何 MBR 與查詢 MBR 沒有交集的分支。

  3. 收集候選:下降到相交的分支,收集候選葉節點。

  4. 精確匹配:對於每個候選節點,執行精確空間謂詞,以確定真正的匹配。

建立 RTREE 索引

您可以在集合模式中定義的GEOMETRY 欄位上建立RTREE 索引。

from pymilvus import MilvusClient

client = MilvusClient(uri="http://localhost:19530") # Replace with your server address

# Assume you have defined a GEOMETRY field named "geo" in your collection schema

# Prepare index parameters
index_params = client.prepare_index_params()

# Add RTREE index on the "geo" field
index_params.add_index(
    field_name="geo",
    index_type="RTREE",      # Spatial index for GEOMETRY
    index_name="rtree_geo",  # Optional, name your index
    params={}                # No extra params needed
)

# Create the index on the collection
client.create_index(
    collection_name="geo_demo",
    index_params=index_params
)

使用 RTREE 進行查詢

您可以使用filter 表達式中的幾何運算符號進行過濾。當目標GEOMETRY 欄位上存在RTREE 時,Milvus 會使用它來自動刪除候選項目。如果沒有索引,篩選就會退回到完全掃描。

如需可用的特定幾何運算符號的完整清單,請參閱幾何運算符號

範例 1:僅篩選

尋找指定多邊形內的所有幾何物件:

filter_expr = "ST_CONTAINS(geo, 'POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))')"

res = client.query(
    collection_name="geo_demo",
    filter=filter_expr,
    output_fields=["id", "geo"],
    limit=10
)
print(res)   # Expected: a list of rows where geo is entirely inside the polygon

範例 2:向量搜尋 + 空間篩選器

尋找同時與某條線相交的最近向量:

# Assume you've also created an index on "vec" and loaded the collection.
query_vec = [[0.1, 0.2, 0.3, 0.4, 0.5]]
filter_expr = "ST_INTERSECTS(geo, 'LINESTRING (1 1, 2 2)')"

hits = client.search(
    collection_name="geo_demo",
    data=query_vec,
    limit=5,
    filter=filter_expr,
    output_fields=["id", "geo"]
)
print(hits)  # Expected: top-k by vector similarity among rows whose geo intersects the line

有關如何使用GEOMETRY 欄位的詳細資訊,請參閱幾何欄位

移除索引

使用drop_index() 方法從集合中移除現有索引。

  • v2.6.3或更早版本中,您必須先釋放集合,才能刪除標量索引。

  • v2.6.4或更新版本開始,您可以在不再需要標量索引時直接將其刪除,而不需要先釋放集合。

client.drop_index(
    collection_name="geo_demo",   # Name of the collection
    index_name="rtree_geo" # Name of the index to drop
)