1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-06 02:15:48 +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'; import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis';
async function searchPlusJson() { async function searchJSON() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
// Create an index // Create an index.
await client.ft.create('users', { try {
'$.name': { await client.ft.create('idx:users', {
type: SchemaFieldTypes.TEXT, '$.name': {
SORTABLE: 'UNF' type: SchemaFieldTypes.TEXT,
}, SORTABLE: 'UNF'
'$.age': SchemaFieldTypes.NUMERIC, },
'$.coins': SchemaFieldTypes.NUMERIC '$.age': SchemaFieldTypes.NUMERIC,
}, { '$.coins': SchemaFieldTypes.NUMERIC
ON: 'JSON' }, {
}); 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([ await Promise.all([
client.json.set('users:1', '$', { client.json.set('noderedis:users:1', '$', {
name: 'Alice', name: 'Alice',
age: 32, age: 32,
coins: 100 coins: 100
}), }),
client.json.set('users:2', '$', { client.json.set('noderedis:users:2', '$', {
name: 'Bob', name: 'Bob',
age: 23, age: 23,
coins: 15 coins: 15
@@ -34,18 +45,20 @@ async function searchPlusJson() {
]); ]);
// Search all users under 30 // Search all users under 30
// https://oss.redis.com/redisearch/Commands/#ftsearch
// TODO: why "$.age:[-inf, 30]" does not work? // TODO: why "$.age:[-inf, 30]" does not work?
console.log( console.log(
await client.ft.search('users', '*') await client.ft.search('idx:users', '*')
); );
// { // {
// total: 1, // total: 1,
// documents: [...] // documents: [...]
// } // }
// Some aggregrations... // Some aggregrations, what's the average age and total number of coins...
// https://oss.redis.com/redisearch/Commands/#ftaggregate
console.log( console.log(
await client.ft.aggregate('users', '*', { await client.ft.aggregate('idx:users', '*', {
STEPS: [{ STEPS: [{
type: AggregateSteps.GROUPBY, type: AggregateSteps.GROUPBY,
REDUCE: [{ REDUCE: [{
@@ -71,4 +84,4 @@ async function searchPlusJson() {
await client.quit(); await client.quit();
} }
searchPlusJson(); searchJSON();