3

Anyone knows how I can create an index where the term is a ref and is searchable through a nested object in an array?

In the collection "conversations" I have saved the following example data:

{
  "created": Time("2019-09-29T22:11:01.493034Z"),
  "updated": Time("2019-09-29T22:11:01.493034Z"),
  "participants": [
    {
      "ref": Ref(Collection("users"), "244754936642929163"),
      "firstname": "John",
      "creator": true
    },
    {
      "ref": Ref(Collection("users"), "244517629884105216"),
      "firstname": "Max"
    }
  ]
}

It would be great to have an index, where I can search if a ref is included in the participants array.

1 Answer 1

2

This can be solved using an index with the array being selected as a term. When an field targeted as a term is an array a separate index entry is generated per item in the array. So assuming extant collections parent and child then

db> CreateIndex({name: "cs", source: Collection("parent"), terms: [{field: ["data", "child"]}]})
{
  ref: Index("cs"),
  ts: 1569831659780000,
  active: true,
  serialized: true,
  name: 'p',
  source: Collection("parent"),
  terms: [ { field: [ 'data', 'child' ] } ],
  partitions: 1
}

will do the business. Example usage:

db> Create(Collection("child"), {})
{
  ref: Ref(Collection("child"), "244918886014648845"),
  ts: 1569831701200000
}
db> Create(Collection("child"), {})
{
  ref: Ref(Collection("child"), "244918887478460941"),
  ts: 1569831702590000
}
db> Create(Collection("parent"), {data:{child:[Ref(Collection("child"), "244918886014648845"), Ref(Collection("child"), "244918887478460941")]}})
{
  ref: Ref(Collection("parent"), "244918956982272520"),
  ts: 1569831768880000,
  data: {
    child: [
      Ref(Collection("child"), "244918886014648845"),
      Ref(Collection("child"), "244918887478460941")
    ]
  }
}
db> Paginate(Match(Index("cs"), Ref(Collection("child"), "244918886014648845")))
{
  data: [
    Ref(Collection("parent"), "244918956982272520")
  ]
}

Either child ref would have matched.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.