highlighting elastic search results using elastic search-php - php

I am trying to highlight my results in elastic search-php , I tried a lot with my knowledge and searching in google, but no luck , the same query is working perfectly in Sense. my query in Sense is
GET /bank/account/_search
{
"query" : {
"match_phrase" : {
"address" : "mill"
}
},
"highlight": {
"pre_tags" : ["<tag1>"],
"post_tags" : ["</tag1>"],
"fields" : {
"address" : {}
}
}
}
with above query i get exact result what i needed, this is the result i got
highlight": {
"address": [
"990 <tag1>Mill</tag1> Road"
]
}
i tried the same query using php i am not get the highlighted results my php query is
<?php
require 'vendor/autoload.php';
$client=new Elasticsearch\Client();
$indexParams = [
'index' => 'bank',
'type' => 'account',
'body' => [
'query' => [
'match' => [
"address" => "mill"
],
],
'highlight' => [
"pre_tags" => "<tag1>",
"post_tags" => "</tag1>",
'fields' => [
'address' => new \stdClass()
]
],
]
];
$results = $client->search($indexParams);
try {
$response = $client->search($indexParams);
} catch (Exception $e) {
var_dump($e->getMessage());
}
echo '<pre>',print_r($response),'</pre>';
?>
the result i aam getting is
[highlight] => Array
(
[address] => Array
(
[0] => 715 Mill Avenue
)
)

i got the answer for above question, i am sending parameters in the form of json and JSON encode the result, when i encode the result in JSON at that pre tags are came in highlight query.
my solution is
"highlight": {
"address": [
"817 Campus </span>Road</span>"
]
}

Related

Trying to add contacts via ActiveCampain API (Laravel)

I´m trying to integrate the RESTFUL API of ActiveCampaing to my Laravel environment, but I haven’t been so luckier, I'm using GuzzleHttp to make the requests, this is the error image and my code:
$client = new \GuzzleHttp\Client([‘base_uri’ => ‘https://myaccount.api-us1.com/api/3/’]);
$response = $client->request('POST', 'contacts', [
'headers' => [
'Api-Token' => 'xxx',
'api_action' => 'contact_add',
],
'json' => [
'email' => 'test2021#test.com',
'first_name' => 'Julian',
'last_name' => 'Carax',
]
]);
echo $response->getStatusCode(); // 200
echo $response->getBody();
Hope you could help me! :D
you are not sending the data in correct format,
from the docs https://developers.activecampaign.com/reference#contact
{
"contact": {
"email": "johndoe#example.com",
"firstName": "John",
"lastName": "Doe",
"phone": "7223224241",
"fieldValues":[
{
"field":"1",
"value":"The Value for First Field"
},
{
"field":"6",
"value":"2008-01-20"
}
]
}
}
So create an array with key contact.
$contact["contact"] = [
"email" => "johndoe#example.com",
"firstName" => "John",
"lastName" => "Doe",
"phone" => "7223224241",
"fieldValues" => [
[
"field"=>"1",
"value"=>"The Value for First Field"
],
[
"field"=>"6",
"value"=>"2008-01-20"
]
]
];
Use try catch blocks as then you can catch your errors
try{
$client = new \GuzzleHttp\Client(["base_uri" => "https://myaccount.api-us1.com/api/3/"]);
$response = $client->request('POST', 'contacts', [
'headers' => [
'Api-Token' => 'xxx',
'api_action' => 'contact_add',
],
'json' => $contact
]);
if($response->getStatusCode() == "200" || $response->getStatusCode() == "201"){
$arrResponse = json_decode($response->getBody(),true);
}
} catch(\GuzzleHttp\Exception\ClientException $e){
$error['error'] = $e->getMessage();
if ($e->hasResponse()){
$error['response'] = $e->getResponse()->getBody()->getContents();
}
// logging the request
\Illuminate\Support\Facades\Log::error("Guzzle Exception :: ", $error);
// take other actions
} catch(Exception $e){
return response()->json(
['message' => $e->getMessage()],
method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500);
}
You can check at the API docs that the fields email, first_name, last_name are under a contact node.
So make a contact array, put these fields inside and you should be fine.
The fields for first and last name are written line firstName and lastName - camelCase, not snake_case like you did.
Official php client
You should probably use the official ActiveCampaign php api client - that would make your life easier.

use query_string and range in elasticsearch php client [query_string] malformed query, expected [END_OBJECT] but found [FIELD_NAME]

i use below code and get below error
for connect php to elasticsearch i use elasticsearch php client
$params = [
'index'=>'index1,index2',
'from'=>$startfrom,
'size'=>$maxperpage,
'sort' => array('id:desc'),
'body' => [
'query' => [
'query_string' => [
'query' => "\"$search_text\""
]
]
],
];
if($limit_time['start']){
$params['body']['query']['range']['date_insert']['gte']=$limit_time['start'];
}
if($limit_time['end']){
$params['body']['query']['range']['date_insert']['lte']=$limit_time['end'];
}
error :
{"error":{"root_cause":[{"type":"parsing_exception","reason":"[query_string] malformed query, expected [END_OBJECT] but found [FIELD_NAME]","line":1,"col":104}],"type":"parsing_exception","reason":"[query_string] malformed query, expected [END_OBJECT] but found [FIELD_NAME]","line":1,"col":104},"status":400}
You should try something like this instead. The query_string and the range queries need to be combined into a bool/filter query:
$params = [
'index'=>'index1,index2',
'from'=>$startfrom,
'size'=>$maxperpage,
'sort' => array('id:desc'),
'body' => [
'query' => [
'bool' => [
'filter' => [
[
'query_string' => [
'query' => "\"$search_text\""
]
]
]
]
]
],
];
$range = ['range' => ['date_insert' => []]]
if($limit_time['start']){
$range['range']['date_insert']['gte'] = $limit_time['start'];
}
if($limit_time['end']){
$range['range']['date_insert']['lte'] = $limit_time['end'];
}
$params['body']['query']['bool']['filter'][] = $range;
i solved problem
but thanks a lot "Val" for your help
i use below code :
$params = [
'index'=>'index1,index2',
'from'=>$startfrom,
'size'=>$maxperpage,
'sort' => array('id:desc')
];
if($search_text){
$params['body']['query']['bool']['must'][0]['match_phrase']['src']=$search_text;
}
if($use_time_status){
if($limit_time['start']){
$params['body']['query']['bool']['must'][1]['range']['date_insert']['gte']=$limit_time['start'];
}
if($limit_time['end']){
$params['body']['query']['bool']['must'][1]['range']['date_insert']['lte']=$limit_time['end'];
}
}

How to create this JSON in PHP?

Sorry for the bad title, but I don't know how to create following JSON in PHP:
{
"id":"1",
"method":"getData",
"params":{
"options":{
"element":{
"id":"1a_ext",
"type":1,
"keyType":"externalkey"
},
"moreInfo":true,
"userFields":[
"id",
"name",
"longname",
"externalkey"
]
}
},
"jsonrpc":"2.0"
}
I don't know to do the part after "params" (how do I "put" options "into" params) - for the other parts I know what I have to do:
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
$json = json_encode($json, true);
return self::request($json);
}
I would really appreciate your help, thanks!
You directly can assign to the params keys like
$json['params']['options'] = $your_options;
Full version of your code as an example
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
# add something to param index
$json['params']['options'] = $your_options;
$json = json_encode($json, true);
return self::request($json);
}
You can create the this in array format in PHP and then JSON encode:
$arr = [
'id' => 1,
'method' => 'getData',
'params' => [
'options' => [
'element' => [
'id' => '1a_ext',
'type' => 1,
'keyType' => 'externalKey'
],
'moreInfo' => true,
'userFields' => [
'id',
'name',
'longname',
'externalKey'
]
]
],
'jsonrpc' => '2.0'
];
$json = json_encode($arr);
Instead of spoonfeeding, i would like to help related, Whenever if you find difficulties to create an array representation of a JSON then you should use var_export(array, true) the second parameter must be true to return the variable representation instead of outputting it
<?php
$json_str = '{
"id": "1",
"method": "getData",
"params": {
"options": {
"element": {"id": "1a_ext", "type": 1, "keyType": "externalkey"},
"moreInfo": true,
"userFields": ["id", "name", "longname", "externalkey"]
}
},
"jsonrpc": "2.0"
}';
$json_arr = var_export(json_decode($json_str, true), true);
print_r($json_arr);
check the output here https://paiza.io/projects/eUZZDsTsSFSM4m9WMl05Ow
$json_arr is an array representation for your JSON, now you can dynamic the array values

How to send internal array in json when i want to send it to the webservice with SoapClient in php7

I'm working with a fly web service.I should to be able to create following json format and send to the server :
{
"FareSourceCode": "313139353639393726323426363636323231",
"SessionId": "53a2210f-b151-4aa1-bef0-3db2dbe71565",
"TravelerInfo": {
"PhoneNumber": "02012345678",
"Email": "Sales#partocrs.com",
"AirTravelers": [
{
"DateOfBirth": "1990-11-01T00:00:00",
"Gender": 0,
"PassengerType": 1,
"PassengerName": {
"PassengerFirstName": "John",
"PassengerLastName": "Smith",
"PassengerTitle": 0
},
"Passport": {
"Country": "US",
"ExpiryDate": "2020-05-06T00:00:00",
"PassportNumber": "AB1234567"
},
"NationalId": "0012230877",
"Nationality": "US",
"ExtraServiceId": [
"sample string 1"
],
"FrequentFlyerNumber": "123456789",
"SeatPreference": 0,
"MealPreference": 0
}
]
}
}
I use SoapClient in php7 with this code :
<?php
$PassengerData = //Get passengers informations from mysql
$AirTravelers = array();
foreach ($PassengerData as $p) {
$PassengerType = 'Adt'; //Adult
$PassengerTitle = ($p->sex) ? 'Mrs' : 'Mr';
$AirTravelers = [
'DateOfBirth' => $p->age,
'Gender' => $p->sex ? 'Female' : 'Male',
'PassengerType' => $PassengerType,
'PassengerName' => [
'PassengerFirstName' => $p->efname,
'PassengerLastName' => $p->elname,
'PassengerTitle' => $PassengerTitle,
],
'Passport' => [
'Country' => 'IR',
'ExpiryDate' => $p->passport_expire,
'PassportNumber' => $p->passport_number,
],
'NationalId' => $p->ncode,
'Nationality' => 'IR',
'SeatPreference' => 'Any',
'MealPreference' => 'Any',
];
}
$client = new \SoapClient($ServerHttp);
$session = $client->CreateSession(array("rq" => [ "OfficeId" => $PartoOfficeId, "UserName" => $PartoUserName, "Password" => $PartoPassword]));
$AirBook = $client->AirBook(
array("rq" => [
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' =>$AirTravelers
]
]
)
);
But this code can't make correct json format.Because php output json like this :
"AirTravelers": **[**{...}**]**
When i see json log(with json_encode):
json_encode([
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' => $AirTravelers
]
])
It is like this (php output json):
"AirTravelers": **{**
And When i use this code :
json_encode([
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' => **[**$AirTravelers**]**
]
])
Json output format were as follows:
$AirTravelers = **[**{....}]**strong text**
My question is :How can i send correct json format to this web service?
I use json_encode in my php request but it doesn't work and when i use :
$AirBook = $client->AirBook(
array("rq" => [
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' =>[$AirTravelers]
]
]
)
);
I receive this error in php :
Fatal error: Uncaught SoapFault exception: [a:DeserializationFailed ] The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:rq. The InnerException message was 'There was an error deserializing the object of type ServiceModel.Request.AirBook. The value '1988-11-16 00:00:00' cannot be parsed as the type 'DateTime'.'. Please see InnerException for more details. in C:\wamp64 \www\paradise\wp-content\plugins\amir_traveler\fly\fly_functions.php on line 341
SoapFault: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:rq. The InnerException message was 'There was an error deserializing the object of type ServiceModel.Request.AirBook. The value '1988-11-16 00:00:00' cannot be parsed as the type 'DateTime'.'. Please see InnerException for more details. in C:\wamp64\www\paradise\wp-content\plugins\amir_traveler\fly\fly_functions.php on line 341

Different output in AWS PHP SDK than in AWSCLI

The primary goal that I'm trying to achieve is to iterate over my running EC2 instances in PHP.
It's really easy to get the data using a bash script, as shown below:
Bash script:
#!/bin/bash
export AWS_ACCESS_KEY_ID="AKIDEXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"
aws ec2 describe-instances --region="eu-west-1" --filter "Name=instance-state-name,Values=running"
Bash output:
{
"Reservations": [
{
"OwnerId": "58728357357",
"ReservationId": "r-0e0283649826935",
"Instances": [
{
"SecurityGroups": [
{
"GroupId": "sg-2fe333148",
"GroupName": "WEB"
}
],
"PublicDnsName": "ec2-53-13-121-72.eu-west-1.compute.amazonaws.com",
"Architecture": "x86_64",
"LaunchTime": "2016-07-11T08:28:23.000Z",
"RootDeviceName": "/dev/sda1",
"BlockDeviceMappings": [
{
"Ebs": {
// ...
}
]
}
However, when I try the following example, using the same keys, I am presented with what seems to be an unusable object - or at least the object looks like it is representing an empty data structure.
PHP File:
<?php
require __DIR__ . "/vendor/autoload.php";
$settings = [
"version" => "latest",
"region" => "eu-west-1",
"credentials" => [
"key" => "AKIDEXAMPLE",
"secret" => "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
],
];
$client = new \Aws\Ec2\Ec2Client($settings);
$result = $client->describeInstances([
"Filters" => [
[
"Name" => "instance-state-name",
"Value" => "running",
]
],
]);
var_dump($result);
PHP Output:
What the hell am I meant to do with this AWS\Result?
class Aws\Result#82 (1) {
private $data =>
array(2) {
'Reservations' =>
array(0) {
}
'#metadata' =>
array(4) {
'statusCode' =>
int(200)
'effectiveUri' =>
string(35) "https://ec2.eu-west-1.amazonaws.com"
'headers' =>
array(5) {
...
}
'transferStats' =>
array(1) {
...
}
}
}
}
Am I missing something in the PHP configuration? Please can someone help point me in the right direction?
P.S. I've masked the API keys in the above examples.
EC2::DescribeInstances takes an array of filters, each of which has a string Name and an array of string Values. In your CLI example, you've supplied something for Values, whereas in your PHP example you've supplied a Value instead. This field is not recognized by the SDK and will be ignored. See the SDK API docs for more information.
Your PHP should be updated to read:
<?php
require __DIR__ . "/vendor/autoload.php";
$settings = [
"version" => "latest",
"region" => "eu-west-1",
"credentials" => [
"key" => "AKIDEXAMPLE",
"secret" => "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
],
];
$client = new \Aws\Ec2\Ec2Client($settings);
$result = $client->describeInstances([
"Filters" => [
[
"Name" => "instance-state-name",
"Values" => ["running"],
]
],
]);
var_dump($result);

Categories