How to index on key metadata

I can’t seem the find a way to reference the Keys collection directly in order to create an index. I’m trying to index on some custom metadata added to the data of the key when it is created. Is this not possible currently?

You haven’t shown us what you have tried, so I can’t help you solve the specific problem you are encountering.

Keys, and everything else in Fauna, are represented by documents. Metadata for Fauna “schema” documents should be stored in the data field, as you would for regular documents.

Here’s an example:

> CreateKey({ role: "admin", data: { color: "red" }})
{
  ref: Ref(Keys(), "341433524248642048"),
  ts: 1661875232860000,
  role: 'admin',
  data: { color: 'red' },
  secret: 'fnAEvQP7N0ACAMUSxyqV2ZfS3Tj39jJiI6DUlV0W',
  hashed_secret: '$2a$05$AhN2FdM0tiiGZgDTwJfX0Ov59GptcwLWs.j3wavpym/Uw5e7ID3Ya'
}
> CreateKey({ role: "admin", data: { color: "green" }})
{
  ref: Ref(Keys(), "341433532038513152"),
  ts: 1661875240270000,
  role: 'admin',
  data: { color: 'green' },
  secret: 'fnAEvQP9B5ACABVN5PuQQjsZm5O2qwDGjHpTfByq',
  hashed_secret: '$2a$05$td7.9MQjDTiwD7oWB/qRkuEEkWVHzG4C3LPHIWFCooN3gxICJzJKC'
}
> CreateKey({ role: "admin", data: { color: "blue" }})
{
  ref: Ref(Keys(), "341433538584773120"),
  ts: 1661875246520000,
  role: 'admin',
  data: { color: 'blue' },
  secret: 'fnAEvQP-jcACAPgZ8RXM81OzcFqbzKOGCwxNjvEq',
  hashed_secret: '$2a$05$QDdj5MyeDU099i9lSk4B1.sXorO6Tx2tEK8YqGcfgNeE2252Q.t7.'
}

With the keys created, we now need an index so that we can search them:

> CreateIndex({
  name: "keys_by_color",
  source: Keys(),
  terms: [
    { field: ["data", "color"] }
  ]
})
{
  ref: Index("keys_by_color"),
  ts: 1661875253010000,
  active: true,
  serialized: true,
  name: 'keys_by_color',
  source: Keys(),
  terms: [ { field: [ 'data', 'color' ] } ],
  partitions: 1
}

Finally, we can use the index to search for keys:

> Paginate(Match(Index("keys_by_color"), "red"))
{ data: [ Ref(Keys(), "341433524248642048") ] }
> Paginate(Match(Index("keys_by_color"), "green"))
{ data: [ Ref(Keys(), "341433532038513152") ] }

I see. My issue was that I was trying to use Collection("keys") instead of Keys() when creating the index or refs. It also didn’t show in the dashboard as an option of a collection to index.

1 Like

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