Neo4j 中的全文搜索
| 请注意,在 Neo4j 3.5 中,全文搜索作为 Cypher 存储过程的一部分提供。更多文档可在此处查阅:/docs/cypher-manual/current/indexes-for-full-text-search/#administration-indexes-fulltext-search-create-and-configure。 |
Neo4j 中的全文搜索通过全文模式(fulltext)模式索引实现。全文模式索引以事务方式创建、删除和更新,并会在整个集群中自动复制。
例如,假设我们有一个包含图书和电影的数据库。这两类节点都拥有属性 title 和 description,但只有图书拥有属性 review。
我们可以为标签为 :Movie 或 :Book、并具有属性 title、description 与 review 的节点创建全文索引,并将其命名为 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
| node.title | node.review | score |
|---|---|---|
"Full Metal Jacket" |
<null> |
0.8093575239181519 |
"The Jacket" |
<null> |
0.1152719184756279 |
"Full Moon High" |
<null> |
0.0836455449461937 |
"Yellow Jacket" |
<null> |
0.07204495370388031 |
因此,电影节点也会被加入索引,即使它们只具有其中一个被索引的标签,且仅包含两个被索引的属性。
此外,如您所见,全文索引在返回所有精确匹配的同时,还会返回给定查询的近似匹配。每条结果条目旁边返回的 score 表示索引认为该条目与查询匹配的程度。结果始终按照分数降序返回,匹配度最高的条目排在最前。
如果我们只想获取与输入的搜索字符串完全匹配的结果怎么办?将 “Full Metal Jacket” 放在引号中即可只返回精确匹配。
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", "'Full Metal Jacket'") YIELD node, score
RETURN node.title, score
| node.title | score |
|---|---|
|
|
我们也可以使用逻辑运算符,例如 AND 和 OR,来搜索多个词。
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", 'full AND metal') YIELD node, score
RETURN node.title, score
在我们的数据库中,只有 “Full Metal Jacket” 这部电影同时包含单词 “full” 与 “metal”。
| node.title | score |
|---|---|
|
|
也可以仅针对特定属性进行搜索,只需在要搜索的文本前加上属性名和冒号。
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", 'description:"surreal adventure"') YIELD node, score
RETURN node.title, node.description, score
| node.title | node.description | score |
|---|---|---|
|
|
|
与节点类似,全文索引也可以在关系上创建。
有关 Neo4j 中全文搜索的完整说明,请参阅:/docs/cypher-manual/current/indexes-for-full-text-search/。
全文模式索引由 Apache Lucene 索引与搜索库提供支持。Lucene 查询语法的完整说明可在 Lucene 文档 中找到。
此页面有帮助吗?