知识库

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 中的全文搜索通过全文模式索引(fulltext schema indexes)提供支持。全文模式索引以事务方式创建、删除和更新,并在整个集群中自动复制。

例如,假设我们有一个包含书籍和电影的数据库。两者都具有 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 分数

"全金属外壳"

<null>

0.8093575239181519

"夹克"

<null>

0.1152719184756279

"满月高"

<null>

0.0836455449461937

"黄夹克"

<null>

0.07204495370388031

届时,电影节点将被包含在索引中,即使它们只具有其中一个索引标签,并且只有两个索引属性。

此外,正如您所见,全文索引除了返回精确匹配外,还会返回给定查询的近似匹配。与每个结果条目一同返回的 score 表示索引认为该条目与查询的匹配程度。结果始终以分数降序返回,最佳匹配结果条目排在首位。

如果我们只想获取与输入的搜索字符串精确匹配的结果怎么办?当我们用引号括起“Full Metal Jacket”时,我们只得到精确匹配结果

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

"全金属外壳"

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 分数

"全金属外壳"

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 分数

"金属乐队:穿越永恒"

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

1.311632513999939

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

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

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