索引和约束

这是 GraphQL Library 7 版本的文档。对于长期支持 (LTS) 版本 5,请参考 GraphQL Library 5 LTS 版本

本页面介绍了如何在 Neo4j GraphQL 库中使用索引和约束。

@fulltext

定义

您可以使用 @fulltext 指令在 Neo4j 中指定一个全文索引。例如:

input FullTextInput {
  indexName: String!
  queryName: String!
  fields: [String]!
}

"""
Informs @neo4j/graphql that there should be a fulltext index in the database, allows users to search by the index in the generated schema.
"""
directive @fulltext(indexes: [FullTextInput]!) on OBJECT

使用此指令并不会自动确保这些索引的存在。它们必须手动创建。

使用

@fulltext 指令可用于节点。在此示例中,为 Product 节点的 name 字段指定了一个名为 "ProductName" 的全文索引:

type Product @fulltext(indexes: [{ indexName: "ProductName", fields: ["name"] }]) @node {
    name: String!
    color: Color! @relationship(type: "OF_COLOR", direction: OUT)
}

可以通过运行以下 Cypher 语句在数据库中创建此索引:

CREATE FULLTEXT INDEX ProductName FOR (n:Product) ON EACH [n.name]

对于指定的每个索引,库都会生成一个新的顶级查询。例如,对于上述类型定义,将生成以下查询和类型:

type Query {
    productsFulltextProductName(phrase: String!, where: ProductFulltextWhere, sort: [ProductFulltextSort!],
    limit: Int, offset: Int): [ProductFulltextResult!]!
}

"""The result of a fulltext search on an index of Product"""
type ProductFulltextResult {
  score: Float
  product: Product
}

"""The input for filtering a fulltext query on an index of Product"""
input ProductFulltextWhere {
  score: FloatWhere
  product: ProductWhere
}

"""The input for sorting a fulltext query on an index of Product"""
input ProductFulltextSort {
  score: SortDirection
  product: ProductSort
}

"""The input for filtering the score of a fulltext search"""
input FloatWhere {
  min: Float
  max: Float
}

此查询随后可用于执行 Lucene 全文查询以匹配并返回产品。以下是一个示例:

query {
  productsFulltextProductName(phrase: "Hot sauce", where: { score: { min: 1.1 } } sort: [{ product: { name: ASC } }]) {
    score
    product {
      name
    }
  }
}

该查询生成的结果格式如下:

{
  "data": {
    "productsFulltextProductName": [
      {
        "score": 2.1265015602111816,
        "product": {
          "name": "Louisiana Fiery Hot Pepper Sauce"
        }
      },
      {
        "score": 1.2077560424804688,
        "product": {
          "name": "Louisiana Hot Spiced Okra"
        }
      },
      {
        "score": 1.3977186679840088,
        "product": {
          "name": "Northwoods Cranberry Sauce"
        }
      }
    ]
  }
}

此外,还可以通过使用 queryName 参数在 @fulltext 指令中定义自定义查询名称:

type Product @fulltext(indexes: [{ queryName: "CustomProductFulltextQuery", indexName: "ProductName", fields: ["name"] }]) @node {
    name: String!
    color: Color! @relationship(type: "OF_COLOR", direction: OUT)
}

这将生成以下顶级查询:

type Query {
    CustomProductFulltextQuery(phrase: String!, where: ProductFulltextWhere, sort: [ProductFulltextSort!],
    limit: Int, offset: Int): [ProductFulltextResult!]!
}

此查询的使用方式如下:

query {
  CustomProductFulltextQuery(phrase: "Hot sauce", sort: [{ score: ASC }]) {
    score
    product {
      name
    }
  }
}

在 Aura 控制台中创建的数据 API 目前不支持 @vector 指令。

通过 @vector GraphQL 指令,您可以查询数据库以执行向量索引搜索。查询通过传入向量索引或查询短语来执行。

按向量索引查询可以查找具有与该索引相似的向量嵌入的节点。也就是说,查询执行的是最近邻搜索。

相比之下,按短语(一段文本字符串)查询会将该短语转发给 Neo4j GenAI 插件,由插件为其生成向量嵌入。然后将此嵌入与数据库中的节点向量嵌入进行比较。

先决条件
  • 数据库版本必须为 Neo4j 5.15 或更高版本。

  • 节点向量嵌入必须已存在于数据库中。请参阅向量索引以了解有关 Cypher 和 Neo4j 中向量索引的更多信息。

  • 嵌入必须使用相同的方法创建,即使用相同的提供程序和模型。请参阅嵌入与向量索引教程以了解有关 Cypher 和 Neo4j 中向量嵌入的信息。

  • 按向量索引查询不能跨多个标签执行。

  • 按短语查询需要 Neo4j GenAI 插件的凭据。

向量索引搜索是只读的,因为查询所操作的数据是从数据库检索出来的,不会被更改或写回数据库。

定义

"""Informs @neo4j/graphql that there should be a vector index in the database, allows users to search by the index in the generated schema."""
directive @vector(indexes: [VectorIndexInput]!) on OBJECT

VectorIndexInput 定义如下:

input VectorIndexInput {
  """(Required) The name of the vector index."""
  indexName: String!
  """(Required) The name of the embedding property on the node."""
  embeddingProperty: String!
  """(Required) The name of the query."""
  queryName: String
  """(Optional) The name of the provider."""
  provider: String
}

如果设置了可选字段 provider,则该类型用于按短语查询,否则用于按向量查询。provider 字段的允许值由可用的 GenAI 提供程序定义。

用法

按向量索引查询

通过传入向量执行最近邻搜索,以查找具有与该向量相似的向量嵌入的节点。

类型定义:
type Product @node @vector(indexes: [{
  indexName: "productDescriptionIndex",
  embeddingProperty: "descriptionVector",
  queryName: "searchByDescription"
}]) {
  id: ID!
  name: String!
  description: String!
}

这定义了在所有 Product 节点上执行的查询,这些节点针对 descriptionVector 属性具有名为 productDescriptionIndex 的向量索引,这意味着已为每个节点的 description 属性创建了向量嵌入。

查询示例:
query FindSimilarProducts($vector: [Float]!) {
  searchByDescription(vector: $vector) {
    edges {
      cursor
      score
      node {
          id
          name
          description
      }
    }
  }
}

输入 $vector 是一个 FLOAT 值列表,看起来应该类似于这样:

向量示例:
{
  "vector": [
    0.123456,
    ...,
    0.654321,
  ]
}

该查询返回所有 Product 节点,其 descriptionVector 属性上的向量嵌入与查询参数 $vector 相似。

按短语查询

执行一个利用 Neo4j GenAI 插件为搜索短语创建向量嵌入,然后将其与数据库中节点上的现有向量嵌入进行比较的查询。

需要插件的凭据。

确保在调用 Neo4jGraphQL 时设置了您的提供程序凭据,例如:

功能配置:
const neoSchema = new Neo4jGraphQL({
    typeDefs,
    driver,
    features: {
        vector: {
            OpenAI: {
                token: "my-open-ai-token",
                model: "text-embedding-3-small",
            },
        },
    },
});

OpenAI 是用于生成向量嵌入的 GenAI 提供程序之一。请参阅 GenAI 提供程序以获取提供程序及其相应标识符的完整列表。

类型定义:
type Product @node @vector(indexes: [{
  indexName: "productDescriptionIndex",
  embeddingProperty: "descriptionVector",
  provider: OPEN_AI,  # Assuming this is configured in the server
  queryName: "searchByPhrase"
}]) {
  id: ID!
  name: String!
  description: String!
}

这定义了在所有 Product 节点上执行的查询,这些节点针对 descriptionVector 属性具有名为 productDescriptionIndex 的向量索引,这意味着已为每个节点的 description 属性创建了向量嵌入。

查询示例:
query SearchProductsByPhrase($phrase: String!) {
  searchByPhrase(phrase: $phrase) {
    edges {
      cursor
      score
      node {
          id
          name
          description
      }
    }
  }
}

首先,查询将查询短语参数 $phrase 传递给 GenAI 插件,并让其为该短语生成向量嵌入。然后,它返回所有 Product 节点,其 descriptionVector 属性上的向量嵌入与插件生成的向量嵌入相似。