1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-09 00:22:08 +03:00

[DOC-2373] adds js samples to match search-quickstart md (#2538)

* [DOC-2373] adds js samples to match search-quickstart md

* Fixes step matching for the Search quickstart

* Update search-quickstart.js

---------

Co-authored-by: Justin Castilla <pxlperfection@gmail.com>
Co-authored-by: Elena Kolevska <elena@kolevska.com>
Co-authored-by: Leibale Eidelman <me@leibale.com>
This commit is contained in:
Justin Castilla
2023-06-22 03:44:35 -07:00
committed by GitHub
parent caaca48ca1
commit 0588b383cb

View File

@@ -1,9 +1,9 @@
// EXAMPLE: search_quickstart // EXAMPLE: search_quickstart
// REMOVE_START // REMOVE_START
import assert from "assert"; import assert from 'assert';
// REMOVE_END // REMOVE_END
// HIDE_START // HIDE_START
import {AggregateGroupByReducers, AggregateSteps, createClient, SchemaFieldTypes} from 'redis'; import { AggregateGroupByReducers, AggregateSteps, createClient, SchemaFieldTypes } from 'redis';
// HIDE_END // HIDE_END
// STEP_START connect // STEP_START connect
const client = createClient(); const client = createClient();
@@ -13,87 +13,90 @@ await client.connect();
// STEP_END // STEP_END
// STEP_START data_sample // STEP_START data_sample
let bicycle1 = { const bicycle1 = {
"brand": "Diaz Ltd", brand: 'Velorim',
"model": "Dealer Sl", model: 'Jigger',
"price": 7315.58, price: 270,
"description": "The Diaz Ltd Dealer Sl is a reliable choice" + description:
" for urban cycling. The Diaz Ltd Dealer Sl " + 'Small and powerful, the Jigger is the best ' +
"is a comfortable choice for urban cycling.", 'ride for the smallest of tikes! This is the tiniest kids\u2019 ' +
"condition": "used", 'pedal bike on the market available without a coaster brake, the ' +
} 'Jigger is the vehicle of choice for the rare tenacious little' +
'rider raring to go.',
condition: 'new'
};
// STEP_END // STEP_END
let bicycles = [ const bicycles = [
bicycle1, bicycle1,
{ {
"brand": "Bridges Group", brand: 'Bicyk',
"model": "Project Pro", model: 'Hillcraft',
"price": 3610.82, price: 1200,
"description": "This mountain bike is perfect for mountain biking. The Bridges Group Project Pro is a responsive choice for mountain biking.", description: 'Kids want to ride with as little weight as possible. Especially on an incline! They may be at the age when a 27.5\" wheel bike is just too clumsy coming off a 24\" bike. The Hillcraft 26 is just the solution they need!',
"condition": "used", condition: 'used'
}, },
{ {
"brand": "Vega, Cole and Miller", brand: 'Nord',
"model": "Group Advanced", model: 'Chook air 5',
"price": 8961.42, price: 815,
"description": "The Vega, Cole and Miller Group Advanced provides a excellent ride. With its fast carbon frame and 24 gears, this bicycle is perfect for any terrain.", description: 'The Chook Air 5 gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. The lower top tube makes it easy to mount and dismount in any situation, giving your kids greater safety on the trails.',
"condition": "used", condition: 'used'
}, },
{ {
"brand": "Powell-Montgomery", brand: 'Eva',
"model": "Angle Race", model: 'Eva 291',
"price": 4050.27, price: 3400,
"description": "The Powell-Montgomery Angle Race is a smooth choice for road cycling. The Powell-Montgomery Angle Race provides a durable ride.", description: 'The sister company to Nord, Eva launched in 2005 as the first and only women-dedicated bicycle brand. Designed by women for women, allEva bikes are optimized for the feminine physique using analytics from a body metrics database. If you like 29ers, try the Eva 291. It\u2019s a brand new bike for 2022.. This full-suspension, cross-country ride has been designed for velocity. The 291 has 100mm of front and rear travel, a superlight aluminum frame and fast-rolling 29-inch wheels. Yippee!',
"condition": "used", condition: 'used'
}, },
{ {
"brand": "Gill-Lewis", brand: 'Noka Bikes',
"model": "Action Evo", model: 'Kahuna',
"price": 283.68, price: 3200,
"description": "The Gill-Lewis Action Evo provides a smooth ride. The Gill-Lewis Action Evo provides a excellent ride.", description: 'Whether you want to try your hand at XC racing or are looking for a lively trail bike that\'s just as inspiring on the climbs as it is over rougher ground, the Wilder is one heck of a bike built specifically for short women. Both the frames and components have been tweaked to include a women\u2019s saddle, different bars and unique colourway.',
"condition": "used", condition: 'used'
}, },
{ {
"brand": "Rodriguez-Guerrero", brand: 'Breakout',
"model": "Drama Comp", model: 'XBN 2.1 Alloy',
"price": 4462.55, price: 810,
"description": "This kids bike is perfect for young riders. With its excellent aluminum frame and 12 gears, this bicycle is perfect for any terrain.", description: 'The XBN 2.1 Alloy is our entry-level road bike \u2013 but that\u2019s not to say that it\u2019s a basic machine. With an internal weld aluminium frame, a full carbon fork, and the slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance.',
"condition": "new", condition: 'new'
}, },
{ {
"brand": "Moore PLC", brand: 'ScramBikes',
"model": "Award Race", model: 'WattBike',
"price": 3790.76, price: 2300,
"description": "This olive folding bike features a carbon frame and 27.5 inch wheels. This folding bike is perfect for compact storage and transportation.", description: 'The WattBike is the best e-bike for people who still feel young at heart. It has a Bafang 1000W mid-drive system and a 48V 17.5AH Samsung Lithium-Ion battery, allowing you to ride for more than 60 miles on one charge. It\u2019s great for tackling hilly terrain or if you just fancy a more leisurely ride. With three working modes, you can choose between E-bike, assisted bicycle, and normal bike modes.',
"condition": "new", condition: 'new'
}, },
{ {
"brand": "Hall, Haley and Hayes", brand: 'Peaknetic',
"model": "Weekend Plus", model: 'Secto',
"price": 2008.4, price: 430,
"description": "The Hall, Haley and Hayes Weekend Plus provides a comfortable ride. This blue kids bike features a steel frame and 29.0 inch wheels.", description: 'If you struggle with stiff fingers or a kinked neck or back after a few minutes on the road, this lightweight, aluminum bike alleviates those issues and allows you to enjoy the ride. From the ergonomic grips to the lumbar-supporting seat position, the Roll Low-Entry offers incredible comfort. The rear-inclined seat tube facilitates stability by allowing you to put a foot on the ground to balance at a stop, and the low step-over frame makes it accessible for all ability and mobility levels. The saddle is very soft, with a wide back to support your hip joints and a cutout in the center to redistribute that pressure. Rim brakes deliver satisfactory braking control, and the wide tires provide a smooth, stable ride on paved roads and gravel. Rack and fender mounts facilitate setting up the Roll Low-Entry as your preferred commuter, and the BMX-like handlebar offers space for mounting a flashlight, bell, or phone holder.',
"condition": "new", condition: 'new'
}, },
{ {
"brand": "Peck-Carson", brand: 'nHill',
"model": "Sun Hybrid", model: 'Summit',
"price": 9874.95, price: 1200,
"description": "With its comfortable aluminum frame and 25 gears, this bicycle is perfect for any terrain. The Peck-Carson Sun Hybrid provides a comfortable ride.", description: 'This budget mountain bike from nHill performs well both on bike paths and on the trail. The fork with 100mm of travel absorbs rough terrain. Fat Kenda Booster tires give you grip in corners and on wet trails. The Shimano Tourney drivetrain offered enough gears for finding a comfortable pace to ride uphill, and the Tektro hydraulic disc brakes break smoothly. Whether you want an affordable bike that you can take to work, but also take trail in mountains on the weekends or you\u2019re just after a stable, comfortable ride for the bike path, the Summit gives a good value for money.',
"condition": "new", condition: 'new'
}, },
{ {
"brand": "Fowler Ltd", model: 'ThrillCycle',
"model": "Weekend Trail", brand: 'BikeShind',
"price": 3833.71, price: 815,
"description": "The Fowler Ltd Letter Trail is a comfortable choice for transporting cargo. This cargo bike is perfect for transporting cargo.", description: 'An artsy, retro-inspired bicycle that\u2019s as functional as it is pretty: The ThrillCycle steel frame offers a smooth ride. A 9-speed drivetrain has enough gears for coasting in the city, but we wouldn\u2019t suggest taking it to the mountains. Fenders protect you from mud, and a rear basket lets you transport groceries, flowers and books. The ThrillCycle comes with a limited lifetime warranty, so this little guy will last you long past graduation.',
"condition": "refurbished", condition: 'refurbished'
}, }
] ];
// STEP_START define_index // STEP_START create_index
let schema = { const schema = {
'$.brand': { '$.brand': {
type: SchemaFieldTypes.TEXT, type: SchemaFieldTypes.TEXT,
sortable: true, SORTABLE: true,
AS: 'brand' AS: 'brand'
}, },
'$.model': { '$.model': {
@@ -111,11 +114,9 @@ let schema = {
'$.condition': { '$.condition': {
type: SchemaFieldTypes.TAG, type: SchemaFieldTypes.TAG,
AS: 'condition' AS: 'condition'
}, }
} };
// STEP_END
// STEP_START create_index
try { try {
await client.ft.create('idx:bicycle', schema, { await client.ft.create('idx:bicycle', schema, {
ON: 'JSON', ON: 'JSON',
@@ -133,107 +134,98 @@ try {
// STEP_END // STEP_END
// STEP_START add_documents // STEP_START add_documents
for (let i = 0; i < bicycles.length; i++) { await Promise.all(
await client.json.set(`bicycle:${i}`, '$', bicycles[i]); bicycles.map((bicycle, i) => client.json.set(`bicycle:${i}`, '$', bicycle))
} );
// STEP_END // STEP_END
// STEP_START query_single_term_and_num_range // STEP_START wildcard_query
let result = await client.ft.search( let result = await client.ft.search('idx:bicycle', '*', {
'idx:bicycle', LIMIT: {
'folding @price:[1000 4000]' from: 0,
); size: 10
}
});
console.log(JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2));
/* /*
{ {
"total": 1, "total": 10,
"documents": [ "documents": ...
{
"id": "bicycle:6",
"value": {
"brand": "Moore PLC",
"model": "Award Race",
"price": 3790.76,
"description": "This olive folding bike features a carbon frame and 27.5 inch wheels. This folding bike is perfect for compact storage and transportation.",
"condition": "new"
}
}
]
} }
*/ */
// STEP_END // STEP_END
// REMOVE_START // REMOVE_START
assert.equal(result.documents[0].id, "bicycle:6"); assert.equal(result.documents[0].id, 'bicycle:1');
// REMOVE_END // REMOVE_END
// STEP_START query_single_term_limit_fields // STEP_START query_single_term
result = await client.ft.search( result = await client.ft.search(
'idx:bicycle', 'idx:bicycle',
'cargo', '@model:Jigger',
{ {
RETURN: ['$.price'] LIMIT: {
from: 0,
size: 10
} }
); });
console.log(JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2));
/* /*
{ {
"total": 1, "total": 1,
"documents": [ "documents": [{
{ "id": "bicycle:0",
"id": "bicycle:9",
"value": { "value": {
"$.price": "3833.71" "brand": "Velorim",
"model": "Jigger",
"price": 270,
"description": "Small and powerful, the Jigger is the best ride for the smallest of tikes! This is the tiniest kids pedal bike on the market available without a coaster brake, the Jigger is the vehicle of choice for the rare tenacious little rider raring to go.",
"condition": "new"
} }
} }]
]
} }
*/ */
// STEP_END // STEP_END
// REMOVE_START // REMOVE_START
assert.equal(result.documents[0].id, "bicycle:9"); assert.equal(result.documents[0].id, 'bicycle:0');
// REMOVE_END // REMOVE_END
// STEP_START simple_aggregation // STEP_START query_exact_matching
result = await client.ft.aggregate('idx:bicycle', '*', { result = await client.ft.search(
STEPS: [ 'idx:bicycle',
'@brand:"Noka Bikes"',
{ {
type: AggregateSteps.GROUPBY, LIMIT: {
properties: ['@condition'], from: 0,
REDUCE: [ size: 10
{
type: AggregateGroupByReducers.COUNT,
AS: 'count'
} }
]
} }
] );
})
console.log(JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2));
/* /*
{ {
"total": 3, "total": 1,
"results": [ "documents": [{
{ "id": "bicycle:4",
"condition": "refurbished", "value": {
"count": "1" "brand": "Noka Bikes",
}, "model": "Kahuna",
{ "price": 3200,
"condition": "used", "description": "Whether you want to try your hand at XC racing or are looking for a lively trail bike that's just as inspiring on the climbs as it is over rougher ground, the Wilder is one heck of a bike built specifically for short women. Both the frames and components have been tweaked to include a womens saddle, different bars and unique colourway.",
"count": "5" "condition": "used"
},
{
"condition": "new",
"count": "4"
} }
] }]
} }
*/ */
// STEP_END // STEP_END
// REMOVE_START // REMOVE_START
assert.equal(result.total, 3); assert.equal(result.documents[0].id, 'bicycle:4');
// REMOVE_END // REMOVE END
await client.quit(); await client.quit();