1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-01 16:46:54 +03:00

Some refactoring.

This commit is contained in:
Simon Prickett
2021-11-24 20:03:23 +00:00
parent 99b261b79c
commit 7d58f05479

View File

@ -2,31 +2,42 @@
import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis';
async function searchPlusJson() {
async function searchJSON() {
const client = createClient();
await client.connect();
// Create an index
await client.ft.create('users', {
'$.name': {
type: SchemaFieldTypes.TEXT,
SORTABLE: 'UNF'
},
'$.age': SchemaFieldTypes.NUMERIC,
'$.coins': SchemaFieldTypes.NUMERIC
}, {
ON: 'JSON'
});
// Create an index.
try {
await client.ft.create('idx:users', {
'$.name': {
type: SchemaFieldTypes.TEXT,
SORTABLE: 'UNF'
},
'$.age': SchemaFieldTypes.NUMERIC,
'$.coins': SchemaFieldTypes.NUMERIC
}, {
ON: 'JSON',
PREFIX: 'noderedis:users'
});
} catch (e) {
if (e.message === 'Index already exists') {
console.log('Index exists already, skipped creation.');
} else {
// Something went wrong, perhaps RediSearch isn't installed...
console.error(e);
process.exit(1);
}
}
// Add some users
// Add some users.
await Promise.all([
client.json.set('users:1', '$', {
client.json.set('noderedis:users:1', '$', {
name: 'Alice',
age: 32,
coins: 100
}),
client.json.set('users:2', '$', {
client.json.set('noderedis:users:2', '$', {
name: 'Bob',
age: 23,
coins: 15
@ -34,18 +45,20 @@ async function searchPlusJson() {
]);
// Search all users under 30
// https://oss.redis.com/redisearch/Commands/#ftsearch
// TODO: why "$.age:[-inf, 30]" does not work?
console.log(
await client.ft.search('users', '*')
await client.ft.search('idx:users', '*')
);
// {
// total: 1,
// documents: [...]
// }
// Some aggregrations...
// Some aggregrations, what's the average age and total number of coins...
// https://oss.redis.com/redisearch/Commands/#ftaggregate
console.log(
await client.ft.aggregate('users', '*', {
await client.ft.aggregate('idx:users', '*', {
STEPS: [{
type: AggregateSteps.GROUPBY,
REDUCE: [{
@ -71,4 +84,4 @@ async function searchPlusJson() {
await client.quit();
}
searchPlusJson();
searchJSON();