全文自然语言搜索¶
本页对应 MatrixOne Python SDK 的自然语言全文检索示例,使用 FulltextIndex 建索引、natural_match() 写查询。它与 SQL FULLTEXT2 的接口形式不同;SQL 示例见 FULLTEXT2 检索示例。
建立索引并查询¶
教程将标题和正文加入同一个全文索引,并使用 BM25 相关性算法。以下是模型和查询片段;client 应先连接 MatrixOne:
from matrixone import FulltextIndex, FulltextAlgorithmType
from matrixone.sqlalchemy_ext import natural_match
from matrixone.orm import declarative_base
from sqlalchemy import BigInteger, Column, String, Text
Base = declarative_base()
class Article(Base):
__tablename__ = "articles"
id = Column(BigInteger, primary_key=True)
title = Column(String(200))
content = Column(Text)
__table_args__ = (
FulltextIndex(
"idx_article_search",
["title", "content"],
algorithm=FulltextAlgorithmType.BM25,
),
)
client.fulltext_index.enable_fulltext()
client.execute('SET ft_relevancy_algorithm = "BM25"')
client.create_table(Article)
client.batch_insert(Article, [{
"id": 1,
"title": "Getting Started with Machine Learning",
"content": "Machine learning is revolutionizing technology...",
}])
# Query with natural_match
results = client.query(Article).filter(
natural_match(Article.title, Article.content, query="how to learn python")
).execute()
教程中的查询接口会自动处理常见停用词;例如 how、to 不作为主要检索词,查询会侧重 learn 和 python。多词查询可匹配其中相关词项;如果需要精确控制必含、排除或提升的词项,请使用布尔模式。
可在查询中继续添加普通 SQL 条件,例如分类、作者或评分过滤。具体分词和相关性表现应使用目标版本和真实语料验证。
相关文档¶
FULLTEXT2SQL 检索示例:不同的 SQL 接口示例。