Kibana scripted field error tells me I dont have any values in field while they do show up in discovery - kibana

I've been trying to create a scripted field in which i want to make a URL which directs me to a specific APM timeline page. The values I want to add to this URL are filters which are needed to select te specific transaction in APM.
When i try to create this field I keep getting an error telling me there are no values in 2/4 fields.
The error is:
{
"root_cause": [
{
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"org.elasticsearch.index.fielddata.ScriptDocValues$Strings.get(ScriptDocValues.java:496)",
"org.elasticsearch.index.fielddata.ScriptDocValues$Strings.getValue(ScriptDocValues.java:503)",
"'https://xxx/xxx/xxx/xxxrangeFrom=now-1h&rangeTo=now&traceId=' + doc['trace.id'].value + '&transactionId=' + doc['transaction.id'].value + '&transactionName=' + doc['transaction.name'].value + '&transactionType=' + doc['transaction.type'].value",
" ^---- HERE"
],
"script": "'https://xxx/xxx/xxx/xxxrangeFrom=now-1h&rangeTo=now&traceId=' + doc['trace.id'].value + '&transactionId=' + doc['transaction.id'].value + '&transactionName=' + doc['transaction.name'].value + '&transactionType=' + doc['transaction.type'].value",
"lang": "painless",
"position": {
"offset": 184,
"start": 0,
"end": 244
}
}
],
"type": "search_phase_execution_exception",
"reason": "Partial shards failure",
"phase": "fetch",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "apm-2020.47-esdec-backend-error-7.8.1",
"node": "uvVVVbE9RRGTnxaF6_S73g",
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"org.elasticsearch.index.fielddata.ScriptDocValues$Strings.get(ScriptDocValues.java:496)",
"org.elasticsearch.index.fielddata.ScriptDocValues$Strings.getValue(ScriptDocValues.java:503)",
"'https://xxx/xxx/xxx/xxxrangeFrom=now-1h&rangeTo=now&traceId=' + doc['trace.id'].value + '&transactionId=' + doc['transaction.id'].value + '&transactionName=' + doc['transaction.name'].value + '&transactionType=' + doc['transaction.type'].value",
" ^---- HERE"
],
"script": "'https://xxx/xxx/xxx/xxxrangeFrom=now-1h&rangeTo=now&traceId=' + doc['trace.id'].value + '&transactionId=' + doc['transaction.id'].value + '&transactionName=' + doc['transaction.name'].value + '&transactionType=' + doc['transaction.type'].value",
"lang": "painless",
"position": {
"offset": 184,
"start": 0,
"end": 244
},
"caused_by": {
"type": "illegal_state_exception",
"reason": "A document doesn't have a value for a field! Use doc[<field>].size()==0 to check if a document is missing a field!"
}
}
}
]
When I check in discovery my fields definetly do have values. I can't figure out what the problem is. Anybody has any idea?

Try with .size() == 1 and other checks for the fields.
if (doc['field.keyword'].size() == 1 && doc['field.keyword'] != null && doc.containsKey('field')) {
return Double.parseDouble(doc['field.keyword'].value)
}
This answer provides more information about the breaking changes in Elastic 7:
https://discuss.elastic.co/t/scripted-fields-dont-work-after-upgrading-to-7-1/185829/2

Related

Getting a specific item in a sub array and selecting one value from it

I want to get the boardgame rank (value) from this nested array in Cosmos DB.
{
"name": "Alpha",
"statistics": {
"numberOfUserRatingVotes": 4155,
"averageRating": 7.26201,
"baysianAverageRating": 6.71377,
"ratingStandardDeviation": 1.18993,
"ratingMedian": 0,
"rankings": [
{
"id": 1,
"name": "boardgame",
"friendlyName": "Board Game Rank",
"type": "subtype",
"value": 746
},
{
"id": 4664,
"name": "wargames",
"friendlyName": "War Game Rank",
"type": "family",
"value": 140
},
{
"id": 5497,
"name": "strategygames",
"friendlyName": "Strategy Game Rank",
"type": "family",
"value": 434
}
],
"numberOfComments": 1067,
"weight": 2.3386,
"numberOfWeightVotes": 127
},
}
So I want:
{
"name": "Alpha",
"rank": 746
}
Using this query:
SELECT g.name, r
FROM Games g
JOIN r IN g.statistics.rankings
WHERE r.name = 'boardgame'
I get this (so close!):
{
"name": "Alpha",
"r": {
"id": 1,
"name": "boardgame",
"friendlyName": "Board Game Rank",
"type": "subtype",
"value": 746
}
},
But extending the query to this:
SELECT g.name, r.value as rank
FROM Games g
JOIN r IN g.statistics.rankings
WHERE r.name = 'boardgame'
I get this error:
Failed to query item for container Games:
Message: {"errors":[{"severity":"Error","location":{"start":21,"end":26},"code":"SC1001","message":"Syntax error, incorrect syntax near 'value'."}]}
ActivityId: 0a0cb394-2fc3-4a67-b54c-4d02085b6878, Microsoft.Azure.Documents.Common/2.14.0
I don't understand why this doesn't work? I don't understand what the syntax error is. I tried adding square braces but that didn't help. Can some help me understand why I get this error and also how to achieve the output I'm looking for?
This should work,
SELECT g.name, r["value"] as rank
FROM Games g
JOIN r IN g.statistics.rankings
WHERE r.name = 'boardgame'

Dynamically Parse Child Nodes in JSON

I have a deserialized object that I want to dynamically loop through to return the related results. The response package looks like so:
{"RatingResponse":
{"Success":"true",
"Message":"",
"QuoteID":"57451",
"LoadNum":"57451",
"Rates":
{"Rate":
[
{"SCAC":"test1",
"CarrierName":"TEST1",
"TransitTime":"1",
"ServiceLevel":"D",
"TotalCost":"1,031.82",
"ThirdPartyCharge":"1,031.82",
"Accessorials":
{"Accessorial":
[
{"Code":"400",
"Cost":"1,655.55",
"Description":"Freight"
},
{"Code":"DSC",
"Cost":"-952.77",
"Description":"Discount"
},
{"Code":"FUE",
"Cost":"329.04",
"Description":"Fuel Surcharge"
}
]
},
"QuoteNumber":""
},
{"SCAC":"test2",
"CarrierName":"TEST2",
"TransitTime":"1",
"ServiceLevel":"D",
"TotalCost":"1,031.82",
"ThirdPartyCharge":"1,031.82",
"Accessorials":
{"Accessorial":
[
{"Code":"400",
"Cost":"1,655.55",
"Description":"Freight"
},
{"Code":"DSC",
"Cost":"-952.77",
"Description":"Discount"
},
{"Code":"FUE",
"Cost":"329.04",
"Description":"Fuel Surcharge"
}
]
},
"QuoteNumber":""
}
]
},
"AverageTotalCost":"1,031.82"
}
}
I have parsed the response data so that there is less information to work with, especially since I only need the Accessorial Costs. The parsed response looks like
[
{
"SCAC": "test1",
"CarrierName": "TEST1",
"TransitTime": "1",
"ServiceLevel": "D",
"TotalCost": "1,031.82",
"ThirdPartyCharge": "1,031.82",
"Accessorials": {
"Accessorial": [
{
"Code": "400",
"Cost": "1,655.55",
"Description": "Freight"
},
{
"Code": "DSC",
"Cost": "-952.77",
"Description": "Discount"
},
{
"Code": "FUE",
"Cost": "329.04",
"Description": "Fuel Surcharge"
}
]
},
"QuoteNumber": ""
},
{
"SCAC": "test2",
"CarrierName": "TEST2",
"TransitTime": "1",
"ServiceLevel": "D",
"TotalCost": "1,031.82",
"ThirdPartyCharge": "1,031.82",
"Accessorials": {
"Accessorial": [
{
"Code": "400",
"Cost": "1,655.55",
"Description": "Freight"
},
{
"Code": "DSC",
"Cost": "-952.77",
"Description": "Discount"
},
{
"Code": "FUE",
"Cost": "329.04",
"Description": "Fuel Surcharge"
}
]
},
"QuoteNumber": ""
}
]
The problem I am facing is that I will never know how many Rate items will come back in the response data, nor will I know the exact amount of Accessorial Costs. I'm hoping to capture the Rate child node counts and the Accessorial child node counts per Rate. Here's what I have so far.
Root rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(responseFromServer);
//rate stores the parsed response data
JArray rate = (JArray)JObject.Parse(responseFromServer)["RatingResponse"]["Rates"]["Rate"];
var rate2 = rate.ToString();
//this for loop works as expected. it grabs the number of Rate nodes (in this example, 2)
for (int i = 0; i < rate.Count(); i++)
{
dynamic test2 = rate[i];
//this is where I'm struggling
dynamic em = (JArray)JObject.Parse(test2)["Accessorials"]["Accessorial"].Count();
for (int j = 0; j < em; j++)
{
string test3 = test2.Accessorials.Accessorial[j].Cost;
System.IO.File.AppendAllText(logPath, Environment.NewLine + test3 + Environment.NewLine);
}
}
I apologize in advance for the bad formatting and odd variable names - I'm obviously still testing the functionality, so I've been using random variables.
Where I'm struggling (as notated above) is getting to the Accessorial node to count how many items are in its array. I was thinking I could parse the first array (starting with SCAC data) and extend down to the Accessorial node, but I'm not having any luck.
Any help is GREATLY appreciated, especially since I am new to this type of code and have spent the majority of the day trying to resolve this.
you can try this
var rates = (JArray)JObject.Parse(json)["RatingResponse"]["Rates"]["Rate"];
var costs = rates.Select(r => new
{
CarrierName = r["CarrierName"],
Costs = ((JArray)((JObject)r["Accessorials"])["Accessorial"])
.Where(r => (string)r["Description"] != "Discount")
.Select(r => (double)r["Cost"]).Sum()
}).ToList();
result
[
{
"CarrierName": "TEST1",
"Costs": 1984.59
},
{
"CarrierName": "TEST2",
"Costs": 1984.59
}
]

How to fix this Matchmaking Rule set for AWS Game Lift

I am new to Game Lift and am trying to make a ruleset for a Jeopardy game for a project I am creating. I try to apply what I want to do for the match making but I always seem to get this error and cannot figure out for the life of me what is wrong.
I am doing 3 players, each having near the same skill set so to keep it fair. Can someone explain what I am doing wrong?
I have already looked up all around the documentation of Game lift but I am still confused how this portion works. The examples they gave worked and I tried editing them to my own liking but it seems it did not work.
"name": "Normal_Game",
"ruleLanguageVersion": "1.0",
"playerAttributes": [{
"name": "skill",
"type": "number",
"default": 10
}],
"teams": [{
"name": "red",
"maxPlayers": 1,
"minPlayers": 1
}, {
"name": "blue",
"maxPlayers": 1,
"minPlayers": 1
},{
"name": "green",
"maxPlayers": 1,
"minPlayers":1
}],
"rules": [{
"name": "FairTeamSkill",
"description": "The average skill of players in each team is within 10 points from the average skill of all players in the match",
"type": "distance",
// get skill values for players in each team and average separately to produce list of two numbers
"measurements": [ "avg(teams[*].players.attributes[skill])" ],
// get skill values for players in each team, flatten into a single list, and average to produce an overall average
"referenceValue": "avg(flatten(teams[*].players.attributes[skill]))",
"maxDistance": 10 // minDistance would achieve the opposite result
}, {
"name": "EqualTeamSizes",
"description": "Only launch a game when the number of players in each team matches, e.g. 4v4, 5v5, 6v6, 7v7, 8v8",
"type": "comparison",
"measurements": [ "count(teams[red].players)" ],
"referenceValue": "count(teams[blue].players)",
"operation": "=" // other operations: !=, <, <=, >, >=
"referenceValue": "count(teams[green].players)",
"operation": "="
}],
"expansions": [{
"target": "rules[FairTeamSkill].maxDistance",
"steps": [{
"waitTimeSeconds": 5,
"value": 50
}, {
"waitTimeSeconds": 15,
"value": 100
}]
}]
}
I validate it all the time, expecting it to take it but it doesn't my error messages keep occurring as this:
Rule set*
Encountered JSON parsing error: Unexpected character ('"' (code 34)): was expecting comma to separate Object entries at [Source: { "name": "Normal_Game", "ruleLanguageVersion": "1.0", "playerAttributes": [{ "name": "skill", "type": "number", "default": 10 }], "teams": [{ "name": "red", "maxPlayers": 1, "minPlayers": 1 }, { "name": "blue", "maxPlayers": 1, "minPlayers": 1 },{ "name": "green", "maxPlayers": 1, "minPlayers":1 }], "rules": [{ "name": "FairTeamSkill", "description": "The average skill of players in each team is within 10 points from the average skill of all players in the match", "type": "distance", // get skill values for players in each team and average separately to produce list of two numbers "measurements": [ "avg(teams[*].players.attributes[skill])" ], // get skill values for players in each team, flatten into a single list, and average to produce an overall average "referenceValue": "avg(flatten(teams[*].players.attributes[skill]))", "maxDistance": 10 // minDistance would achieve the opposite result }, { "name": "EqualTeamSizes", "description": "Only launch a game when the number of players in each team matches, e.g. 4v4, 5v5, 6v6, 7v7, 8v8", "type": "comparison", "measurements": [ "count(teams[red].players)" ], "referenceValue": "count(teams[blue].players)", "operation": "=" // other operations: !=, <, <=, >, >= "referenceValue": "count(teams[green].players)", "operation": "=" }], "expansions": [{ "target": "rules[FairTeamSkill].maxDistance", "steps": [{ "waitTimeSeconds": 5, "value": 50 }, { "waitTimeSeconds": 15, "value": 100 }] }] }; line: 38, column: 10]
You seem to have these 2:
"referenceValue":
"operation":
defined twice in EqualTeamSizes rules, that might cause issues. And a missing comma after "operation": "="
{
"name": "EqualTeamSizes",
"description": "Only launch a game when the number of players in each team matches, e.g. 4v4, 5v5, 6v6, 7v7, 8v8",
"type": "comparison",
"measurements": [ "count(teams[red].players)" ],
"referenceValue": "count(teams[blue].players)",
"operation": "=" // other operations: !=, <, <=, >, >=
"referenceValue": "count(teams[green].players)",
"operation": "="
}

GeoJson data in R

I want to work on GeoJson data having below mentioned format;
{ "id": 1,
"geometry":
{ "type": "Point",
"coordinates": [
-3.706,
40.3],
"properties": {"appuserid": "5b46-7d3c-48a6-9c08-cc894",
"eventtype": "location",
"devicedate": "2016-06-08T07:25:21",
"date": "2016-06-08T07:25:06.507",
"location": {
"building": "2",
"floor": "0",
"elevation": ""
}}}
The problem is i want to use a "Where" clause to "appuserid" and select the selected records for processing. I dont know how to do it ? I have already saved data from a Mongodb in a dataframe.
Right now i am trying to do it as follow;
library(sqldf)
sqldf("SELECT * FROM d WHERE d$properties$appuserid = '0000-0000-0000-0000'")
But it gives an error.
Error: Only lists of raw vectors are currently supported
code is below;
library(jsonlite);
con <- mongo(collection = "geodata", db = "MongoDb", url = "mongodb://192.168.26.18:27017", verbose = FALSE, options = ssl_options());
d <- con$find();
library(jqr)
jq(d, '.features[] | select(d$properties$appuserid == "5b46-7d3c-48a6-9c08-cc894")')
Error : Error in jq.default(d, ".features[] | select(d$properties$appuserid == \"5b46-7d3c-48a6-9c08-cc894\")") :
jq method not implemented for data.frame.
jqr is one option, an R client for jq https://stedolan.github.io/jq/
x <- '{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"population": 200
},
"geometry": {
"type": "Point",
"coordinates": [
10.724029,
59.926807
],
"properties": {
"appuserid": "5b46-7d3c-48a6-9c08-cc894"
}
}
},
{
"type": "Feature",
"properties": {
"population": 600
},
"geometry": {
"type": "Point",
"coordinates": [
10.715789,
59.904778
],
"properties": {
"appuserid": "c7e866a7-e32d-4dc2-adfd-c2ca065b25ce"
}
}
}
]
}'
library(jqr)
jq(x, '.features[] | select(.geometry.properties.appuserid == "5b46-7d3c-48a6-9c08-cc894")')
returns
{
"type": "Feature",
"properties": {
"population": 200
},
"geometry": {
"type": "Point",
"coordinates": [
10.724029,
59.926807
],
"properties": {
"appuserid": "5b46-7d3c-48a6-9c08-cc894"
}
}
}

DocumentDB - How do I return the distance in the SELECT part of the query?

I would like to return the distance between my search co-ordinates and the field I'm searching for.
As an example, you can use this "Query Playground":
https://www.documentdb.com/sql/demo#geospatial
They use the following example query:
-- Find all volcanoes of type Stratovolcano
-- (http://www.sciencedaily.com/terms/stratovolcano.htm)
-- that are within 100 km of Redmond, WA.
SELECT *
FROM volcanoes v
WHERE ST_DISTANCE(v.Location, {
"type": "Point",
"coordinates": [-122.19, 47.36]
}) < 100 * 1000
AND v.Type = "Stratovolcano"
AND v["Last Known Eruption"] = "Last known eruption from 1800-1899, inclusive"
And they get the following results:
{
"Volcano Name": "Rainier",
"Country": "United States",
"Region": "US-Washington",
"Location": {
"type": "Point",
"coordinates": [
-121.758,
46.87
]
},
"Elevation": 4392,
"Type": "Stratovolcano",
"Status": "Dendrochronology",
"Last Known Eruption": "Last known eruption from 1800-1899, inclusive",
"id": "33eff74b-e331-bca5-bf32-f8ece733465a",
"_rid": "FX8tANMM6QEeBAAAAAAAAA==",
"_ts": 1438994836,
"_self": "dbs/FX8tAA==/colls/FX8tANMM6QE=/docs/FX8tANMM6QEeBAAAAAAAAA==/",
"_etag": "\"00008304-0000-0000-0000-55c551940000\"",
"_attachments": "attachments/"
}
Let's say that I want to bring the distance back in metres between the volcano (at [-121.758, 46.87]) and the search co-ordinates [-122.19, 47.36]
The T-SQL developer in me says I can just take the whole ST_DISTANCE bit from the WHERE clause, and include it along with the SELECT like this:
-- Find all volcanoes of type Stratovolcano
-- (http://www.sciencedaily.com/terms/stratovolcano.htm)
-- that are within 100 km of Redmond, WA.
SELECT *, ST_DISTANCE(v.Location, {
"type": "Point",
"coordinates": [-122.19, 47.36]
})
FROM volcanoes v
WHERE ST_DISTANCE(v.Location, {
"type": "Point",
"coordinates": [-122.19, 47.36]
}) < 100 * 1000
AND v.Type = "Stratovolcano"
AND v["Last Known Eruption"] = "Last known eruption from 1800-1899, inclusive"
However that doesn't work, it just gives me a syntax error:
{
"errors": [
{
"severity": "Error",
"location": {
"start": 153,
"end": 154
},
"code": "SC1001",
"message": "Syntax error, incorrect syntax near ','."
}
]
}
I've tried a range of things, like v.*, aliasing the result of ST_DISTANCE with an AS, but I'm not getting anywhere and I'm not finding what I need in Google.
So what do I need to do? For me, querying within a certain distance is crucial, but it's of limited use if I then have to re-calculate all those distances client-side.
The query must use SELECT v, ST_DISTANCE(...) in place of SELECT *, ST_DISTANCE(...). Similar to ANSI-SQL, a SELECT clause in DocumentDB can either include a list of values or use *, but not both at the same time.
Full query:
-- Find all volcanoes of type Stratovolcano
-- (http://www.sciencedaily.com/terms/stratovolcano.htm)
-- that are within 100 km of Redmond, WA.
SELECT v, ST_DISTANCE(v.Location, {
"type": "Point",
"coordinates": [-122.19, 47.36]
}) AS DistanceMetres
FROM volcanoes v
WHERE ST_DISTANCE(v.Location, {
"type": "Point",
"coordinates": [-122.19, 47.36]
}) < 100 * 1000
AND v.Type = "Stratovolcano"
AND v["Last Known Eruption"] = "Last known eruption from 1800-1899, inclusive"

Resources