From d9c815f50e6814197f4a1f955527addb44871e5c Mon Sep 17 00:00:00 2001 From: Itamar Haber Date: Sun, 22 Jan 2023 21:18:34 +0200 Subject: [PATCH] Initial example --- examples/json_search/example.json | 11 +++++ examples/json_search/index.js | 67 +++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 examples/json_search/example.json create mode 100644 examples/json_search/index.js diff --git a/examples/json_search/example.json b/examples/json_search/example.json new file mode 100644 index 0000000000..8404f92efb --- /dev/null +++ b/examples/json_search/example.json @@ -0,0 +1,11 @@ +{ + "id": "json_search", + "file": "index.js", + "highlight": [ + "10", + "44-56", + "63" + ], + "hide": [], + "collapse": [] +} \ No newline at end of file diff --git a/examples/json_search/index.js b/examples/json_search/index.js new file mode 100644 index 0000000000..a9e493ebc1 --- /dev/null +++ b/examples/json_search/index.js @@ -0,0 +1,67 @@ +import { createClient, SchemaFieldTypes} from 'redis'; + +const client = createClient(); + +await client.connect(); + +// Create an index. +// https://redis.io/commands/ft.create/ +try { + await client.ft.create('idx:users', { + '$.name': { + type: SchemaFieldTypes.TEXT, + SORTABLE: 'UNF' + }, + '$.age': { + type: SchemaFieldTypes.NUMERIC, + AS: 'age' + }, + '$.coins': { + type: SchemaFieldTypes.NUMERIC, + AS: 'coins' + }, + '$.email': { + type: SchemaFieldTypes.TAG, + AS: 'email' + } + }, { + 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. +// https://redis.io/commands/json.set/ +await Promise.all([ + client.json.set('noderedis:users:1', '$', { + name: 'Alice', + age: 32, + coins: 100, + email: 'alice@nonexist.com' + }), + client.json.set('noderedis:users:2', '$', { + name: 'Bob', + age: 23, + coins: 15, + email: 'bob@somewhere.gov' + }) +]); + +// Search all users under 30 +console.log('Users under 30 years old:'); +console.log( + // https://redis.io/commands/ft.search/ + JSON.stringify( + await client.ft.search('idx:users', '@age:[0 30]'), + null, + 2 + ) +);