Elasticsearch in lumen giving empty Items in Resulted Data - php

I am working with Elasticsearch in lumen for simple search.
I followed Elastic search installation tutorial from : https://medium.com/#basemkhirat_88244/laravel-lumen-flexible-elasticsearch-query-builder-inspired-from-eloquent-bb5221c65af8
And In my controller.php
public function search() {
$users = \Basemkhirat\Elasticsearch\Facades\ES::index('user_index')->type("text")->body([
"query" => [
"bool" => [
"must" => [
[ "match" => [ "name" => "Leena Patel" ] ],
]
]
]
])->get();
dd($users);
}
And in my routes.php file
$app->get('/search', 'Controller#search');
My es.php configuration file :
return [
'default' => env('ELASTIC_CONNECTION', 'default'),
'connections' => [
'default' => [
'servers' => [
[
"host" => env("ELASTIC_HOST", "127.0.0.1"),
"port" => env("ELASTIC_PORT", 9200),
'user' => env('ELASTIC_USER', ''),
'pass' => env('ELASTIC_PASS', ''),
'scheme' => env('ELASTIC_SCHEME', 'http'),
]
],
'index' => env('ELASTIC_INDEX', 'user_index'),
// Elasticsearch handlers
// 'handler' => new MyCustomHandler(),
]
],
'indices' => [
'user_index' => [
"aliases" => [
"user_index_alias"
],
'settings' => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
],
'mappings' => [
'users_schema' => [
"properties" => [
'name' => [
'type' => 'text'
]
]
]
]
]
]
];
When running /search link in browser it shows result array like
Basemkhirat\Elasticsearch\Collection Object
(
[items:protected] => Array
(
)
[total] => 0
[max_score] =>
[took] => 1
[timed_out] =>
[scroll_id] =>
[shards] => stdClass Object
(
[total] => 1
[successful] => 1
[skipped] => 0
[failed] => 0
)
)
My Question is Why My Items array is empty even though there is data with name = Leena Patel ?
Please help! I am learning ElasticSearch!
Edit :
My Database table users that contains column name with data Leena Patel SO i want this record in my items result

Please use below link for elastic search
https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/
then follow below steps for lumen
1) Move config directory to root alongside with app folder
vendor\elasticquent\elasticquent\src\config
2) Remove comment from `$app->withEloquent();` in bootstrap\app.php of lumen folder
3) Register elasticquent in app.php file of lumen folder as below
$app->configure('elasticquent');
4) Run command in your lumen folder
composer dump-autoload
After these steps you need to set route in web.php of lumen folder
for i.e.
use App\Article; // Use at top of web.php
$router->get('article', function() {
Article::createIndex($shards = null, $replicas = null); // Using this code create command
Article::reindex(); // Reindex article indices
$articles = Article::searchByQuery(['match' => ['title' => 'Android']]);
return $articles;
});

Related

How can I return properly an array value in blade laravel view

I am using a Database tables component for Laravel, however I want to do a check within the blade view, but can't seem to figure out the best approach for that. Since the array is created in the view and not in the controller.
I have an array and an object value. And if that object value is true it should present an extra line within the array.
What I have is the following:
"title" => "view_template"
What I want to produce is the following
[
'sometitle1' => 'someview1',
'sometitle2' => 'someview2', //this part needs if statement is true
'sometitle3' => 'someview3'
]
I am thinking of something like this
[
'sometitle1' => 'someview1',
($obj->has_this_field) ? ['sometitle2' => 'someview2']:
'sometitle3' => 'someview3'
]
But it doesn't do that obviously. I normally solve this with array_push in the controller. What would be the best approach since this is in a blade view.
I also tried this
[
'sometitle1' => 'someview1',
($obj->has_this_field) ? ['sometitle2' => 'someview2']:
'sometitle3' => 'someview3'
]
And this will obviously not work
[
'sometitle1' => 'someview1',
($obj->has_this_field) ? 'sometitle2' => 'someview2':
'sometitle3' => 'someview3'
]
#include('partials.panel', [
'header' => trans('general.information'),
'partial' => 'partials.show-tabs',
'partialData' => [
'root' => 'equipment.equipment.panels',
'tabs' => [
'general' => 'general',
'advanced' => 'maintenance',
(!$equipment->has_running_hours) ? ['runninghours' => 'runninghours']:
'history' => 'history',
]
]
])
This is what I want to produce
[
'general' => 'general',
'runninghours' => 'runninghours',
'history' => 'history'
]
Why you don't make an array first with #php //your Logic #endphp then pass that array to your #include part
Something like below.
#php
$array = [
'header' => trans('general.information'),
'partial' => 'partials.show-tabs',
'partialData' => [
'root' => 'equipment.equipment.panels',
'tabs' => [
'general' => 'general',
'advanced' => 'maintenance',
]
]
];
if(!$equipment->has_running_hours)
{
$array['partialData']['tabs']['runninghours'] = 'runninghours';
}
else
{
$array['partialData']['tabs']['history'] = 'history';
}
#endphp
Now pass this to your #include
#include('partials.panel',$array)

Getting data as array instead of stdClass in zf-rest

I'm using zf-rest for building my RESTful web apps. I have the following configurations:
'zf-rest' => [
Resource\FeedbackResource::class => [
'listener' => Resource\FeedbackResource::class,
'route_name' => 'api/rest/feedback',
'entity_http_methods' => [
],
'collection_http_methods' => [
'POST',
],
],
],
'zf-content-validation' => [
Resource\FeedbackResource::class => [
'use_raw_data' => false,
'allows_only_fields_in_filter' => true,
'POST' => Resource\FeedbackResource::class . '\\Validator',
],
],
'input_filter_specs' => [
Resource\FeedbackResource::class . '\\Validator' => [
Resource\FeedbackResource::PARAM_NAME => $inputFilterSpecForStrings,
Resource\FeedbackResource::PARAM_EMAIL => $inputFilterSpecForStrings,
],
],
Then I created the resource with the corresponding method:
class FeedbackResource extends AbstractResourceListener
{
public function create($data)
{
// do something
}
}
I posted a json string to the endpoint and everything works fine so far. But what I'm wondering about is that I will get $data as an object with the json data as attributes. I expected to get an assoziative array. Is this possible?

Create Associative Array with Foreach, Insert into existing Associative Array

Hello.
I currently have a problem with the AWS Route-53 API. To create a record you need to call a function, which itself needs an array of inputs.
I want to create a record set here and for that I have some POST values. One of them, $_POST['record_value'], is a textarea and has multiple lines. I loop through them. This is to enable multiple values for one record. The code is as follows when you hardcode it as one value in ResourceRecords;
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
[
'Value' => $recordValue
],
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
Hower. I want to make ResourceRecords dynamically. For every line in the textarea I need a new set of the following part of the code;
[
'Value' => $recordValue
],
What I thought is the following;
$newData = [];
foreach(explode("\r\n", $recordValue) as $valLine) {
$newData[] = ["Value" => $valLine];
}
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
$newData
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
However, this seems to return an exception: Found 1 error while validating the input provided for the ChangeResourceRecordSets operation:↵[ChangeBatch][Changes][0][ResourceRecordSet][ResourceRecords][0] must be an associative array. Found array(1).
Am I building the array wrong or am I doing this wrong alltogether?
$newData is already an array, you don't need to wrap it in another array.
'ResourceRecords' => $newData,

Elasticsearch Unable to print array in PHP

I followed this Video as a guide to get elasticsearch up and running with PHP, but I am unable to print or view the results. I can print the raw data, but i'm unable to go any deeper.
Operating system: Debian (jessie)
PHP version: 5.6.30
Java version: 1.7.0
Elasticsearch version: 5.4.0
I use this code to request the data:
// Creating the request.
if(!defined('JSON_PRESERVE_ZERO_FRACTION'))
{
define('JSON_PRESERVE_ZERO_FRACTION', 1024);
}
require_once('vendor/autoload.php'); // autoload which makes it "easier"
// to get values from elasticsearch
$hosts = [
"192.168.1.120:9200"
];
$client = Elasticsearch\ClientBuilder::create()
->setHosts($hosts)
->build();
// Define the search
$query = ([
'index' => '*',
'type' => '*',
'body' => [
'from' => 0,
'size' => 40,
'query' => [
'query_string' => [
'query' => 'a'
]
]
]
]);
$raw = $client->search($query);
print_r($raw);
This print_r($raw); returns this:
Array ( [took] => 2 [timed_out] => [_shards] => Array ( [total] => 30 [successful] => 30 [failed] => 0 ) [hits] => Array ( [total] => 0 [max_score] => [hits] => Array ( ) ) )
I know that by doing print_r, it should show all arrays inside eachother. So I don't understand what I'm doing wrong here? I know it should be displaying because I did the same thing in program called POSTMAN, and got back 40 results. I also tried another PHP version. PHP7, but it returned the same thing.
What am I doing wrong here?
It seems like it didn't like that I put * as index and type. So to either remove them, or change them to a working index,type will fix the problem.
For anyone else having this problem, this is the basic fix:
$query = [
'body' => [
'query' => [
'match' => [
'title' => 'Your search'
]
]
]
];
or
$query = [
'index' => 'your valid index',
'type' => 'your valid type',
'body' => [
'query' => [
'match' => [
'title' => 'Your search'
]
]
]
];

Can't update map column of DynamoDB table

I am currently developing a skill for Amazon's echo dot which requires the use of persistent data. I ran into an issue when developing a web interface for my skill where I was not able to easily update the mapAttr column of the DynamoDB table used by the skill.
I've been trying to work this out for the last 2 days, I've looked everywhere including the documentation but can't seem to find anything that'll help me.
This is the code I am using:
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#attr' => 'mapAttr.ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => json_encode($value)
],
'UpdateExpression' => 'SET #attr = :val1'
]);
I have tried many different things so this might be just absolutely wrong, but nothing that I have found has worked.
The table has 2 columns, userId and mapAttr, userId is a string and mapAttr is a map. Originally I thought it was simply a JSON string but it was not like that as when I tried to update it with a JSON string directly it would stop working when read by Alexa.
I am only trying to update 1 out of the 2 attributes of mapAttr. That is ReminderJSON which is a string.
Any help would be appreciated. Thanks.
Try calling updateItem like this
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr',
'#attr' => 'ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => ['S' => json_encode($value)]
],
'UpdateExpression' => 'SET #mapAttr.#attr = :val1'
]);
However, please be aware that in order for this to work, attribute mapAttr must already exist. If it doesn't, you'll get ValidationException saying The document path provided in the update expression is invalid for update...
As a workaround, you may want to add a ConditionExpression => 'attribute_exists(mapAttr)' to your params, catch possible exception, and then perform another update adding a new attribute mapAttr:
try {
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr'
'#attr' => 'ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => ['S' => json_encode($value)]
],
'UpdateExpression' => 'SET #mapAttr.#attr = :val1'
'ConditionExpression' => 'attribute_exists(#mapAttr)'
]);
} catch (\Aws\Exception\AwsException $e) {
if ($e->getAwsErrorCode() == "ConditionalCheckFailedException") {
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr'
],
'ExpressionAttributeValues' => [
':mapValue' => ['M' => ['ReminderJSON' => ['S' => json_encode($value)]]]
],
'UpdateExpression' => 'SET #mapAttr = :mapValue'
'ConditionExpression' => 'attribute_not_exists(#mapAttr)'
]);
}
}

Categories