Realm - Select multiple rows - realm

I have a mongodb-realm object(collection) named 'Products':
THE SCHEMA:
const Products = {
name: "Products",
properties: {
_id: "objectId",
name : "string",
}
}
THE DATA
_id:'60f73ca7c1a70278596cc7d0',
products:[
{_id:1, name: 'product1'},
{_id:2, name: 'product2'},
{_id:3, name: 'product3'},
{_id:4, name: 'product'}
]
Now, I want to select some(say two) of these using realm. In this case I want to filter product1 and product2. I'm trying to put the ids in an array and try to filter them but it doesn't work. Below is my code
const obj = realm.objects('Products').filtered("_id == $0", [ObjectId('1'), ObjectId('2')])
Now My question is: How can I filter multiple rows in realm? And as my example above, how can I filter product1 and product2?

Related

How does one create a GSI for an Item in a Array in DyanmoDB?

I have a DyanmmoDB table that has:
Partition key: State (IE: two letter State ID)
Sort Key: City (Name of city in the state)
Items in the "record" is an array, let's say Advertisements
"StateShort": "AK",
"City": "Anchorage",
"Ads": [
{
"AdDateAdded": 1674671363999,
"AdDateExpire": 1682447536551,
"AdIDKey": "ABC-123-GUID-Here",
"AdTitle": "This is the Title to Ad 1"
"AdDescription": "Description of the Details to Ad 1",
"AdOwner": "bob#example.com",
},
{
"AdDateAdded": 1674671363999,
"AdDateExpire": 1682447536551,
"AdIDKey": "DEF-456-GUID-Here",
"AdTitle": "This is the Title to Ad 2"
"AdDescription": "Description of the Details to Ad 2",
"AdOwner": "bob#example.com",
}
]
Query to retrieve all ads in State and City, easy-peasy, as they are PK and SK.
but, I do NOT want to Scan to find all the ads that AdOwner has ("bob#example.com"). They may have Ads in other states and city requiring me to Scan entire table.
FEELS like a perfect use case for a Global secondary indexes.
I've added AdOwner as a GSI but, clearly it can't find the key in the array.
Question: Is this solvable with a GSI? If so, what structure would that look like?
After creating the GSI, I've tried this code but, it returns no items
const params = {
"TableName": "My_table",
"IndexName": "AdEmail-index",
"KeyConditionExpression": "#IndexName = :AccountID",
"ExpressionAttributeNames": {
"#IndexName": "AdOwner",
},
ExpressionAttributeValues: {
":AccountID": "bob#example",
},
"ScanIndexForward": false
}
try{
const item = await dynamo.query(params).promise()
console.log("what: ", item)
}
catch (e) {
console.log("ERROR", e)
}
No, a global secondary index key must be a top level attribute and be of type string, number or binary.
You should vertically shard your items, giving you more flexibility:
pk
sk
data
AdOwner
AK
Anchorage#BC-123-GUID-Here
{}
bob#example.com
AK
Anchorage#BDEF-456-GUID-Here
{}
bob#example.com
All ads in a state and city, still easy, using Query:
SELECT * FROM MY TABLE WHERE pk = 'AK' AND sk BEGINS_WITH 'Anchorage'
You can now create a GSI on the AdOwner to fulfill your second access pattern.
SELECT * FROM MY TABLE.INDEX WHERE AdOwnder = 'bob#example.com'

How to query data in Cosmos db from nested json

I have some difficulty in writing a query to query data from nested json in Cosmos db.
Sample json -
{
"id": xyz
"items": [
{
"arr_id": 1,
"randomval": "abc"
},
{
"arr_id": 2,
"randomval": "mno"
},
{
"arr_id": 1,
"randomval": "xyz"
}
]
}
Lets say in above case, if i want to get all jsons data with arr_id = 1.
Expected Result -
{
"id": xyz
"items": [
{
"arr_id": 1,
"randomval": "abc"
},
{
"arr_id": 1,
"randomval": "xyz"
}
]
}
If i write a query like below, it still gives me entire json.
Select * from c where ARRAY_CONTAINS(c.items, {"arr_id": 1},true)
I want it to filter it items level too. I guess it just filters at header level and provides entire json where even a single arr_id matches.
You can use either
SELECT c.id, ARRAY(SELECT VALUE i FROM i in c.items where i.arr_id = 1) as items
FROM c
WHERE EXISTS(SELECT VALUE i FROM i in c.items where i.arr_id = 1)
or
SELECT c.id, ARRAY(SELECT VALUE i FROM i in c.items where i.arr_id = 1) as items
FROM c
depending on whether you expect an empty array if no arrayItem with arr_id=1 exists or you wnat to filter out those records compeletely.
Also see this link for a good overview of query options across arrays - https://devblogs.microsoft.com/cosmosdb/understanding-how-to-query-arrays-in-azure-cosmos-db/

Return the content of a specific object in an array — CosmosDB

This is a follow up to question 56126817
My current query
SELECT c.EventType.EndDeviceEventDetail FROM c
WHERE c.EventType.EndDeviceEventType.eventOrAction = '93'
AND c.EventType.EndDeviceEventType.subdomain = '137'
AND c.EventType.EndDeviceEventType.domain = '26'
AND c.EventType.EndDeviceEventType.type = '3'
AND ARRAY_CONTAINS(c.EventType.EndDeviceEventDetail,{"name":
"RCDSwitchReleased","value": "true" })
My Query Output
[
{
"EndDeviceEventDetail": [
{
"name": "Spontaneous",
"value": "true"
},
{
"name": "DetectionActive",
"value": "true"
},
{
"name": "RCDSwitchReleased",
"value": "true"
}
]
}
]
Question
How could change my query so that I select only the "value" of the array that contains the "name" "DetectionActive" ?
The idea behind is to filter the query on one array entry and get as output the "value" of another array entry. From reading here, UDF (not the best in this case) and JOIN should be used.
First attempt
SELECT t.value FROM c JOIN t in c.EventType.EndDeviceEventDetail
WHERE c.EventType.EndDeviceEventType.eventOrAction = '93'
AND c.EventType.EndDeviceEventType.subdomain = '137'
AND c.EventType.EndDeviceEventType.domain = '26'
AND c.EventType.EndDeviceEventType.type = '3'
AND ARRAY_CONTAINS(c.EventType.EndDeviceEventDetail,{"name":
"RCDSwitchReleased","value": "true" })
Gets Bad Request (400) error
Your idea and direction is right absolutely, I simplified and tested your sql.
SELECT detail.value FROM c
join detail in c.EventType.EndDeviceEventDetail
WHERE c.EventType.EndDeviceEventType.eventOrAction = '93'
AND ARRAY_CONTAINS(c.EventType.EndDeviceEventDetail,{"name":
"RCDSwitchReleased","value": "true" })
Found the error message as below:
It because that the value is the reserved word in cosmos db sql syntax,please refer to this case:Using reserved word field name in DocumentDB
You could try to modify the sql like:
SELECT detail["value"] FROM c

How can I dynamically substitute where condition parameters in Dynamodb?

Current code Example:
Scan * from table_name where name='ajith' and lastname='gupta';
In the real scenario, I will be getting different values. I need to pass those here in this above query and get the output. Also, it's better to prevent data injection.
Desired:
Scan * from table_name where name=? and lastname=?;
Use the Expression Attribute Names and Expression Attribute Values parameters.
Javascript example using the DocumentClient:
let params = {
TableName: 'table_name',
KeyConditionExpression: '#lname = :lname and #name = :name',
ExpressionAttributeNames: {
'#name': 'name',
'#lname': 'lastname'
},
ExpressionAttributeValues: {
':name': 'ajith',
':lname': 'qupta',
}
}
dynamodbDocumentClient.query(params).promise().then(result => {
// soSomethingWithTheResultHere
})
This example assumes you have a table with partition and sort key of called name and lastname
See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html for more information about queries.

SQLite count and get other records in Cordova

Snippet of my code:
var sql = "SELECT name,data, COUNT(name) as 'mycount' FROM floodMaps WHERE name='?' GROUP BY name,data";
db.transaction(function(tx) {
tx.executeSql(sql,[flodMapName], function(tx,res){
//console.log(res.rows.item(0).data);
console.log(res.rows.item(0).mycount);
if(res.rows.item(0).mycount > 0) {
console.log('GETTING DATA FROM DB...');
It throws an error:
a statement with no error handler failed: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I am trying to count at the same time get the data from a table but unfortunately it's not working. I did my research, I haven't found a good documentation for the plugin.
This is how I created the table:
document.addEventListener("deviceready", function(){
//database
db = window.sqlitePlugin.openDatabase({name: 'demo.db', location: 'default'});
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS floodMaps (name text primary key, data text)');
tx.executeSql('DELETE FROM floodMaps');
}, function(error) {
console.log('Create Table ERROR: ' + error.message);
}, function() {
console.log('Table created successfully.');
});
//end database
}, false);
The whole code is here.
I believe that the ? parameter placeholder should not be in single quotes. Try this instead:
var sql = "SELECT name, data, COUNT(name) as `mycount` FROM floodMaps WHERE name= ? GROUP BY name, data";
I guess you need not have to use single quote at all for alias. You can use as follows:
SELECT name,data, COUNT(name) as mycount FROM floodMaps WHERE name=?
Check out this official link that has sample for count query too.

Resources