动物群搜索参考

Joe*_*Joe 1 faunadb

我收藏了两份文件products...

{
  "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")
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我的收藏里还有两份文件suppliers......

{
  "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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

esk*_*yrd 5

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

CreateIndex({
  name: "products_by_supplier",
  source: Collection("products"),
  terms: [{ field: ["data", "supplier"]}]
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

> 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")
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

有关更多详细信息,请参阅搜索教程:https://docs.fauna.com/fauna/current/tutorials/indexes/search