全文 JSON 搜索¶
MatrixOne Python SDK 的 JSON 全文解析器适用于存放在文本列中的 JSON 内容。教程使用 FulltextIndex(..., parser="json") 建索引、用 boolean_match() 检索。该示例查找 JSON 值,不检索 JSON 键。
定义列、索引和查询¶
将 JSON 对象序列化后写入 TEXT 列。以下片段假定 client 已连接:
import json
from matrixone import FulltextIndex
from matrixone.sqlalchemy_ext import boolean_match
from matrixone.orm import declarative_base
from sqlalchemy import BigInteger, Column, Text
Base = declarative_base()
class Product(Base):
__tablename__ = "products"
id = Column(BigInteger, primary_key=True)
specifications = Column(Text)
features = Column(Text)
__table_args__ = (
FulltextIndex("idx_specs", "specifications", parser="json"),
FulltextIndex("idx_features", "features", parser="json"),
)
product = {
"id": 1,
"specifications": json.dumps({"processor": "Intel Core i9", "ram": "32GB DDR5"}),
"features": json.dumps({"rgb_keyboard": True, "cooling": "liquid cooling"}),
}
client.fulltext_index.enable_fulltext()
client.create_table(Product)
client.batch_insert(Product, [product])
results = client.query(Product).filter(
boolean_match(Product.specifications).must("Intel")
).execute()
Intel 能匹配 Intel Core i9 这个值;搜索 processor 不会因为它是 JSON 键而命中。嵌套 JSON 的值也会被索引。布尔值按文本检索,例如将 true 作为搜索词;数组中的元素可单独搜索:
# features 中包含 {"rgb_keyboard": true, "ports": ["USB-C", "HDMI"]}
has_true = client.query(Product).filter(
boolean_match(Product.features).must("true")
).execute()
has_usb_c = client.query(Product).filter(
boolean_match(Product.features).must("USB-C")
).execute()
全文查询可以与普通字段条件组合,例如先按 category 或价格筛选,再匹配 JSON 文本。读取查询结果中的 JSON 字段时,可用 json.loads() 还原 Python 对象。
常见排查¶
确认列按
TEXT存储 JSON 字符串,并用json.dumps()序列化。确认索引声明使用
parser="json"。检查搜索词是否是 JSON 值,而不是键名。
核对查询的列和测试数据字段一致;教程示例分别在
specifications、features列搜索。
相关文档¶
JSON 路径检索示例:按 JSON 路径提取字段,与全文搜索 JSON 值的用途不同。
FULLTEXT2SQL 检索示例:另一个 SQL 全文检索接口。