Problem in implementing Sphinx API along with Cake php - php

I am working on project where I need to implement SphinxSearch with Cake php. So I am simply trying to use a component and behaviour into it. The link to it, is :-
http://bakery.cakephp.org/articles/eugenioclrc/2010/07/10/sphinx-component-and-behavior
I am requesting Sphinx API like below :
$sphinx = array('matchMode' => SPH_MATCH_ALL, 'sortMode' => array(SPH_SORT_EXTENDED => '#relevance DESC'));
$results = $this->ModelName->find('all', array('search' => 'Search_Query', 'sphinx' => $sphinx));
pr($result);
For above it is working fine ,but when I tried to minimise the response time querying to a particular field of the table (using extended match modes,i.e. SPH_MATCH_EXTENDED2) , Sphinx just fails to output any result. The extended query which I used is given below :-
$sphinx = array('matchMode' => SPH_MATCH_EXTENDED2, 'sortMode' => array(SPH_SORT_EXTENDED => '#relevance DESC'));
$results = $this->ModelName->find('all', array('search' => '#Field_name Search_Query', 'sphinx' => $sphinx));
pr($results);
Can anyone recognise where am I going wrong with it? Please help if I am going wrong some where.
Thanks in advance.

Btw, when you use EXTENDED2 mode make sure your rank mode is set accordingly.
Edit:
Anyway back to you problem, looking at that component/behavior code you can see right away that no error checking is done whatsoever. Try changing the code a bit so you can at least see the errors and/or warnings.
Component
if(!isset($query['search'])){
$result = self::$sphinx->Query('', $indexes);
} else {
$result = self::$sphinx->Query($query['search'], $indexes);
}
if ($result === false) {
// throw new SphinxException();
die(self::$sphinx->GetLastError());
}
$warn = self::$sphinx->GetLastWarning();
if ($warn) echo $warn;
Behavior
$result=$this->runtime[$model->alias]['sphinx']->search($s);
if ($result === false) {
die($this->runtime[$model->alias]['sphinx']->GetLastError());
}
$warn = $this->runtime[$model->alias]['sphinx']->GetLastWarning();
if ($warn) echo $warn;
I hope that helps.

As you said ,
Sphinx just fails to output any result.
That means it's an error :
Please check whether you have added the specific field to the indexing by using sql_query
Also check if the field you are searching for is not an attribute
As per the sphinx documentation :
Attributes, unlike the fields, are not full-text indexed. They are stored in the index, but it is not possible to search them as full-text, and attempting to do so results in an error.

Related

Check if update push is succesfull

I update an existing document with the code below. Its working fine.
foreach($jArray as $value){
!!some code!!
try {
$collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
echo json_encode($collection);
}
catch ( MongoConnectionException $e ) {
echo '<p>Update failed</p>';
exit();
}
}
JSON response:
{"w":1,"wtimeout":10000}{"w":1,"wtimeout":10000}
(2 values are tried to update)
Even if no tablename matched, means no update happend, the result is w = 1.
Why? No update happend and w is 1/true?
There seems to be a little confusion here. The JSON response you are looking at is not the actual return value from the update operation. What you did was JSONifying the collection itself, which has the integer attributes w and wtimeout (see source code here). Those attributes are in no way related to the result of the update operation itself.
So, the right way to go seems to be changing the lines inside the scope of your try statement to:
$result = $collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
echo json_encode($result);
For more information about what is returned from the update method, refer to these docs.

PHP-generated JSON for Google Maps: a tiny mystery

I am using a PHP script (this one) to generate a JSON file for a Google Map.
this is the PHP code (note: I am using Laravel):
<?php
$query = "SELECT id, info, lat, lng FROM places";
$results = DB::select($query);
$myLocations = array();
$i = 0;
$testLoc = array('loc95' => array( 'lat' => 15, 'lng' => 144.9634 ));
foreach ($results as $result)
{
$myLocation = array(
'loc'.++$i => array(
'lat' => round((float)$result->lat, 4),
'lng' => round((float)$result->lng, 4)
));
$myLocations += $myLocation;
}
$myLocations += $testLoc;
echo json_encode($myLocations);
?>
and this is the output:
{"loc1":{"lat":45.4833,"lng":9.1854},"loc2":{"lat":45.4867,"lng":9.1648},"loc3":{"lat":45.4239,"lng":9.1652},"loc95":{"lat":15,"lng":144.9634}}
ok. the script I use to put the JSON data in a Google Map, unfortunately, keeps ignoring any data coming from the MySQL database, and shows only the test data place(s). I have tried to swap data, to put in test data the same info found in database... nothing, I keep seeing only the test data.
but, really: I cannot figure out why. What am I missing... ?
You wrote that you're using another script and that the other script only shows the testlocations on google maps.
My guess is that you didn't update the other script to your needs, specifically my crystal ball is telling me that you still have this line in there:
setMarkers(locs);//Create markers from the initial dataset served with the document.
In your question you only showed the part which worked and I agree, but you only mentioned that "something else" isn't working. If you want an answer for that part, try reprashing your question and include the parts which cause you problems.

mongodb getLastError() php

how do i use getLastError() within php to check if my save method is inserting to mongo?
i set up my db as follows:
$this->databaseEngine = $app['mongo'];
$this->db = $this->databaseEngine->dbname;
$this->collection = $this->db->collectionname;
my insert query then looks like this:
$query = array(
'fieldname' => $fieldname
);
$this->collection->insert($query);
I want to then use getLastError() to check whether it is inserting correctly, and if not why. but im not sure how to implement it.
do i use after the insert:
$this->collection->getLastError("what goes here?");
cheers.
Update
i eventually used this to get the last error:
echo '<pre>' . print_r($this->databaseEngine->lastError(), true) . '</pre>';
Sammaye's way works just as well, see below.
$this->collection->getLastError("what goes here?");
Nothing goes there, the return of the getLastError is the last error from MongoDB ( http://www.php.net/manual/en/mongodb.lasterror.php ). Also it is used on the MongoDB class (atm).
You don't have to use it like that, instead you can do:
$this->collection->insert($query, ARRAY('safe' => TRUE));
This will return an array from the function detailing whether or not it actually inserted. The details of the array can be found by reading this page:
http://www.php.net/manual/en/mongocollection.insert.php

What is the best way to check if table exists in DynamoDB?

What is the best way to check if table exists in DynamoDb?
I would appreciate it if the code would be in PHP.
Either active or not.
* Added later as an example to various cases for error code 400
It's very easy to check if the table exist, it can have one of the following
TableStatus => CREATING, ACTIVE, DELETING or UPDATING
but in case i get error 400 it can mean more than one thing.
1) sent null string as a table name by mistake.
[x-aws-body] => {"TableName":""}
)
[body] => CFSimpleXML Object
(
[__type] => com.amazon.coral.validate#ValidationException
[message] => The paramater 'tableName' must be at least 3 characters long and at most 255 characters long
)
[status] => 400
2) syntax error in the command sent to DynamoDB, for example writting tabel_name instead of table_name.
[x-aws-body] => {"TabelName":"test7"}
)
[body] => CFSimpleXML Object
(
[__type] => com.amazon.coral.validate#ValidationException
[message] => The paramater 'tableName' is required but was not present in the request
)
[status] => 400
3) I would guess but didn't check, if I exceed at that same time the provisioned capacity on the table.
You can have a look at "describe_table" of the official PHP SDK. 400 means "does not exist" There is a pretty extensive example in the official documentation. Look at how it is used in the "delete" example, right at the bottom.
http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/LowLevelPHPTableOperationsExample.html
Here is the (stripped) example from the doc
<?php
require_once dirname(__FILE__) . '/sdk/sdk.class.php';
$dynamodb = new AmazonDynamoDB();
$table_name = 'ExampleTable';
$response = $dynamodb->describe_table(array('TableName' => $table_name));
if((integer) $response->status !== 400)
{
$error_type = $response->body->__type;
$error_code = explode('#', $error_type)[1];
if($error_code == 'ResourceNotFoundException')
{
echo "Table ".$table_name." exists.";
}
}
?>
Some of these answers are using the older SDK's and so I thought I'd update this useful question with what I coded up and works well. The newer exceptions really do make this task easier. This function gives you a nice boolean to use in scripts.
use Aws\DynamoDb\Exception\ResourceNotFoundException; // <-- make sure this line is at the top
public function TableExists($tableName) {
$ddb = DynamoDbClient::factory(array('region' => 'us-east-1')); // EC2 role security
try {
$result = $ddb->describeTable(array(
"TableName" => $tableName
));
} catch (ResourceNotFoundException $e) {
// if this exception is thrown, the table doesn't exist
return false;
}
// no exception thrown? table exists!
return true;
}
Hopefully this complete working code helps some of you.
I think the answer that solves this with describeTable is a good one, but fooling around with the status code response makes the code less readable and more confusing.
I chose to check for a tables existence using listTables. Here are the docs
$tableName = 'my_table';
$client = DynamoDbClient::factory(array('region' => 'us-west-2'));
$response = $client->listTables();
if (!in_array($tableName, $response['TableNames'])) {
// handle non-existence.
// throw an error if you want or whatever
}
// handle existence
echo "Table " . $tableName . " exists";
With DynamoDB you need to parse the contents of the error message in order to know what type of error you received since the status code is almost always 400. Here is a sample function that could work to determine if a table exists. It also allows you to specify a status as well if you want to check if it exists and if it is in a certain state.
<?php
function doesTableExist(AmazonDynamoDB $ddb, $tableName, $desiredStatus = null)
{
$response = $ddb->describe_table(array('TableName' => $tableName));
if ($response->isOK()) {
if ($desiredStatus) {
$status = $response->body->Table->TableStatus->to_string();
return ($status === $desiredStatus);
} else {
return true;
}
} elseif ($response->status === 400) {
$error = explode('#', $response->body->__type->to_string());
$error = end($error);
if ($error === 'ResourceNotFoundException') {
return false;
}
}
throw new DynamoDB_Exception('Error performing the DescribeTable operation.');
}
Update: In the AWS SDK for PHP 2, specific exceptions are thrown by the DynamoDB client, making this way easier to handle. Also, there are "Waiter" objects, including one for this use case (see usage in the unit test) that is designed to sleep until the table exists.
The above answers are correct if you just want to know whether the table exist or not. I want to make another helpful point here in case.
One should be very careful in multi-threaded or production level code.
Assuming that one thread deleted the table, then you will still get the answer that the table exists in answer to your query from second thread, until the table is fully deleted. In such case, once the table is deleted, the table handle in second thread is zombie, like the dangling pointer error in C++.
With dynamodb cli you can do it very simple as follows:
aws dynamodb describe-table --table-name "my-table"
If the table exists it returns
0 -- Command was successful. There were no errors thrown by either the CLI or by the service the request was made to.
If the table does not exist it returns
255 -- Command failed. There were errors thrown by either the CLI or by the service the request was made to.
See also:
http://docs.aws.amazon.com/cli/latest/reference/dynamodb/describe-table.html
http://docs.aws.amazon.com/cli/latest/topic/return-codes.html

Dissapearing PHP Variables

I am creating a 3D Secure PHP Project. I am having a rather bizzare issue in that the "MD" code is going missing when re-submitting the Array of data
My code is as follows :
$paRes = $_REQUEST['PaRes'];
$md = $_REQUEST['MD'];
require "payment_method_3d.php";
x_load('cart','crypt','order','payment','tests');
/*
* For Debugging Purposes
* Only.
echo "The Value Of PaRes is : ";
echo $paRes;
*/
$soapClient = new SoapClient("https://www.secpay.com/java-bin/services/SECCardService?wsdl");
$params = array (
'mid' => '',
'vpn_pswd' => '',
'trans_id' => 'TRAN0095', // Transaction ID MUST match what was sent in payment_cc_new file
'md' => $md,
'paRes' => $paRes,
'options' => ''
);
It seems that the $_REQUEST['MD'] string seems to go missing AFTER the soap call. Although I am having difficulty print this out to the screen. The strange thing is the $paRes variable works without issue.
Any ideas why this would be the case?
Check your case. PHP array keys are case sensitive. From this little bit of code it looks as if the request variable may be 'md' instead of 'MD'.
Try $md = $_REQUEST['md'];
PHP array statements are case sensitive, so this should work:....
$md = $_REQUEST['md'];
Thanks for your responses guys.
What was happening was the include page was sitting in front of the request methods and causing issues loading the REQUEST methods to the page.

Categories