知识库

Neo4j 中的全文本搜索

请注意,在 Neo4j 3.5 中,全文本搜索作为 Cypher 存储过程的一部分在 Neo4j 中可用。更多文档可以在这里找到: https://neo4j.ac.cn/docs/cypher-manual/current/indexes-for-full-text-search/#administration-indexes-fulltext-search-create-and-configure

Neo4j 中的全文本搜索由全文本模式索引支持。全文本模式索引以事务方式创建、删除和更新,并在整个集群中自动复制。

例如,假设我们有一个包含书籍和电影的数据库。两者都具有属性 titledescription,但只有书籍具有属性 review。

我们可以在具有标签 :Movie:Book 且具有属性 titledescriptionreview 的节点上创建全文本索引。我们将其命名为 titlesAndDescriptions

查询
CALL db.index.fulltext.createNodeIndex("titlesAndDescriptions",["Movie", "Book"],["title", "description", "review"])

让我们看看以下查询得到什么结果

查询
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", "Full Metal Jacket") YIELD node, score
RETURN node.title, node.review, score
表 1. 结果
node.title node.review 得分

"Full Metal Jacket"

<null>

0.8093575239181519

"The Jacket"

<null>

0.1152719184756279

"Full Moon High"

<null>

0.0836455449461937

"Yellow Jacket"

<null>

0.07204495370388031

然后,即使电影节点只有其中一个索引标签和两个索引属性,它们也会包含在索引中。

此外,如您所见,全文本索引除了任何精确匹配之外,还会返回给定查询的近似匹配。与每个结果条目一起返回的得分表示索引认为该条目与查询匹配的程度。结果始终按降序得分返回,其中最佳匹配结果条目放在首位。

如果我们希望仅获取与输入的搜索字符串匹配的结果怎么办?当我们将“Full Metal Jacket”放在引号中时,我们只获得精确匹配

查询
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", "'Full Metal Jacket'") YIELD node, score
RETURN node.title, score
表 2. 结果
node.title 得分

"Full Metal Jacket"

1.3701786994934082

我们还可以使用逻辑运算符(如ANDOR)来搜索术语

查询
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", 'full AND metal') YIELD node, score
RETURN node.title, score

我们数据库中只有“Full Metal Jacket”电影同时包含“full”和“metal”这两个词。

表 3. 结果
node.title 得分

"Full Metal Jacket"

0.7603841423988342

也可以通过在要搜索的文本前面加上属性名称和冒号来搜索特定属性

查询
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", 'description:"surreal adventure"') YIELD node, score
RETURN node.title, node.description, score
表 4. 结果
node.title node.description 得分

"Metallica Through The Never"

"这部电影讲述了年轻的巡演人员 Trip 与乐队一起经历的超现实冒险故事。"

1.311632513999939

与节点类似,可以在关系上创建全文本索引。

有关 Neo4j 中全文本搜索的完整说明,请参阅: https://neo4j.ac.cn/docs/cypher-manual/current/indexes-for-full-text-search/

全文本模式索引由Apache Lucene索引和搜索库提供支持。Lucene 查询语法的完整描述可以在Lucene 文档中找到。