按参考搜索动物群

Fauna Search By Ref

我在 products collection...

中有两个文档
{
  "ref": Ref(Collection("products"), "300137558676865540"),
  "ts": 1622492331145000,
  "data": {
    "product_id": 1004,
    "display_name": "Product By ABC",
    "description": "Product Description ABC",
    "status": "in_stock",
    "price_current": 100,
    "supplier": Ref(Collection("suppliers"), "300137504766427654")
  }
},
{
  "ref": Ref(Collection("products"), "300137592998855170"),
  "ts": 1622492386360000,
  "data": {
    "product_id": 1005,
    "display_name": "Product By XYZ",
    "description": "Product Description XYZ",
    "status": "in_stock",
    "price_current": 150,
    "supplier": Ref(Collection("suppliers"), "300137513423471107")
  }
}

然后我的 suppliers collection...

中也有两个文件
{
  "ref": Ref(Collection("suppliers"), "300137504766427654"),
  "ts": 1622492279715000,
  "data": {
    "supplier_id": 205,
    "display_name": "Test Supplier ABC"
  }
},
{
  "ref": Ref(Collection("suppliers"), "300137513423471107"),
  "ts": 1622492287963000,
  "data": {
    "supplier_id": 206,
    "display_name": "Test Supplier XYZ"
  }
}

如何通过 supplier 参考字段搜索 products collection?任何帮助表示赞赏!谢谢!

Fauna 中的所有搜索都是使用索引完成的。您需要为“产品”集合创建一个索引,将“供应商”指定为搜索字段(即索引中的 terms 字段):

CreateIndex({
  name: "products_by_supplier",
  source: Collection("products"),
  terms: [{ field: ["data", "supplier"]}]
})

然后您可以找到 supplier 字段与特定供应商的参考相匹配的所有产品:

> Paginate(
  Match(
    Index("products_by_supplier"),
    Ref(Collection("suppliers"), "300137504766427654")
  )
)
{ data: [ Ref(Collection("products"), "300137558676865540") ] }

如果要验证结果是否正确,可以迭代结果以获取关联的产品文档:

> Map(
  Paginate(
    Match(
      Index("products_by_supplier"),
      Ref(Collection("suppliers"), "300137504766427654")
    )
  ),
  Lambda("X", Get(Var("X")))
)
{
  data: [
    {
      ref: Ref(Collection("products"), "300137558676865540"),
      ts: 1622501576960000,
      data: {
        product_id: 1004,
        display_name: 'Product By ABC',
        description: 'Product Description ABC',
        status: 'in_stock',
        price_current: 100,
        supplier: Ref(Collection("suppliers"), "300137504766427654")
      }
    }
  ]
}

请注意,我的结果中的 ts 字段与您的不同,因为我刚刚创建了那些文档。

详见搜索教程:https://docs.fauna.com/fauna/current/tutorials/indexes/search