I have a form that allows for several fields to search for records in a database. It's able to search by first name, last name, location, etc, but I'm having trouble adding date ranges to the query. Each record has a start year and an end year, and my form has fields Date To and From. My code checks if each form in the field is filled out, and if so appends to a query string; once the query string is complete, it is passed into a Connection.Post search. Everything works except for To and From, but when I add these fields I get a 404 error.
I have a QueryBuilder method that checks the fields and builds the query, here is how it starts:
string query = "{\"query\": { \"bool\": { \"must\": [ ";
bool emptyQ = true;
Here is the first_name part for example:
if (!String.IsNullOrWhiteSpace(q.Name.First))
{
if (exact == true)
{
query += "{ \"match\": { \"first_name\": \"" + q.Name.First + "\" }}";
}
else
{
// no fuzziness allowed in the search term; how can i fix this? (i.e. Sam -> Samuel, but Isac -\> Isaac)
query += "{ \"match_phrase_prefix\": { \"first_name\": \"" + q.Name.First + "\"}}";
}
emptyQ = false;
}
Here is the part that isn't working right:
bool aggs = false;
if (q.FromYear != 0 || q.ToYear != DateTime.Now.Year)
{
if (emptyQ == false)
{
query += "] } }, ";
}
if (emptyQ == true)
{
query += "{";
}
DateTime fromyear = Convert.ToDateTime("01/01/" + q.FromYear.ToString());
if (q.FromYear == 0)
{
fromyear = Convert.ToDateTime("00/00/0000" + q.FromYear.ToString());
}
DateTime toyear = Convert.ToDateTime("12/31/" + q.ToYear.ToString());
query += "\"aggregations\": { \"range\": { \"date_range\": { \"field\": \"start_date\", \"ranges\": [{\"from\": \"" + fromyear + "\"}]}}}";
query += "{\"range\": { \"date_range\": { \"field\": \"end_date\", \"ranges\": [{\"to\": \"" + toyear +
"\"}] }}}}";
aggs = true;
}
if (aggs == false)
{
query += " ] } } }";
}
i.e. when one or both of the date fields is filled out, the query is invalid. When every field is filled out, this is what the query builder returns:
{"query":
{ "bool":
{ "must": [
{ "match_phrase_prefix": { "first_name": "sam"}},
{ "fuzzy": { "last_name": "durand" }},
{ "match": { "record_type": { "query": "Baptism", "type": "phrase"} }},
{ "fuzzy_like_this":
{ "fields": [ "city", "region", "county", "country" ],
"like_text": "Massachusetts"
}
}
]}
},
"aggregations":
{ "range":
{ "date_range":
{ "field": "start_date",
"ranges": [{"from": "1/1/1600 12:00:00 AM"}]
}
}
},
{"range":
{ "date_range":
{ "field": "end_date",
"ranges": [{"to": "12/31/2014 12:00:00 AM"}]
}
}
}
}
Which gives me a 400 bad request error. Again, when the year fields are not filled out, it works just fine. I'm sure it's a problem with how I'm formatting my query, but I'm not sure what I'm doing wrong. Also, is there an easier way I can search for a date range without using aggregations? Is there a search method that I can put in the "query { " itself, rather than after it?
If you're trying to filter the results by a date range you don't want to use the date_range aggregation, you want to use the range filter. That would give you something more like:
{"query":
{ "bool":
{ "must": [
{
"range" : {
"start_date" : {
"gte": "1/1/1600 12:00:00 AM",
}
}
},
{
"range" : {
"end_date" : {
"lte": 12/31/2014 12:00:00 AM",
}
}
},
]}
}
Turns out I didn't have to do anything fancy at all, I just used a simple range:
query += "{ \"range\": { \"start_date.year\": { \"gte\": " + fyear + ", \"lte\": " + tyear + "} }}, " +
"{ \"range\": { \"end_date.year\": { \"gte\": " + fyear + ", \"lte\": " + tyear + "} }}] } } }, ";
My problem was in assuming that datetime objects would not be read correctly in a range query, but you can in fact use datetime objects in a range.
Related
In response, I get a big object with many data fields. I need a function that will be going through all properties of an object, and if it is a date, apply iml.parseDate(value) for this field. This function must be universal for other modules.
I've noticed that typeof(date) returns " string" so I don't know how to do this.
[
{
"id": 13965629,
"updated_at": "2020-07-10 02:01 PM +0300",
"created_at": "2020-07-10 02:01 PM +0300",
"creator": {
"name":"Jon Doe",
"registered": "2020-06-22 12:31 PM +0100",
}
}
]
You can interate through your objects or arrays and match the date using regexp.
E.g.
function convertDates(obj) {
Object.keys(obj).forEach(key => {
let val = obj[key];
if (Array.isArray(val)) {
val.forEach(convertDates);
}
else if (typeof val === 'object') {
return convertDates(val);
}
else if (/\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+(?:PM|AM)\s+\+\d{4}/.test(val)) {
obj[key] = parseDate(val);
}
});
return obj;
}
I'm having this request body for Google DLP as a text value. Is there any way to configure userdefined RedactConfig to modify the output..?. Is there any way to achieve that one..?
{
"item":{
"value":"My name is Alicia Abernathy, and my email address is aabernathy#example.com."
},
"deidentifyConfig":{
"infoTypeTransformations":{
"transformations":[
{
"infoTypes":[
{
"name":"EMAIL_ADDRESS"
}
],
"primitiveTransformation":{
"replaceWithInfoTypeConfig":{
}
}
}
]
}
},
"inspectConfig":{
"infoTypes":[
{
"name":"EMAIL_ADDRESS"
}
]
}
}
Is there any way to configure userdefined RedactConfig to modify the output..?
And I need the following O/P from Google DLP.
{
"item": {
"value": "My name is Alicia Abernathy, and my email address is {{__aabernathy#example.com__[EMAIL_ADDRESS]__}}."
},
"overview": {
"transformedBytes": "22",
"transformationSummaries": [
{
"infoType": {
"name": "EMAIL_ADDRESS"
},
"transformation": {
"replaceWithInfoTypeConfig": {}
},
"results": [
{
"count": "1",
"code": "SUCCESS"
}
],
"transformedBytes": "22"
}
]
}
}
So you don't actually want to anonymize text, you just want to add information to it? This API isn't suitable for that ... your best bet is to just use inspectContent and with the byte offsets in the findings do your own transforms.
Something like this in pseudocode ...
private static final void labelStringWithFindings(
String stringToLabel,
InspectContentResponse dlpResponse) {
StringBuilder output = new StringBuilder();
final byte[] messageBytes = ByteString.copyFromUtf8(
stringToLabel).toByteArray();
ImmutableList sortedFindings =
sort(dlpResponse.getResult().getFindingsList());
int lastEnd = 0;
for (Finding finding : sortedFindings) {
String quote = Ascii.toLowerCase(finding.getQuote());
String infoType = finding.getInfoType().getName();
String surrogate = String.format("{{__%s__[%s]__}}",
quote, infoType);
final byte[] surrogateBytes = surrogate.getBytes(StandardCharsets.UTF_8);
int startIndex = (int) finding.getLocation().getByteRange().getStart();
int endIndex = (int) finding.getLocation().getByteRange().getEnd();
if (lastEnd == 0 || startIndex > lastEnd) {
output.write(messageBytes, lastEnd, startIndex - lastEnd);
output.write(surrogateBytes, 0, surrogate.length);
}
if (endIndex > lastEnd) {
lastEnd = endIndex;
}
}
if (messageBytes.length > lastEnd) {
output.write(messageBytes, lastEnd, messageBytes.length - lastEnd);
}
return output.toString();
}
I'm trying to get the key values of the documents in my Firestore database, but I'm not getting it.
This value below:
This my code:
function objectsToArray(objects) {
var outputArray = [];
for (var i in objects){
outputArray.push([
objects[i].fields.id, objects[i].fields.data, objects[i].fields.acao,
objects[i].fields.categoria, objects[i].fields.movimentos, objects[i].fields.descricao
]);
}
return outputArray;
}
My output Logger.log of JSON:
[20-01-11 19:42:06:370 CET] [{"name":"projects/orcamento- b37bb/databases/(default)/documents/orcamento/0MwgqEm9abho3bpB5yCc","fields":
{"categoria":"SUPERMERCADO","data":"2019-07- 31T00:00:00.000Z","descricao":"","acao":"Despesa","movimentos":23.82,"id":107},
"createTime":"2019-12-31T14:35:47.959299Z","updateTime":"2019-12- 31T14:35:47.959299Z"},
any suggestions?
Thanks
The original data seems to be structured like this:
[
{
"name":"projects/orcamento- b37bb/databases/(default)/documents/orcamento/0MwgqEm9abho3bpB5yCc",
"fields": {
"categoria":"SUPERMERCADO",
"data":"2019-07- 31T00:00:00.000Z",
"descricao":"",
"acao":"Despesa",
"movimentos":23.82,
"id":107
},
"createTime":"2019-12-31T14:35:47.959299Z",
"updateTime":"2019-12- 31T14:35:47.959299Z"
},
You want the value: 0MwgqEm9abho3bpB5yCc
Which is in the element with the name property key.
function objectsToArray(objects) {
var L,nameValue,finalValue;
objects = [
{
"name":"projects/orcamento- b37bb/databases/(default)/documents/orcamento/0MwgqEm9abho3bpB5yCc",
"fields": {
"categoria":"SUPERMERCADO",
"data":"2019-07- 31T00:00:00.000Z",
"descricao":"",
"acao":"Despesa",
"movimentos":23.82,
"id":107
},
"createTime":"2019-12-31T14:35:47.959299Z",
"updateTime":"2019-12- 31T14:35:47.959299Z"
},
]
var outputArray = [];
L = objects.length;
for (var i=0;i<L;i++){
nameValue = objects[i].name;
Logger.log('nameValue: ' + nameValue)
finalValue = nameValue.slice(nameValue.lastIndexOf("/")+1);
Logger.log('finalValue: ' + finalValue)
outputArray.push(finalValue);
}
Logger.log('outputArray: ' + JSON.stringify(outputArray))
return outputArray;
}
I would like to turn this resultset
[
{
"Document": {
"JsonData": "{\"key\":\"value1\"}"
}
},
{
"Document": {
"JsonData": "{\"key\":\"value2\"}"
}
}
]
into this
[
{
"key": "value1"
},
{
"key": "value2"
}
]
I can get close by using a query like
select value c.Document.JsonData from c
however, I end up with
[
"{\"key\":\"value1\"}",
"{\"key\":\"value2\"}"
]
How can I cast each value to an individual JSON fragment using the SQL API?
As David Makogon said above, we need to transform such data within our app. We can do as below:
string data = "[{\"key\":\"value1\"},{\"key\":\"value2\"}]";
List<Object> t = JsonConvert.DeserializeObject<List<Object>>(data);
string jsonData = JsonConvert.SerializeObject(t);
Screenshot of result:
A third party API is returning JSON in the following format
{
"group1": {
"Colour": "Blue",
"Name": "Dave"
},
"group2": {
"Colour": "Red",
"Name": "Karen"
},
"group3": {
"Colour": "Green",
"Name": "Ryan"
}
}
I'm finding the outer 'groupX' identifier to problematic when attempting to deserialize the JSON using JSON.NET.
Does anyone know best to parse JSON in this format?
{
"employees": [
{ "first-name":"John" , "last-name":"Doe" },
{ "first-name":"Anna" , "last-name":"Smith" },
{ "first-name":"Peter" , "last-name":"Jones" }
]
}
Your JSON is Correct.
if tou want to check than use below url JSONlint
Define a class Group like this:
class Group
{
public string Colour { get; set; }
public string Name { get; set; }
}
Then you can deserialize like this:
var dict = JsonConvert.DeserializeObject<Dictionary<string, Group>>(json);
Here's a quick demo:
string json = #"
{
""group1"": {
""Colour"": ""Blue"",
""Name"": ""Dave""
},
""group2"": {
""Colour"": ""Red"",
""Name"": ""Karen""
},
""group3"": {
""Colour"": ""Green"",
""Name"": ""Ryan""
}
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, Group>>(json);
foreach (var kvp in dict)
{
Console.WriteLine(kvp.Key);
Group group = kvp.Value;
Console.WriteLine(" Colour: " + group.Colour);
Console.WriteLine(" Name: " + group.Name);
}
Output:
group1
Colour: Blue
Name: Dave
group2
Colour: Red
Name: Karen
group3
Colour: Green
Name: Ryan