How to make search using "contains" with DynamoDB
19,842
The CONTAINS
operator is not available in the query
API. You need to use the scan
API for this (see this link).
Try the following:
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();
const SEARCH_KEYWORD = "b";
let params = {
TableName : 'TABLE_NAME',
FilterExpression: "contains(#movie_name, :movie_name)",
ExpressionAttributeNames: {
"#movie_name": "movie_name",
},
ExpressionAttributeValues: {
":movie_name": SEARCH_KEYWORD,
}
};
documentClient.scan(params, function(err, data) {
console.log(data);
});
Result:
{
Items: [
{
movie_id: 2,
movie_name: 'name b'
}
],
Count: 1,
ScannedCount: 2
}
Related videos on Youtube
Author by
Skate to Eat
Updated on June 04, 2022Comments
-
Skate to Eat almost 2 years
I'm trying to make search function on my React app.
I have this DynamoDB table:
--------------------- movie_id | movie_name --------------------- 1 | name a --------------------- 2 | name b ---------------------
I want to make a search function to search "b" on the React app's search input and get "name b" from the DB as the result.
I tried to
query
withCONTAINS
but didn't work and does not seem to be a proper way to do it.const SEARCH_KEYWORD = "b"; let params = { TableName : 'TABLE_NAME', KeyConditionExpression: "contains(#movie_name, :movie_name)", ExpressionAttributeNames:{ "#movie_name": 'movie_name' }, ExpressionAttributeValues:{ ":movie_name": SEARCH_KEYWORD } }; documentClient.query(params, function(err, data) { console.log(data); });
What is the best way to create search function on my React app with DynamoDB?
Does it even make sense to run a query by the search keyword to check if the data contains keyword value?
-
Skate to Eat almost 7 yearsThank you so much! It works! One more question tho, is this ideal way to build search function? or there's better way to do this?
-
Zanon almost 7 years@Ohsik, searching with "contains" will never be optimal because it will always require a full scan of the table. This can bring to performance issues if you have a lot of data. However, checking if the name "begins with" can be used with the
query
API and benefit from indexes, which will greatly improves the performance. But obviously "begins with" is different from "contains". -
Zanon almost 7 years@Ohsik, if you need to use "contains" with millions of rows, I suggest that you look after Elasticsearch integration with DynamoDB.
-
user3277530 over 3 yearsI think that it is possible now
-
user3277530 over 3 yearsyou can use it as a filter expression now
-
lopezdp about 3 yearsLimitation here is that it will only scan through 1mb of data at a time... :(
-
theboshy about 3 yearshow can this be applied to a list of objects instead of a list of plain strings?