I have two documents in the 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")
}
}
then I have also two documents in my 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"
}
}
How do I search the products
collection by the supplier
reference field? Any help is appreciated! Thanks!
All searching in Fauna is done using indexes. You need to create an index for your "products" collection, specifying "supplier" as the search field (aka the terms
field in the index):
CreateIndex({
name: "products_by_supplier",
source: Collection("products"),
terms: [{ field: ["data", "supplier"]}]
})
Then you can find all products where the supplier
field matches the reference for a specific supplier:
> Paginate(
Match(
Index("products_by_supplier"),
Ref(Collection("suppliers"), "300137504766427654")
)
)
{ data: [ Ref(Collection("products"), "300137558676865540") ] }
If you want to verify that the results are correct, you can iterate over the results to fetch the associated product documents:
> 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")
}
}
]
}
Note that the ts
field in my result differs from yours, because I just created those documents.
See the search tutorial for more details: https://docs.fauna.com/fauna/current/tutorials/indexes/search