I'm using the following document to show me how to connect and query data from Azure Cosmos DB SQL API account using Node.JS
https://learn.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs
There is a section in the document that is set to query the Azure Cosmos DB
// query to return all items
const querySpec = {
query: "SELECT * from c"
};
const { resources: results } = await container.items
.query(querySpec)
.fetchAll();
Can someone let me know where the results of the above query is displayed?
I'm using Visual Studio Code to build the code, but when I run it I'm not sure where the results are displayed. For example, will the results be display in Azure Cosmos DB? Within Visual Studio Code? or where?
You've probably gathered I'm a Node.JS newbie
Thanks
By default, it will show in your console where you run your code. But I did not see any output in your code, maybe you should add something like the following
if (results.length == 0) {
throw "No items found matching";
}
// Change person to your data type
const person = results[0];
console.log("The '" + person.id + "' family has lastName '" + person.lastName + "'");
console.log("The '" + person.id + "' family has " + person.children.length + " children '");
Related
I wanted to get the query stats for a container in JSON or any other format supported from azure cosmosdb. Is there a way to get the query stats for a specific query from the azure cosmosdb through the rest api exposed?
You can get query stats from response header.
Code:
var qry = new SqlQuerySpec { query = "SELECT * FROM root" };
var result = await client.PostWithNoCharSetAsync(new Uri(baseUri, resourceLink), qry);
//get response header
Console.WriteLine("result:" + result);
//get documents
Console.WriteLine("result content:" + result.Content.ReadAsStringAsync().Result);
Result:
You can get code sample here.https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/rest-from-.net/Program.cs
As the title describes, I'm trying to change the TTL of a cosmos db table.
I couldn't find anything in c#/powershell/arm templates
Here is what I'm trying to achieve
The only thing I was able to find is the api call that is triggered in azure portal, but I'm wondering if it is safe to use this API directly?
In Cosmos DB Table API, Tables are essentially Containers thus you can use Cosmos DB SQL API SDK to manipulate the Table. Here's the sample code to do so:
var cosmosClient = new CosmosClient(CosmosConnectionString);
var database = cosmosClient.GetDatabase(Database);
var container = database.GetContainer("test");
var containerResponse = await container.ReadContainerAsync();
var containerProperties = containerResponse.Resource;
Console.WriteLine("Current TTL on the container is: " + containerProperties.DefaultTimeToLive);
containerProperties.DefaultTimeToLive = 120;//
containerResponse = await container.ReplaceContainerAsync(containerProperties);
containerProperties = containerResponse.Resource;
Console.WriteLine("Current TTL on the container is: " + containerProperties.DefaultTimeToLive);
Console.ReadKey();
Setting TTL is now supported through Microsoft.Azure.Cosmos.Table directly with version >= 1.0.8.
// Get the table reference for table operations
CloudTable table = <tableClient>.GetTableReference(<tableName>);
table.CreateIfNotExists(defaultTimeToLive: <ttlInSeconds>);
The following stored procedure failed to produce any result even though the SQL query used in it produced results when tested on the Azure portal.
function checktemp() {
var context = getContext();
var container = context.getCollection();
var response = context.getResponse();
let query = `SELECT DISTINCT {"Elevator": t.connectiondeviceid,
"Vibration": t["vibration"],
"Temperature": t["temperature"]}
FROM t
WHERE t["temperature"] > 75
AND t.EventEnqueuedUtcTime > "2019-08-03T20:30:51.905Z"
ORDER BY t["temperature"] DESC`
// Query documents and take 1st item.
var isAccepted = container.queryDocuments(
container.getSelfLink(), query,
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
response.setBody('no docs found');
}
else {
var body = { moststrain: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
I expect to have items returned, but I always get 'no docs found'. My partition key is /ConnectionDeviceId.
Tested your sample document with your stored procedure code,it works for me.Your SP structure should be fine.
Some mistake with the spell of property(ConnectionDeviceId) you provide,it should be ConnectionDeviceId in sql:t.ConnectionDeviceId.
To solve such issue like something works in the portal, no results in SP, i suggest you removing query statements partially step by step to locate which part of SQL causes no results.
Anyway,the issue is related to partition key. When you query data in the portal, it scans all the partitions. However,if you execute SP,it only scans specific partition.
Since the data is partitioned on 'connectiondeviceid', I was supposed to provide a value of it during execution of the stored procedure.
I have the following code to use to update and existing record in a postgres database using Node.js:
var mods = "UPDATE users SET login = '" + now + "' WHERE name = '" + String(req.body.usr) + "';";
client.query(mods, function(err, result) {
//call `done()` to release the client back to the pool
done();
if(err){
console.log(err);
}
});
I would like to provide multiple 'WHERE' conditions instead of just one...however I am having problems with syntax. For example I wish to do something like
'WHERE name = ' + String(req.body.usr) AND 'WHERE login = ' + String(req.body.password)
Any help would be appreciated, I am just having syntax issues with trying to provide more than one WHERE condition to the update query. I thank you in advance.
Don't write WHERE multiple times, just use AND to chain them. Or, you could google Postgress Where.
var mods = "UPDATE users SET login = '" + now + "' WHERE name = '" + name + "' AND login ='" + login + "' AND ... ";
I am trying to query the entities in Azure Cosmos DB table on the basis of Timestamp using azure table storage SDK for node.js
The timestamp I have in DB is following
and in code I am querying creating the filter like this
const filter = storage.TableQuery.dateFilter(
"Timestamp",
storage.TableUtilities.QueryComparisons.GREATER_THAN,
new Date(Date.UTC(2019, 0, 1))
);
query = new TableQuery().where(filter);
But no results are being returned for me.
I have googled a bit and found the following stack overflow question as well
nodejs query azure storage table according to timestamp
Both solutions in it's answer are not working for me.
Here is my sample code works for me, as below, which you can refer to try again. Hope it helps.
I installed Azure Storage SDK for Node.js via command npm i azure-storage
var azure = require('azure-storage');
var tableService = azure.createTableService('<your storage account>','<your storage key>');
There are two ways to build a query object.
Directly use where function with filter template string and values.
var query = new azure.TableQuery().where('Timestamp ge ?', new Date(Date.UTC(2019, 0, 1)));
First build a filter expression, then to generate a query object.
var filter = azure.TableQuery.dateFilter('Timestamp', azure.TableUtilities.QueryComparisons.GREATER_THAN, new Date(Date.UTC(2019, 0, 1)));
var query = new azure.TableQuery().where(filter);
Finally, to query table entities.
console.log(query);
tableService.queryEntities('<your table name>', query, null, function(error, result, response) {
if(!error) {
// query was successful
console.log(result);
}
console.log(error);
});