Index value as first item of an array

Assuming that your documents are in the collection called “images”, you can use a binding in an index to return just the first item in the images field:

CreateIndex({
  name: 'first_image_by_id',
  source: {
    collection: Collection("images"),
    fields: {
      first_image: Query(
        Lambda(
          "doc",
          Select(["data", "images", 0], Var("doc"), '') 
        )
      ),
    },
  },
  terms: [
    { field: ["data", "id"] },
  ],
  values: [
    { binding: "first_image" },
    { field: "ref" },
  ]
})

The source in this index defines a “binding” field called first_image. The field value is computed when the Lambda function is executed when indexing a document. The function merely selects the first item in the document’s images field, or returns the empty string if the document doesn’t have an images field, or the value is not an array with at least one element.

The terms definition lets the index search by the id field.

The value definition returns both the result of the binding function as well as the document’s reference.

When I create a sample document:

> Create(
  Collection("images"),
  {
    data: {
      id: 'item1',
      images: ['first', 'second', 'third']
    }
  }
)
{
  ref: Ref(Collection("images"), "307846710482174464"),
  ts: 1629844351200000,
  data: { id: 'item1', images: [ 'first', 'second', 'third' ] }
}

I can retrieve the first image for that document with:

> Paginate(Match(Index("first_image_by_id"), "item1"))
{
  data: [ [ 'first', Ref(Collection("images"), "307846710482174464") ] ]
}
1 Like