diff --git a/examples/search-json.js b/examples/search-json.js index 623e0bfd56..c44bf7eef6 100644 --- a/examples/search-json.js +++ b/examples/search-json.js @@ -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();