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
with CONTAINS
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?
Retrieving an item in DynamoDB requires using GetItem, and specifying the table name and item primary key. Be sure to include a complete primary key rather than omitting a portion. For example, omitting the sort key of a composite key. It executes as an eventually consistent read.
In Amazon DynamoDB, you can use either the DynamoDB API, or PartiQL, a SQL-compatible query language, to query an item from a table. With Amazon DynamoDB the Query action lets you retrieve data in a similar fashion. The Query action provides quick, efficient access to the physical locations where the data is stored.
A filter expression determines which items within the Query results should be returned to you. All of the other results are discarded. A filter expression is applied after a Query finishes, but before the results are returned.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With