DynamoDB contains value in an array using rails - ruby-on-rails

I'm studying DynamoDB using rails and I got a doubt.
I not be able to find a solution on web, so If you can solve it I'll thank.
The doubt is how can I find values into array saved on a table, for example:
I have a lot of data in my_table where there are fields called "numbers" that are arrays like:
[1,2,3,4]
[3,4,5,6]
[1,3,4,7]
[4,7,8,10]
[8,9,12,14]
[12,14,16,20]
So, I want select all entries that contains numbers 1,3,4. In this case four results.
So, my code is
result = dynamodb.scan({
table_name: "my_table",
select: "ALL_ATTRIBUTES",
attributes_to_get: ["numbers"],
scan_filter: {
"numbers" => {
attribute_value_list: [1,3,4],
comparison_operator: "CONTAINS"
}
}
})
But I get this error: One or more parameter values were invalid: Invalid number of argument(s) for the CONTAINS ComparisonOperator
How can I do this action using dynamo DB?
Thanks a lot

Try this and let me know if it works, I know from experience that DynamoDB is very painful to filter.
result = dynamodb.scan(
table_name: 'my_table',
expression_attribute_values: {
':one' => 1,
':two' => 2,
':three' => 3,
':four' => 4
},
filter_expression: 'contains(numbers, :one) OR contains(numbers, :two) OR contains(numbers, :three) OR contains(numbers, :four)'
)
I can't think of anything simpler currently, the method you linked is marked as deprecated, instead you should use expression_attribute_values and filter_expression.

Related

how do I grab a deeply nested value in ruby?

so I am trying to filter invoices by their sale_id. there is a lot of information on an invoice and I need to grab the sale_id off of a hash inside of an array. I am filtering invoices by this value but have had trouble getting the correct result
I search for invoices from a specific store with invoices = store.invoices. this will return an array populated with hashes. here is apart of what I get for one hash:
rows: [{"name"=>"sale 1", "item_id"=>1289, "sale_id"=>1413, "single_amount"=>"5000.0", "amount"=>"5000.0", "quantity"=>1, "charges_amount"=>"0.0", "tax_amount"=>"0.0", "tax_rate_id"=>nil, "total_amount"=>"5000.0"}],
note: nil,
total: 0.5e4,
paid_total: 0.0,
i've tried: filtered = invoices.select { |i| i['sale_id'] == sale.id } but this just returns an empty array. I thought maybe I just needed to reach a level deeper so I tried invoices.select{|i| i['rows'][sale_id] == 1413} but I again get an empty result.
I also tried rows = invoices.map(&:rows), which will give me a nested array with hashes of rows from all the different invoices. but this doesn't help me much because I will ultimately need the individual invoice id after finding ones that are a match. I've been stuck on this for so long and feel like I'm missing a basic piece here and would love some insight. thanks!
Edit: I was able to get this to work by modifying a suggestion with: invoices.select { |i| i['rows'][0]['sale_id'] == self.id }
You need to get the first item in the rows array and then select sale_id
invoices.select { |i| i['rows'][0]['sale_id'] == sale.id }
You can also use dig to prevent error in case some key/values are missing.
invoices.select { |i| i.dig('rows', 0, 'sale_id') == sale.id }

Dexie - Get records that are the same in two collections

I am looking for a way to get all the records in two collections that have values that match. One is the primary key, the other is a foreign key, and they are both indexed. (Dexie / IndexedDB)
I'd love to do it in the database read but I don't how. I've tried using a filter, but that's not working either. The following doesn't work:
var theDogs = this.dogArray.filter((getDogs) => {
return ( (getDogs.pk_dog === this.enteredRuns.fk_dog) )
})
console.log("theDogs ", theDogs)
I'd love it if someone could help with this. Thanks!
My project is Quasar/Electron.

How to find record using $type in mongodb?

I am using ruby on rails with MongoDB. I have one field 'possession' as string type field. I've updated it as 'Integer'.
Now, I want to find old data with specific string(for example, '6') and need to update all as integer values(means 6).
So, instead of doing each loop on all record I will just distinct values and update_all based on distinct values.
Please let me know if anyone has idea about this.
To find data using $type you can use type value as 2 for string. And using forEach function you can update the records.
You can use this query:
db.collection.find({
possession: {
$type: 2
}
}).forEach(function(data){
db.collection.update({
"$set": {
"possession": parseInt(data.possession)
}
})
})
I think #Mayuri has the right idea, but unfortunately did not test their answer. I get an error when I run their code. here is a fix to their solution. I used mongo shell to test...
I also took the liberty of using the $type string name instead of a number code.
db.collection.find({
possession: {
$type: "string"
}
}).forEach(function(data){
db.collection.update({"_id": data._id}, {
"$set": {
"possession": parseInt(data.possession)
}
})
})

How do I use join and indexBy in Yii2?

I have this, but it loads each and every ebay row individually, generating thousands of SQL statements:
$products = \app\models\Product::find()
->joinWith('ebay', false, 'inner join')
->indexBy(function($row){return $row->ebay->epid;})
->all();
I tried this, but it gave an error: 'Getting unknown property: app\models\Product::ebay.epid'
$products = \app\models\Product::find()
->joinWith('ebay', false, 'inner join')
->indexBy('ebay.epid')
->all();
Setting eager loading = true doesn't help either. It still loads each row individually then loads them again at the end.
How can I efficiently join a table in Yii and index by a value in the joined table?
You won't be able to do it with indexBy. However, ArrayHelper::index can index an array on a related model field. So here's how it can be done:
$products = \app\models\Product::find()
->with('ebay')
->all();
ArrayHelper::index($products, 'ebay.epid');
The code will run two queries, one to get all products, one to get all related ebay products. Then the array will be indexed with no DB queries at all.
I ended up doing it manually for a subset of the ids and it only uses 2 queries. I'd still be interested in the indexBy though.
$products = Product::find()->joinWith('ebay', true, 'inner join')->where(['ebay.epid' => $productIds])->all();
$ebayProducts = array();
foreach ($products as $p) {
$ebayProducts[$p->ebay->epid] = $p;
}
If you want index by relation recods via joinWith() or with() results you can use following:
->with(['relationName' => function($q) {
$q->indexBy('field_name');
}])

LINQ to SQL - Filtering the dataset between two nested collections

I have an MVC 3 project in Visual Studio c#. I have a LINQ to SQL query which works fine and by following an example listed elsewhere on stackoverflow:
Comparing two lists using linq to sql
I have been able to successfully reduce my results where my two nested collections match. This is the bit of code that did the trick (example from the link above):
var anyDesiredSkills = canidateSkills.Any( c => desiredSkills.Select( ds => ds.SkillId ).Contains( c.SkillId ) );
I've adapted this successfully, but now I need to be able to filter records using more than one condition. I was wondering if anyone would be able to adapt the above to show how you could include more than one condition?
To give you some background on what my goal is:
A search page where you can select any number of contacts
Each contact added to the search criteria may/may not have a 'role' assigned. If a role is present this should be factored in to the query.
Results returned based on this dynamic criteria.
Thanks in advance for any and all help :O)
It sounds like you're looking for something like:
var desiredSkillIds = desiredSkills.Select(_=>_.SkillId).ToList();
var matchingContacts =
from contact in Contacts
where contact.Role == null || desiredRoles.Contains(contact.Role)
where contact.Skills.Any(cs=> desiredSkillIds.Contains(cs.SkillId))
select contact;
Or in method-based syntax:
var matchingContacts = Contacts
.Where(contact => contact.Role == null || desiredRoles.Contains(contactRole))
.Where(contact => contact.Skills.Any(cs => desiredSkillIds.Contains(cs.SkillId)));
Here's the final code I used:
servicelist = servicelist.Where(
d => d.ContactSelection.Any(
h => model.ContactFilter.Select(ds => ds.StaffNumber).Contains(h.StaffNumber)
&&
model.ContactFilter.Select(ds => ds.ContactRole).Contains(h.ContactRole) || model.ContactFilter.Select(ds => ds.StaffNumber).Contains(h.StaffNumber) && model.ContactFilter.Select(ds => ds.ContactRole).Contains("0"))
);
Note that the last filter .Contains("0) is the value of '-- select role --' which is an option injected in to the drop down. Hope this helps anyone else!

Resources