How to push items into array in php - php

I am using Laravel with ES and trying to build a dynamic query.
But the following doesnt work:
$query[] = ['term' => ['city' => 1]];
$query[] = ['term' => ['state' => 2]];
$query[] = ['range' => ['price' => ['lte' => 2]]];
$asd = ['filtered' => [
'query' => [
'match' => ['title' => Input::get('query')]
],
'filter'=> [
'bool' => [
'must' => [
['term' => [ 'is_active' => 1] ],
[ 'range' => [
'end_date' => [
'from' => 'now'
]
]
],
$query
]
]
],
],];
echo json_encode($asd);
This will append $query[] wrong into $asd, like:
{"term":{"is_active":1}},
{"range":{"end_date":{"from":"now"}}},
[
{"term":{"city":1}},
{"term":{"state":2}},
{"range":{"price":{"lte":2}}}
]
How I would like to append it is:
{"term":{"is_active":1}},
{"range":{"end_date":{"from":"now"}}},
{"term":{"city":1}},
{"term":{"state":2}},
{"range":{"price":{"lte":2}}}
without the [] around it.
Solved:
$asd = ['filtered' => [
'query' => [
'match' => ['title' => Input::get('query')]
],
'filter'=> [
'bool' => [
'must' =>
$query
]
],
],];

A valid json string always consist of a single object or an array of objects.
The string you are asking for is not legal json, it would not be possible to parse.
Json with a single object looks like this:
{ // Object start.
"property": "value" // Where value could be a object or array or whatever.
} // Object end.
And if an array:
[ // Array start.
"Array value" // which could be an object or another array or whatever.
] // Array end.
When you convert your PHP array containing associative arrays, it will be converted into a string containing a array of objects.
You could always remove the [] from the string if you wish it to look like you described, but it will not be valid json.
Edit:
An elastic query looks basically like this:
{
"query": {
"term": { data ... }
}
}
I'm guessing that what you want/need to do is to create the php array like this:
$query = [
'query' => [
'term' => [
'state' => 2
'city' => 1
],
'range' => [
'price' => [
'lte' => 2
]
]
]
]
Which would result in a JSON string that looks like this:
{
"query":
{
"term":
{
"state": 2,
"city": 1
},
"range":
{
"lte": 2
}
}
}

Related

How to get value of filtered spreadsheets using google sheets api?

i need to showing data from sheet based on user keyword.
i try using setBasicFilter to filter data.
Here example requestbody.
$query = [
'requests' => [
[
'setBasicFilter' => [
'filter' => [
'range' => [
'sheetId' => 0,
'startColumnIndex' => 0,
'endColumnIndex' => 14,
'startRowIndex' => 0
],
'sortSpecs' => [
[
'dimensionIndex' => 0,
'sortOrder' => 'DESCENDING'
],
[
'dimensionIndex' => 2,
'sortOrder' => 'ASCENDING'
]
],
'filterSpecs' => [
[
'columnIndex' => 2,
'filterCriteria' => [
'condition' => [
'type' => 'TEXT_CONTAINS',
'values' => [
[
'userEnteredValue' => 'input'
]
]
]
]
]
]
]
]
]
]
];
but, its only change view data on the spreadsheets, and response only return empty.
Do you have a solution for this problem?
I got the solution after seeing this issue Google Sheets API, Read Values by Filter
you can use foreach() than use if() to get data that you need to filter.
example :
foreach ($data['values'] as $key => $value) {
if($value[2] === 'input') {
// $key . $value
}
}

Merge indexed arrays from POST request

I have this array coming from post request:
$x = [
"meal" => [
"monday" => [
"breakfast" => [
0 => "type1",
1 => "type1",
],
"afternoonTea" => [
0 => "type2",
],
],
],
"number" => [
"monday" => [
"breakfast" => [
0 => "10",
1 => "9",
],
"afternoonTea" => [
0 => "1",
],
],
],
];
I am trying to merge all this into one array without using tones of foreaches.
Maybe someone more clever will know how to use iterators to achieve that.
Data from meal and number is always 1:1.
I need to convert this to something like this:
$x = [
"monday" => [
"breakfast" => [
[
'type' => "type1",
'number' => 10,
],
[
'type' => "type1",
'number' => 9
]
],
"afternoonTea" => [
[
'type' => "type2",
'number' => 1,
],
],
],
],
];
If you count 3 as being tonnes then this isn't your answer - but I can't see a way of reducing down the number of reach loops below this without getting to a game of code golf which won't be helpful.
Because you know there is a 1:1 relationship between meal and number, you can use the indexes from one to get data from the other by doing:
$result = [];
foreach($x['meal'] as $day => $list) {
foreach($list as $activity => $types) {
foreach($types as $i => $type) {
$result[$day][$activity][] = [
'type' => $type,
'value' => $x['number'][$day][$activity][$i],
];
}
}
}
The output of this will be $result will contain the array in the format you want.

ElasticSearch Delete by query not working in PHP

I am using Elastic search 5.x and the following code is working fine:
curl -XPOST "http://localhost:9200/test_index/test_info/_delete_by_query" -d'
{
"query": {
"match": {
"category_id": "21"
}
}
}'
But when I am trying the same in my php code, its not working:
$client->deleteByQuery([
'index' => 'test_index',
'type' => 'test_info',
'query' => [
'match' => [
['category_id' => 21]
]
]
]);
You need to provide your query array inside body array of your parameters:
$client->deleteByQuery([
'index' => 'test_index',
'type' => 'test_info',
'body' => [
'query' => [
'match' => [
['category_id' => 21]
]
]
]
]);
this an old question, previous comments don't work anymore in 2020 :
$client->deleteByQuery([
'index' => 'test_index',
(there were a type here) 'type' => 'test_info',
'body' => [
'query' => [
'match' => [
(there were an array here) ['category_id' => 21]
]
]
]
]);
So the final code is :
$client->deleteByQuery([
'index' => 'test_index',
'body' => [
'query' => [
'match' => [
'category_id' => 21
]
]
]

Converting MongoDB query using aggregate to PHP driver aggregate query

I have the following query working in mongoDB but its not working in PHP.
MongoDB Query
db.energy_meter.aggregate(
{
$unwind: {
path:"$KeyValues",
includeArrayIndex:"arrayIndex",
preserveNullAndEmptyArrays:true
}
},
{
$project: {
timestamp:{
"$add":["$EventTS",{"$multiply":[60000,"$arrayIndex"]}]
} ,
"RPhaseVoltage":"$KeyValues.RPhaseVoltage",
arrayIndex:1,
}
}
);
Above query is converted to PHP
$cursor = DB::collection('energy_meter')->raw(function($collection)
{
return $collection->aggregate([
[
'$unwind' =>
['path' => '$KeyValues'],
['includeArrayIndex' => 'arrayIndex'],
['preserveNullAndEmptyArrays' => 'true']
],
[
'$project' =>
[
'timestamp' => [
'$add' => [
'$EventTS',
['$multiply' => [60000, '$arrayIndex']]
]
]
],
[
'MainsInputVoltagev' => ['$KeyValues.MainsInputVoltagev']
],
[
'arrayIndex' => 1
]
]
]);
});
I am getting following error
RuntimeException in Aggregate.php line 168: A pipeline stage specification object must contain exactly one field.
What is problem in my converted php query? Please suggest resolution of above problem.
You should always convert normal query to array decode. json_decode should make query for PHP driver and json_encode should give query mongodb query parameters.
(
{
$unwind: {
path:"$KeyValues",
includeArrayIndex:"arrayIndex",
preserveNullAndEmptyArrays:true
}
},
{
$project: {
timestamp:{
"$add":["$EventTS",{"$multiply":[60000,"$arrayIndex"]}]
} ,
"RPhaseVoltage":"$KeyValues.RPhaseVoltage",
arrayIndex:1,
}
}
)
Like this :
array(
array(
'$unwind' => array(
'path' => '$KeyValues',
'includeArrayIndex' =>"arrayIndex",
'preserveNullAndEmptyArrays'=> true
)
),
array(
'$project' => array(
'timestamp' => array(
'$add'=>[ '$EventTS',array('$multiply'=>[60000,'$arrayIndex'])]
) ,
"RPhaseVoltage" => '$KeyValues.RPhaseVoltage',
'arrayIndex' =>1,
)
)
)
If you have at least PHP5.4, you can use simpler array syntax. Replace array( with [ and ) with ] for array.
[
[
'$unwind' => [
'path' => '$KeyValues',
'includeArrayIndex' => 'arrayIndex',
'preserveNullAndEmptyArrays' => 'true'
]
],
[
'$project' => [
'timestamp' => [
'$add' => [
'$EventTS',
[ '$multiply' => [60000, '$arrayIndex'] ]
]
],
'MainsInputVoltagev' => '$KeyValues.MainsInputVoltagev',
'arrayIndex' => 1
]
]
]

Elastic Search PHP Client Date Range Query

I have this code what executes an query.
I am using the official php elastic search library.
https://github.com/elastic/elasticsearch-php
The field "Tijdsperiode" is in this format : ( 2016-01-30 00:00:00 ) ( YY-MM-DD HH:MM:SS )
$params = [
'index' => 'veenendaal2',
'type' => 'passanten2',
'body' => [
'query' => [
'match_all' => [],
'filter' => [
'range' => [
'Tijdsperiode' => [
'gte' => '2016-01-30 01:00:00',
'lte' => '2016-01-30 08:00:00'
]
]
]
],
],
];
$response = $client->search($params);
var_dump($response);
I just wonder what the format need to be to get results between the 2 dates.
When i do this :
$params = [
'index' => 'veenendaal2',
'type' => 'passanten2',
'body' => [
'query' => [
'match_all' => [],
],
],
];
It's working fine but i need the results between the 2 dates!
I also tried this but with no result :
$json = '{
"query": {
"bool": {
"must": [
{
"range": {
"Tijdsperiode": {
"gt": "2016-01-30 07:00:00",
"lt": "2016-01-30 09:00:00"
}
}
}
]
}
}
}';
$client = ckan_graphmapper_client();
$params = [
'index' => 'veenendaal2',
'type' => 'passanten2',
'body' => $json
];
$response = $client->search($params);
I also tried it with a mapping :
$params = [
'index' => 'veenendaal2',
'type' => 'passanten2',
'size' => $size,
'body' => [
'query' => [
"match_all" => [],
'filter' => [
'range' => [
'Tijdsperiode' => [
'gte' => '2016-01-30 01:00:00',
'lte' => '2016-01-30 08:00:00'
]
]
]
],
'mappings' => [
'_default_' => [
'properties' => [
'Tijdsperiode' => [
'type' => 'date',
'format' => 'yyyy-MM-dd HH:mm:ss'
]
]
]
]
]
];
How to do the right syntax for choosing between 2 dates?. Both string formats ( 2016-01-30 00:00:00 ) ( YY-MM-DD HH:MM:SS )
Thanks!
So it turns out my import of data was not mapping the correct way.
The date field was recognised as a string value.
When i finnaly had the correct mapping in elastic i could do this query :
$query = [
'query' => [
'filtered' => [
'query' => [
'match_all' => []
],
'filter' => [
'range' => [
'Tijdsperiode' => [
'gte' => $start,
'lte' => $end
]
]
]
]
]
];

Categories