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'
]
]
]
];
Related
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)
I'm having a bit of an issue with an API document I'm currently working with. The code I've been testing just doesn't seem to work, and I've been looking at it for that long now, I just cannot see where I'm going wrong.
API Documentation Screenshot here: https://ibb.co/CW4HRR9
// POST /package/{id}/web/ftpusers
$args = [
'update' => [
'ftp' => [
'id' => '12345',
'user' => ['Password' => 'Password123']
],
],
];
$response = $services_api->postWithFields("/package/".$test_domain_id."/web/ftpusers", $args);
echo '<pre>';
print_r($response);
echo '</pre>';
It just doesn't seem to work, and I'm guessing I'm doing something wrong where it states object and object[]
Looks like I was missing an array object as I've now got this working (extra array within 'ftp'
$args = [
'update'=> [
'ftp' => [
[
'id' => $info[0]->Id,
'user' => [
'Enabled' => true,
'Password' => 'Password123'
],
]
],
],
];
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;
});
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)'
]);
}
}
Consider this PHP array for defining a search query on elasticsearch
$searchParams = [
'index' => $index_name,
'type' => 'nginx-access',
'size' => 1000,
'sort' => ['_score'],
'fields' => ["remote_addr", "#timestamp", "request", "method", "status"],
'body' => [
// 'min_score' => 4,
'query' => [
'bool' => [
'must' => [
['match' => ['status' => '200']],
['match' => ['method' => 'POST']],
['match' => ['request' => '/wp-login.php']],
],
]
]
]
];
$results = $this->client->search($searchParams);
var_dump($results);
Notice that 'min_score' is commented out. The array of results returns everything as expected, however I only want results that match all of the criteria. I thought this is what query->bool->must is supposed to do, however near the end of the dataset I am getting matches for other seemingly random things as well.
If I run it with min_score then I'm always going to get the results I want, but this does not seem the right way to do it.
Am I missing something obvious here?