Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

redirect to learn (client-side) #638

Merged
merged 4 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 50 additions & 42 deletions docs/howtos/solutions/geo/getting-started-geo/index-geo-search.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ This section outlines the implementation of the `getStoreProductsByGeoFilter` AP

4. **Result Processing**: The function filters out duplicate products across different stores, ensuring unique product listings in the final output. It then formats the store locations into a more readable structure and compiles the final list of products to return.

```js
```ts
import * as StoreInventoryRepo from '../../../common/models/store-inventory-repo';

interface IInventoryBodyFilter {
Expand All @@ -276,7 +276,7 @@ interface IInventoryBodyFilter {
userLocation?: {
latitude?: number;
longitude?: number;
},
};
}

const searchStoreInventoryByGeoFilter = async (
Expand All @@ -286,13 +286,14 @@ const searchStoreInventoryByGeoFilter = async (
const redisClient = getNodeRedisClient();
const repository = StoreInventoryRepo.getRepository();
let storeProducts: IStoreInventory[] = [];
const trimmedStoreProducts: IStoreInventory[] = [] // similar item of other stores are removed
const trimmedStoreProducts: IStoreInventory[] = []; // similar item of other stores are removed
const uniqueProductIds = {};

if (repository
&& _inventoryFilter?.userLocation?.latitude
&& _inventoryFilter?.userLocation?.longitude) {

if (
repository &&
_inventoryFilter?.userLocation?.latitude &&
_inventoryFilter?.userLocation?.longitude
) {
const lat = _inventoryFilter.userLocation.latitude;
const long = _inventoryFilter.userLocation.longitude;
const radiusInMiles = _inventoryFilter.searchRadiusInMiles || 500;
Expand All @@ -306,17 +307,13 @@ const searchStoreInventoryByGeoFilter = async (
.gt(0)
.and('storeLocation')
.inRadius((circle) => {
return circle
.latitude(lat)
.longitude(long)
.radius(radiusInMiles)
.miles
return circle.latitude(lat).longitude(long).radius(radiusInMiles).miles;
});

if (_inventoryFilter.productDisplayName) {
queryBuilder = queryBuilder
.and('productDisplayName')
.matches(_inventoryFilter.productDisplayName)
.matches(_inventoryFilter.productDisplayName);
}

console.log(queryBuilder.query);
Expand All @@ -325,26 +322,38 @@ const searchStoreInventoryByGeoFilter = async (
FT.SEARCH "storeInventory:storeInventoryId:index" "( ( ( (@statusCode:[1 1]) (@stockQty:[(0 +inf]) ) (@storeLocation:[-73.968285 40.785091 50 mi]) ) (@productDisplayName:'puma') )"
*/

// (3) --- Executing the Query
// (3) --- Executing the Query
const indexName = `storeInventory:storeInventoryId:index`;
const aggregator = await redisClient.ft.aggregate(
indexName,
queryBuilder.query,
{
LOAD: ["@storeId", "@storeName", "@storeLocation", "@productId", "@productDisplayName", "@stockQty"],
STEPS: [{
type: AggregateSteps.APPLY,
expression: `geodistance(@storeLocation, ${long}, ${lat})/1609`,
AS: 'distInMiles'
}, {
type: AggregateSteps.SORTBY,
BY: ["@distInMiles", "@productId"]
}, {
type: AggregateSteps.LIMIT,
from: 0,
size: 1000,
}]
});
LOAD: [
'@storeId',
'@storeName',
'@storeLocation',
'@productId',
'@productDisplayName',
'@stockQty',
],
STEPS: [
{
type: AggregateSteps.APPLY,
expression: `geodistance(@storeLocation, ${long}, ${lat})/1609`,
AS: 'distInMiles',
},
{
type: AggregateSteps.SORTBY,
BY: ['@distInMiles', '@productId'],
},
{
type: AggregateSteps.LIMIT,
from: 0,
size: 1000,
},
],
},
);

/* Sample command to run on CLI
FT.AGGREGATE "storeInventory:storeInventoryId:index"
Expand All @@ -360,37 +369,36 @@ const searchStoreInventoryByGeoFilter = async (

if (!storeProducts.length) {
// throw `Product not found with in ${radiusInMiles}mi range!`;
}
else {

// (4) --- Result Processing
} else {
// (4) --- Result Processing
storeProducts.forEach((storeProduct) => {
if (storeProduct?.productId && !uniqueProductIds[storeProduct.productId]) {
if (
storeProduct?.productId &&
!uniqueProductIds[storeProduct.productId]
) {
uniqueProductIds[storeProduct.productId] = true;

if (typeof storeProduct.storeLocation == "string") {
const location = storeProduct.storeLocation.split(",");
if (typeof storeProduct.storeLocation == 'string') {
const location = storeProduct.storeLocation.split(',');
storeProduct.storeLocation = {
longitude: Number(location[0]),
latitude: Number(location[1]),
}
};
}

trimmedStoreProducts.push(storeProduct)
trimmedStoreProducts.push(storeProduct);
}
});
}
}
else {
throw "Mandatory fields like userLocation latitude / longitude missing !"
} else {
throw 'Mandatory fields like userLocation latitude / longitude missing !';
}

return {
storeProducts: trimmedStoreProducts,
productIds: Object.keys(uniqueProductIds)
productIds: Object.keys(uniqueProductIds),
};
};

```

The implementation demonstrates a practical use case for Redis's Geo Location search capabilities, showcasing how to perform proximity searches combined with other filtering criteria (like product name) and present the results in a user-friendly format.
Expand Down
14 changes: 14 additions & 0 deletions docs/howtos/solutions/index-solutions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,17 @@ Learn how to easily build, test and deploy code for common microservice and cach
</div>

</div>

## Geo Location Search

<div class="row">

<div class="col">
<RedisCard
title="Geo Location Search in Redis"
description="Getting Started With Geo Location Search in Redis"
page="/howtos/solutions/geo/getting-started"
/>
</div>

</div>
23 changes: 12 additions & 11 deletions docusaurus.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const path = require('path');

module.exports = {
clientModules: ['./redirect.js'],
title: 'The Home of Redis Developers',
tagline:
'Learn all the best practices to get up and running with Redis in no time. Get started and discover the power of Redis, whether on your local machines or in the cloud.',
Expand Down Expand Up @@ -181,7 +182,7 @@ module.exports = {
name: 'Tugdual Grall',
title: 'Former Technical Marketing Manager at Redis',
image: 'profile_pic_tugdual_grall.png',
}
},
},
},
themeConfig:
Expand All @@ -202,7 +203,7 @@ module.exports = {
'elixir',
'groovy',
'sql',
'typescript'
'typescript',
],
},

Expand Down Expand Up @@ -298,14 +299,14 @@ module.exports = {
// Useful if you want to support a single color mode
disableSwitch: false,
},
announcementBar: {
id: 'redis-7-2-release', // Any value that will identify this message.
content:
'<div class="announcement-bar"><a href="https://redis.com/blog/introducing-redis-7-2/" target="_blank" rel="noopener"><span>Announcing Redis 7.2 and Enhanced Vector DB</span> <span style="margin-left:1rem">Learn more</span> <span style="margin-left:0.25rem">→</span></a></div>',
backgroundColor: 'rgb(210, 215, 254)', // Defaults to `#fff`.
textColor: 'rgb(22 31 49)', // Defaults to `#000`.
isCloseable: true, // Defaults to `true`.
},
announcementBar: {
id: 'redis-7-2-release', // Any value that will identify this message.
content:
'<div class="announcement-bar"><a href="https://redis.com/blog/introducing-redis-7-2/" target="_blank" rel="noopener"><span>Announcing Redis 7.2 and Enhanced Vector DB</span> <span style="margin-left:1rem">Learn more</span> <span style="margin-left:0.25rem">→</span></a></div>',
backgroundColor: 'rgb(210, 215, 254)', // Defaults to `#fff`.
textColor: 'rgb(22 31 49)', // Defaults to `#000`.
isCloseable: true, // Defaults to `true`.
},
}),
presets: [
[
Expand Down Expand Up @@ -354,5 +355,5 @@ module.exports = {
plugins: [
'docusaurus-plugin-sass',
path.resolve(__dirname, 'plugins', 'gtm'),
]
],
};
40 changes: 40 additions & 0 deletions redirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';

function tryRedirect() {
if (location.host.includes('learn.')) {
return;
}

let path = location.pathname;

if (!path.startsWith('/')) {
path = `/${path}`;
}

location.replace(`https://redis.io/learn${path}`);
}

export default (function () {
if (!ExecutionEnvironment.canUseDOM) {
return null;
}

return {
onRouteUpdate({ location }) {
console.log(location);

tryRedirect();
setTimeout(tryRedirect, 50);
setTimeout(tryRedirect, 150);
setTimeout(tryRedirect, 250);
setTimeout(tryRedirect, 350);
setTimeout(tryRedirect, 450);
setTimeout(tryRedirect, 550);
setTimeout(tryRedirect, 650);
setTimeout(tryRedirect, 750);
setTimeout(tryRedirect, 850);
setTimeout(tryRedirect, 950);
setTimeout(tryRedirect, 1050);
},
};
})();
Loading