Is it possible to use variables inside a regex query. I copied the query from your documentation and tried to replace “Steven Sp” with a string variable. I am using this query with the JavaScript library. I can get it to work with the ratel interface.
This:
const query = `query all($a: string) {
users(func: regex(username, /^$a.*$/))
{
uid
name
emailAddress
username
timezone
bio
}
};`
Didn’t seem to work for me, I get an error.
Also this (just using javascript to do the string interpolation):
function eqQuery(predicate: string, usernameString: string) {
return `query {
users(func: regex(${predicate}, "/^${usernameString}.*$/"))
{
uid
name
emailAddress
username
timezone
bio
}
}`;
}
Returns a: “Function name: regex is not valid” error.
Not sure what I am doing wrong.
A follow on question from “is it possible to use variables in regex”, is should I?
The app I am building will consist of user profiles that I would like to have searchable, and for terms like “name” and “username” ideally the search would work with a partial match, so I am thinking regex. Is this reasonable? Or should I be trying to put an indexed search layer in front of the underlying DGraph layer?
Below is the full sample, the commented out option is the one that works. In both cases I am searching the same username “vespertilian” which is the only demo user I have loaded.
I did notice in the docs that there should be a minimum requirement setup for regex searching.
// function query(usernamePartialString: string): string {
// return `query {
// users(func: regexp(username, /${usernamePartialString}/))
// {
// uid
// name
// emailAddress
// username
// timezone
// bio
// }
// }`;
// }
const query = `query all($a: string) {
users(func: regexp(username, /$a/))
{
uid
name
emailAddress
username
timezone
bio
}
};`
export async function usersUsernameResolver(
_: any,
{username} : any,
context: any,
info: any,
dgraphClient: DgraphClient = newDgraphClient()
) {
const vars = { $a: username};
let result = null;
try {
// const res = await dgraphClient.newTxn().query(query(username));
const res = await dgraphClient.newTxn().queryWithVars(query, vars);
const jsonStr = new Buffer(res.getJson_asU8()).toString();
result = JSON.parse(jsonStr).users;
console.log(result)
} catch(e) {
console.log(e)
}
return result;
}