How to store output of KQL query in a variable - azure

This code:
let myvar = Usage| where IsBillable == true| distinct DataType;
throws an error
no tabular expression found

let is used for Ad-Hoc definitions, in a query's scope.
Your code does not contain a query, only a let statement.
You can use it as following:
let myvar = Usage | where IsBillable | distinct DataType;
myvar
P.S.
IsBillable == true can be shortand to IsBillable

Related

KQL query showing preceding logs from a specific log

I'm working on a query where I need the log that has a message of "Compromised" in it, then I want it to return the preceding 5 "deny" logs. New to KQL and just don't know the operator, so I appreciate the help!
Current query:
| sort by TimeGenerated
| where SourceIP == "555.555.555.555"
| where TimeGenerated between (datetime(10/20/2021, 16:25:41.750).. datetime(10/20/2021, 16:35:41.750))
| where AdditionalExtensions has "Compromised" or DeviceAction == "deny"
Ideally in my head it would be something like:
Needed query:
| sort by TimeGenerated
| where SourceIP == "555.555.555.555"
| where AdditionalExtensions has "Compromised"
| \\show preceding 5 logs that have DeviceAction = "deny"
Thank you!
You can use the prev() function
Here's how you do it:
let N = 5; // Number of records before/after records for which Cond is true
YourTable
| extend Cond = (SourceIP == "555.555.555.555") and (AdditionalExtensions has "Compromised") and (DeviceAction == "deny") // The predicate to "identify" relevant records
| sort by TimeGenerated asc
| extend rn = row_number(0, Cond)
| extend nxt = next(rn, N), prv = prev(rn, N)
| where nxt < N or (rn <= N and isnotnull(prv)) or Cond
| project-away rn, nxt, prv, Cond
Note that the sorting is done after the extend, and not before - this is more optimal (it's always best to push down the sorting as further down as possible).
(Courtesy of #RoyO)

How to implement nested filters in diesel?

I'm quite new to Rust and Diesel. I'm now trying to implement Diesel filtering for query like this:
-- #param1 is duration in years
-- #param2 is duration in months
SELECT columns FROM a
WHERE
(...dynamic AND clauses)
AND (((a.min_unit = "Years") AND (a.min_duration <= #param1))
OR ((a.min_unit = "Months") AND (a.min_duration <= #param2)))
(...dynamic AND clauses)
After some searches in docs and around the web, I still couldn't find how to do this.
My closest guess is:
let param1 = ...;
let param2 = ...;
let mut query = a::table.select(a::all_columns).into_boxed();
// dynamic clauses: query = query.filter(...) ...
query = query.filter(a::min_unit.eq(Some("Years")).and(a::min_duration.le(Some(param1))))
.or_filter(a::min_unit.eq(Some("Months")).and(a::min_duration.le(Some(param2))));
// dynamic clauses: query = query.filter(...) ...
let results = a::table.load<A>(&*conn);
Anyone has idea?
Thanks!
Your code actually looks correct (I haven't run it). The documentation here points to how it is done: https://docs.diesel.rs/diesel/query_dsl/trait.QueryDsl.html#method.or_filter foo.filter(bar).or_filter(baz) is like foo.filter(bar.or(baz)) but the second one is "nested". So, to get
(id = 5 OR other = 6) AND foo=7
one would do
.filter(id.eq(5).or(other.eq(6))).filter(foo.eq(7)).
Hope that helps!
Well, here is my latest try:
let min_months_predicate = a::min_unit.eq(Some("Months"))
.and(a::min_duration.le(Some(param1)));
let min_years_predicate = a::min_unit.eq(Some("Years"))
.and(a::min_duration.le(Some(param1)));
query = query.filter(min_months_predicate.or(min_years_predicate))
.filter(a::max_duration.ge(Some(param2)));
debug!("TEST QUERY: {:?}", debug_query(&query));
which yields this query:
"SELECT \"a\".\"id\", \"a\".\"code\", .... WHERE (\"a\".\"min_unit\" = $1 AND \"a\".\"min_duration\" <= $2 OR \"a\".\"min_unit\" = $3 AND \"a\".\"min_duration\" <= $4) AND \"a\".\"max_duration\" >= $5"
And when I use sql EXPLAIN with this query, I got this clause:
Filter: ((max_duration >= 60) AND (((min_unit = 'Months'::text) AND (min_duration <= 3)) OR ((min_unit = 'Years'::text) AND (min_duration <= 5))))
which seems correct.

How to use series_divide() in Kusto?

I am not able correctly divide time-series data with another time-series.
I get data from my TestTablewhich results in the following view:
TagId, sdata
8862, [0,0,0,0,2,2,2,3,4]
6304, [0,0,0,0,2,2,2,3,2]
I want to divide the sdata series for tagId 8862 with the series from 6304
I expect the following result:
[NaN,NaN,NaN,NaN,1,1,1,1,2]
When I try the below code, I only get two empty ddata rows in my S2 results
TestTable
| where TagId in (8862,6304)
| make-series sdata = avg(todouble(Value)) default=0 on TimeStamp in range (datetime(2019-06-27), datetime(2019-06-29), 1m) by TagId
| as S1;
S1 | project ddata = series_divide(sdata[0].['sdata'], sdata[1].['sdata'])
| as S2
What am I doing wrong?
both arguments to series_divide() can't come from two separate rows in the dataset.
here's an example for how you could achieve that (based on the limited-and-perhaps-not-fully-representative-of-your-real use case, as shown in your question)
let T =
datatable(tag_id:long, sdata:dynamic)
[
8862, dynamic([0,0,0,0,2,2,2,3,4]),
6304, dynamic([0,0,0,0,2,2,2,3,2]),
]
;
let get_value_from_T = (_tag_id:long)
{
toscalar(
T
| where tag_id == _tag_id
| take 1
| project sdata
)
};
print sdata_1 = get_value_from_T(8862), sdata_2 = get_value_from_T(6304)
| extend result = series_divide(sdata_1, sdata_2)
which returns:
|sdata_1 | sdata_2 | result |
|--------------------|---------------------|---------------------------------------------|
|[0,0,0,0,2,2,2,3,4] | [0,0,0,0,2,2,2,3,2] |["NaN","NaN","NaN","NaN",1.0,1.0,1.0,1.0,2.0]|

how to return a scarlar with let as method

I am trying to compare if an array is a subset of other and use it in another query. I could get the comparision method working. However, if I use the compare method in another query I get an error saying "Left and right side of the relational operator must be scalars" This hints that the comparearrays is not reutrning a scalar. Any ideas?
let x = parsejson('["a", "b", "c"]');
let y = parsejson('["a", "b", "c"]');
let z = parsejson('["b","a"]');
let comparearrays = (arr1:dynamic, arr2:dynamic)
{
let arr1Length = arraylength(arr1);
let total =
range s from 0 to arr1Length-1 step 1
| project dat = iff(arr1[s] in (arr2), true , false)
| where dat == true
| count;
total | extend isEqual= iff(Count == arr1Length,'true','false') | project
tostring(isEqual)
};
//comparearrays(z, x)
datatable (i:int) [4] | project i | where comparearrays(x,y) == 'true'
You are correct in your understanding - the current implementation returns a table with a single row and single column, but have no fear - toscalar to the rescue:
let x = parsejson('["a", "b", "c"]');
let y = parsejson('["a", "b", "c"]');
let z = parsejson('["b","a"]');
let comparearrays = (arr1:dynamic, arr2:dynamic)
{
let arr1Length = arraylength(arr1);
let result =
range s from 0 to arr1Length-1 step 1
| project dat = iff(arr1[s] in (arr2), true , false)
| where dat == true
| count
| extend isEqual = iff(Count == arr1Length,'true','false')
| project tostring(isEqual);
toscalar(result)
};
//comparearrays(z, x)
datatable (i:int) [4] | project i | where comparearrays(x,y) == 'true'
You do have a bug in the comparearrays functions, since comparearrays(z, x) returns true which is not correct....

Access variable from outside of the function in jQuery

Please see my exaple:
var AbcVar = "abc";
function Abc(AbcVar){
console.log(AbcVar);
}
It this wrong way to allowing function to access external var?
Why is the output of console.log undefined?
It's time to meet Mr. Scoping.
Plainly speaking, scoping is an encapsulation of variables (note that in javascript, functions are also variables.) Now, in the imaginary language I just made up, the { character starts a scope and } ends it, variables are defined with simple equality (x = 42 for example):
{ |
x = 42; |
{ | |
y = "I'm in an inner scope!"; | |
x == 42; //true | |
{ | | |
x == 42; | | |
y == "I'm in an inner scope!"; | | |
| x, y, z are defined |
z = "pyramid time!"; | | |
y = y + "...not"; | | x, y are defined | x is defined
} | | |
y == "I'm in an inner scope!...not"; | |
//z is not defined | |
x = 4; | |
} | |
x == 4; |
//y is undefined |
//z is undefined |
} |
javascript has lexical scoping. Put simply, functions create a new scope:
var x = 42;
(funciton () {
x === 42;
var y = 5;
})();
//y is undefined
Now, there's an additional place where variables can be created, and that is in the function arguments. The two following functions behave the same (arguments is a pseudo-array containing the parameters passed into the function):
function parameterfull(a, b, c) {
//do stuff with a, b, c
}
function parameterless() {
var a = arguments[0], b = arguments[1], c = arguments[2];
//do stuff with a, b, c
}
If you happen to not pass an argument, its value will be undefined.
Now, using your function and the above translation:
var AbcVar = "abc";
function Abc() {
var AbcVar = arguments[0];
console.log(AbcVar);
}
So now you see why AbcVar is (sometimes) undefined inside the function.
tl;dr The function parameter AbcVar is overriding the global variable AbcVar, and since you didn't pass a value to the function, it's undefined (but only inside of the function, the global AbcVar remains the same.)
Inside the function, AbcVar will refer to the parameter AbcVar of the function. If you don't pass any parameter, the value will be undefined.
The parameter shadows the variable in higher scope with the same name. If you want to access it, you have to remove or rename the parameter. That said, you should always prefer passing arguments to functions (where possible).
hi you can change this to
var AbcVar = "abc";
function Abc(bbb){
console.log(AbcVar);
}
you can access external global var,if you write inside function,it assume that like;
var AbcVar = "abc";
function Abc(var AbcVar){
console.log(AbcVar);
}
so inside funciton AbcVar is new vaiable and null ,it shadow global AbcVar
if you run the function you've just created and pass it your AbcVar,
console.log(AbcVar);
it loggs "abc" as expected
Consider the following code
var AbcVar = "abc";
function logVariable(passedIn){
console.log(passedIn);
}
logVariable(AbcVar);
which creates a variable, a function to log the value of the variable, and then passes the variable to the logger which loggs it in the console
If you notice two lines on your interactive console after you run your logger function: abc followed by undefined
the first is the line printed when you call console.log() and the second is the value that logVariable returns after executing, which is undefined on success.

Resources