-
I am having a hard time understanding how queries with path variables work. const { AceBase } = require("acebase")
const db = new AceBase("db")
db.schema.set("messages/$username/*", { "text": "string" })
db.ready(async () => {
await db.ref("messages/user1").push({ text: "First message" })
await db.ref("messages/user2").push({ text: "Second message" })
await db.ref("messages/user1").push({ text: "Third message" })
let usercount = await db.query("messages").count()
console.log(`User count: ${usercount}`)
let msgcount = await db.query("messages/$username").count()
console.log(`Message count: ${msgcount}`)
let user1msgcount = await db.query("messages/user1").count()
console.log(`Messages of user1: ${user1msgcount}`)
}) when I execute it with
which I don't understand: I thought that querying "messages/$username" should return all three messages under all usernames. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Executing a query on a path with a wildcard * or $variable requires an index on the data. On top of that, indexes are only used if a filter is applied to the query. So to workaround this, you'll have to do this: // Create index on scattered data:
await db.indexes.create('messages/$username', '$key'); // $key indexes the keys you refer to as $username
// Query it with a filter that matches all records
let msgcount = await db.query('messages/$username').filter('$key', '==', null).count(); I'll change the code to throw an error if there is no index, and maybe automatically apply an all-matching filter on the first available index otherwise, but the above should work! |
Beta Was this translation helpful? Give feedback.
-
I took a closer look into this and saw I made a mistake in my example code. |
Beta Was this translation helpful? Give feedback.
-
I published acebase v1.18.0, try updating and using this code: // Create index on scattered data:
await db.indexes.create('messages/$username', '{key}'); // {key} indexes the keys of every child of messages/$username
// Query it
let msgcount = await db.query('messages/$username').count(); As you can see, there's no need to add a filter to the count query anymore, it's done automatically behind the scenes. Let me know if it works! |
Beta Was this translation helpful? Give feedback.
I published acebase v1.18.0, try updating and using this code:
As you can see, there's no need to add a filter to the count query anymore, it's done automatically behind the scenes. Let me know if it works!