Filtering nested tree of document

Hello,

I have following data structure of a single document:

"data": {
 "title": "Title1",
 "blocks": [
  { 
    "block_1": {
     "text": "Text1",
     "refs": Ref(Collection("xyz"), "XYZ") 
  },
  { 
    "block_2": {
     "text": "Text2",
     "refs": Ref(Collection("xyz"), "XYZ2") 
  }
 ]
}

Say that the document is given.
Is there a way in fql to get the “blocks” based on their “refs” value? E.g. only return “block_1” based on “refs” = XYZ.
I.e. the above example should only return “block_1”.

I hope the question is clear. Feel free to ask for clarification. :slight_smile:

Thanks for your help.

Hi, I’m not an expert, but I’m just working in a similar function.

I don’t know if it will work with double nested but here’s my approach
You can create an Index.

CreateIndex({
  name: "YourIndexName",
  serialized: true,
  unique: true,
  source: Collection("block?"),
  // Allow to filter the blocks by refs
  terms: [
    {
      field: ["data", "blocks", "refs"]
    }
  ],
  values: [{ field: ["ref"] }],
});

And in your Lambda you can create a var

  blockData: Match(Index("YourIndex"), Var("refs"))
  blockFilter: Filter(Get(Var("blockData")), Lamda("block", Equals("refs", Var("searchedRef")))

And return the Var(“reactionFilter”)
I hope it can help you!

1 Like

Hi @3rChuss, thank you so much for your answer. I built the index now.

How exactly would you query Fauna? I don’t quite understand how to build the Lambda.

Like how do I combine these two?

blockData: Match(Index("YourIndex"), Var("refs"))
blockFilter: Filter(Get(Var("blockData")), Lambda("block", Equals("refs", Var("searchedRef"))))

Hi @gllanfranchi Are you still working on this?

The key thing that @3rChuss showed is that when you index on a field that is in an array, every element of the array is added as an entry into the index.

Also, in general, the Let function can go a long way to help organize a complex or multi-step query. That would be how you could create a list of different “steps” of computed values.

Let(
  {
    blockData: Match(Index("YourIndex"), Var("refs")),
    blockFilter: Filter(Get(Var("blockData")), Lamda("block", Equals("refs", Var("searchedRef")))
  },
  Var("blockFilter")
)

Depending on the actual data you have, the extra filter step might not be necessary. The Document you shared: it’s not actually a valid javascript/json object. If you are still looking for help getting this working, can you confirm what an example document looks like?

Cheers.

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.