Kusto query with filter depending on dashboard parameter - azure

I want to be able to toggle a filter on my query via a parameter in dashboard. How can I turn the "where" operator off?
E.g. the parameter in the dashboard is "_toggle"
let _filter = dynamic(["A", "B"]);
Table
| where id in (_filter) // execute this line only if _toggle == true
| project id
I already tried creating a second list containing all the ids and toggle between the small an the complete list via iff() but this is too resource intensive.

you could try something like this:
let _filter = dynamic(["A", "B"]);
Table
| where _toggle == false or id in (_filter)
| project id

Related

Get a category name from the id in the url using kusto query

I need to get the category name from category id using kusto query.
First i have got the most searched url from the website using the below kusto query and ran it in app insights logs
Requests
| where resultCode==200
| where url contains "bCatID"
| summarize count=sum(itemCount) by url
| sort by count
| take 1
From the above query i got the result like
https://www.test.com/item.aspx?idItem=123456789&bCatID=1282
So for corresponding categoryid=1282 i need to get the category name using kusto
you can use the parse operator.
for example:
print input = 'https://www.test.com/item.aspx?idItem=123456789&bCatID=1282'
| parse input with 'https://www.test.com/item.aspx?idItem=123456789&bCatID='category_id:long
parse_urlquery
print url ="https://www.test.com/item.aspx?idItem=123456789&bCatID=1282"
| extend tolong(parse_urlquery(url)["Query Parameters"]["bCatID"])
url
Query Parameters_bCatID
https://www.test.com/item.aspx?idItem=123456789&bCatID=1282
1282
Fiddle
Feedback to the OP query
Not an answer
KQL is case sensitive. The name of the table in Azure Application Insights is requests (and not Requests).
resultCode is of type string (and not integer/long) and should be compared to "200" (and not 200)
bCatID is a token and therefore can be searched using has or even has_cs, which should be preferred over contains due to performance reasons.
URLs can be used with different parameters. It might make more sense to summarize only by the Host & Path parts + the bCatID query parameter.
count is a reserved word. It can be used as alias only if qualified: ["count"] or ['count'] (or better not used at all).
sort followed by take 1 can be replaced with the more elegant top 1 by ...
requests
| where resultCode == "200"
| project url = parse_url(url), itemCount
| summarize sum(itemCount) by tostring(url.Host), tostring(url.Path), tolong(url["Query Parameters"]["bCatID"])
| top 1 by sum_itemCount

How to get parse_json result property ignore case in Azure Application Insight log query?

The log item looks like below, the currencyamount field has multiple case situation:
{ "AdditionalFields":{
"backendRequestBody":{
"currencyamount":1
} } }
{ "AdditionalFields":{
"backendRequestBody":{
"CurrencyAmount":1
} } }
{ "AdditionalFields":{
"backendRequestBody":{
"currencyAmount":1
} } }
However, the parse_json log query is case sensitive, is there any way to get the currentAmount field case insensitively using azure log query?
The query below only able to get one of the log entry which has lower case currencyamount field.
AzureDiagnostics
| where apiId_s contains "targetId" and AdditionalFields.backendRequestBody has "amount"
| extend amt = (parse_json(tostring(AdditionalFields.backendRequestBody)).currencyamount)
AFAIK, in parse Json we cannot be able to use Incase sensitive Json object. Instead of that you can use following way to achieve.
AzureActivity
| where apiId_s contains "targetId" and AdditionalFields.backendRequestBody has "amount"
| extend backendReqbody = parse_json(AdditionalFields.backendRequestBody)
| extend lowercuramount = parse_json(tostring(parse_json(backendReqbody.currencyamount)))
| extend curamount = parse_json(tostring(parse_json(backendReqbody.CurrencyAmount)))
| extend lowupcuramount = parse_json(tostring(parse_json(backendReqbody.currencyAmount)))
You can use conditions like (iff) Ms -Doc while filtering the data in a result.

Active users and views in azure workbooks

Can someone briefly explain the differences between active users and page views in an azure workbook? I would like to get the stats of active users of a particular azure event, but the counts shown are not realistic for the provided scenario.
As per the attached image, there is only one active user, which has to be at least 3-4 and can go up to 15-16. The value displayed in Views is unrealistic though.
Your valuable inputs are highly appreciated. Thank you
if you edit the template/workbook and look at the queries you can see exactly what is going on there:
let start = startofday(ago({Metric}));
union customEvents, pageViews
| where timestamp >= start
| where name in ({Activities}) or '*' in ({Activities}) or ('%' in ({Activities}) and itemType == 'pageView') or ('#' in ({Activities}) and itemType == 'customEvent')
{OtherFilters}
| summarize Users = dcount(user_Id), Sessions = dcount(session_Id), Views = count()
| evaluate narrow()
| project Title = case(Column == 'Users', 'Active Users', Column == 'Sessions', 'Unique Sessions', 'Views'), Metric = Value, SubTitle = '━━'
views in this case, is a count of items in the tables; Views = count(),
Users is dcount(user_Id) and Sessions = dcount(session_Id)
seeing just 1 user/session implies that there's nothing automatically generating "distinct" ids for those values, so the user_Id, session_Id fields are completely empty across all rows (the one unique id being undefined in both columns)
how user and session id values get populated is very specific to what application insights sdks you are using, and how you've configured them.

Is it possible to get query results in an App Insights inline function?

I am trying to write an App Insights query that will report back the timespan between two known events, specifically circuit breaker open and close events. The assumption is that these events always occur in pairs, so we need to know the time between the two for every occurrence in a time period.
My first attempt was to use an inline function. Simplified version below.
let timeOpened = (timeClosed:datetime)
{
let result = customEvents
| where name == 'CircuitBreakerStatusChange'
| where customDimensions['State'] == 'Open'
| where timestamp < timeClosed
| order by timestamp desc
| take 1
| project timestamp;
let scalar = toscalar(result);
scalar
};
customEvents
| where timestamp > ago(4h)
| where name == 'CircuitBreakerStatusChange'
| where customDimensions['State'] == 'Closed'
| extend timeOpen = timestamp - timeOpened(timestamp)
There may be a better way to do this. If so your ideas are welcome! But in this particular attempt the only feedback I get from Azure when running this is "Syntax error". However, I don't believe there's a syntax error here because if I just change the return value of the function from scalar to now() it runs successfully. Also I can run the body of the function in isolation successfully. Any idea what's wrong here?
I think you are getting syntax error because query language does not allow possibly recursive constructs. Now() worked because it was statically (not dynamically) retrieved at the query time.
I think you may achieve the desired outcome with serialize and prev() operators:
Table | order by timestamp asc | serialize
| extend previousTime = prev(timestamp,1)
| extend Diff = iff(customDimensions['State'] == 'Closed', timestamp - previousTime, 0)
| where Diff > 0
Note: I haven't tested the example above and it may need some additional thought to make it work (e.g. making sure that the previous record is actually "Opened" before doing previousTime calculation).

How to write a query for reordering elements

I'm working on a code that will have a list of items in a specific order and I'd like to reorder them at will. The setup isn't really that important, but to summarize it, it's a node server with MSSQL database.
For the sake of the demonstration lets say we're discussing forum categories that show in a specific order.
Id | OrderNumber | Name
------------------------
1 | 1 | Rules
2 | 3 | Off-topic
5 | 2 | General
8 | 4 | Global
I've already handled the front end that will allow me to reorder them as I like and the problem is what should happen when I press the save button on the database.
Ideally I'd like to send a JavaScript object containing item IDs in the right order to the API endpoint on the server that will execute a stored procedure. Something like:
Data = {
IDs:"5,2,8,1"
}
Is there a way that I can program a that stored procedure that it's only parameter is the list of Ids but that it can go through that list and do something I can only describe as the following pseudo code:
var Order = 1;
foreach ID in Data.IDs
UPDATE Categories SET OrderNum = Order WHERE Id = ID
Order = Order + 1
My biggest problem is that I'm not very experienced with advanced SQL commands, but that's the only part I need help with, I handled everything else already. Thank you for your help.
Example
Declare #IDs varchar(max) = '5,2,8,1'
Update A
set OrderNumber=B.RetSeq
From YourTable A
Join (
Select RetSeq = row_number() over (order by (select null))
,RetVal = B.n.value('(./text())[1]', 'int')
From ( values (cast('<x>' + replace(#IDs,',','</x><x>')+'</x>' as xml) )) A(xmldata)
Cross Apply xmldata.nodes('x') B(n)
) B on A.ID=B.RetVal
Updated Table
Id OrderNumber Name
1 4 Rules
2 2 Off-topic
5 1 General
8 3 Global

Resources