I'm new in solr and I've been using this thread to do a atomic update
How do I update a document in Solr PHP?
Basically im doing an mysql query then update a document on solr
Question: How to do an atomic update where a specific field matches a field should be matched inside an if statement like this:
if(solr(username.field) == 'john'))
{
//execute atomic update
}
so far my code is messy like these:
$query = "SELECT * from User";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH,
);
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_assoc($result))
{
$querySearch = '+username:*'; //query all user that is on solr
$query = new SolrQuery();
$query->setQuery($querySearch);
$query->setStart(0);
$query->setRows(10000);
$client = new SolrClient($options);
$query_response = $client->query($query);
$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);
$response = $query_response->getResponse();
$doc = new SolrInputDocument();
$counter = $response->response->numFound;
for($x = 0; $x < $counter; $x++)
{
$doc = $response->response->docs[$x]->getInputDocument(); //this gets the old value (refer to thread)
$docs = $query_response->getResponse()->response->docs[$x]->username->values; //how I get the value of users
$second_doc = new SolrInputDocument();
if($docs == get_product($row['USERNAME']))
{
$second_doc->addField('points', $row['POINTS']); //this suppose to update my solr document with those username found
}
else
{
$second_doc->addField('points', "0");
}
$second_doc->merge($doc);
$updateResponse = $client->addDocument($second_doc);
$client->commit();
}
}
It should have been
if(!empty($response->response->docs[$x]->username->values[$x]) == get_product($row['USERNAME']))
{
$doc = $response->response->docs[$x]->getInputDocument();
$second_doc->addField('point', $row['POINT']);
}
else
{
//do other update here
}
//$response->response->docs[$x]->username->values[$x] => get the usernames in the document
Related
I want to fetch all products from Square Catalog.
Here is the code:
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::SANDBOX,
]);
//Providing SKU
$object_ids = ['GFLR20L', '232GGGD'];
$body = new \Square\Models\BatchRetrieveCatalogObjectsRequest($object_ids);
$body->setIncludeRelatedObjects(true);
$api_response = $client->getCatalogApi()->batchRetrieveCatalogObjects($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
Output:
object(Square\Models\BatchRetrieveCatalogObjectsResponse)#13 (3)
{
["errors":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["objects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["relatedObjects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
}
**> Post Suggestions by sjosey:
My PHP Code:
Looking for Products with name Paper in it.**
$object_types = ['ITEM'];
$prefix_query = new \Square\Models\CatalogQueryPrefix('name', 'paper');
$query = new \Square\Models\CatalogQuery();
$query->setPrefixQuery($prefix_query);
> Storing Values Here
$body = new \Square\Models\SearchCatalogObjectsRequest();
$body->setObjectTypes($object_types);
$body->setQuery($query);
$body->setLimit(100);
$api_response = $client->getCatalogApi()->searchCatalogObjects($body);
> Fetching the api response here
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
> Echo Result
var_dump($result);
Here is the output:
object(Square\Models\SearchCatalogObjectsResponse)#15 (5) { ["errors":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["cursor":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["objects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["relatedObjects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["latestTime":"Square\Models\SearchCatalogObjectsResponse":private]=> string(20) "1776-07-04T00:00:00Z" }
object_ids are not the same as SKU; they are unique generated ids on Square's side. You would want to use the SearchCatalogObjects (POST /v2/catalog/search) endpoint instead to search by SKU. An example query using one of your SKUs would be:
{
"query": {
"exact_query": {
"attribute_name": "sku",
"attribute_value": "GFLR20L"
}
}
}
This will get your catalog object ids, but if you're interested in the inventory you would still need to use another endpoint to get the inventory, such as RetrieveInventoryCount (which takes the catalog_object_id's as the parameter).
Figured out the solution. The following codes fetches a list of all the products by Product IDS. The array can be used to set data as per requirements (By SKU or Anything)
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::PRODUCTION,
]);
$bag = [];
$cursor = null;
$ctr = 1;
$api_response = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
$g1 = $result;
$g2 = json_encode($g1);
$g3 = json_decode($g2);
$cursor = $g3->cursor;
$objects = $g3->objects;
$g4 = json_encode($objects);
$g5 = json_decode($g4);
foreach($g5 as $g51){
$bag[$g51->id] = $g51;
}
while($cursor != null){
$api_response2 = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response2->isSuccess()) {
$result2 = $api_response2->getResult();
} else {
$errors2 = $api_response2->getErrors();
}
$g6 = $result2;
$g7 = json_encode($g6);
$g8 = json_decode($g7);
$cursor = $g8->cursor;
$objects2 = $g8->objects;
$g9 = json_encode($objects2);
$g10 = json_decode($g9);
foreach($g10 as $g101){
$bag[$g101->id] = $g101;
}
}
var_dump(count($bag));
i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.
I'm currently looking at a script that a previous developer made that is meant to look a table, if the id does not exist then create the new code, if it does exist, overwrite the existing one.
Sounds fairly simple, but I can't get my head around how Yii manages the overwrite and new verification code. It is only adding new records, not over writing.
$invitingUser = User::model()->findByPk(Yii::app()->user->id);
if ($invitingUser->isAttending($eventId)) {
// Event attending
$event = Event::model()->findByPk($eventId);
//
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation(array($guestInviteForm));
if (isset($_POST['GuestInviteForm'])) {
$guestInviteForm->attributes = $_POST['GuestInviteForm'];
// Perform Validation
$valid = $guestInviteForm->validate();
if ($valid) {
// Check if a Verification Code entry for this user already exists
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
The code never seems to enter the else here
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
1st. After form validation:
if ($valid) {
Verification code select done:
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
If you translate it to SQL it will be something like this:
SELECT * FROM verification_code WHERE user_id=x AND type=x
2nd. Check if record exists
if (is_null($existingVerificationCode)) {
If its not - creating new, populating, saving.
Else updating:
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
save(false) means save without validation. Consider model attributes - fields in your database table.
Seems like it ever goes in the ELSE because it never finds $existingVerificationCode.
We don't have the whole code, but from what I see, I suspect you're checking the wrong user, because it's weird to search for an event for $user, and if that doesn't exist, to create one related to $invitingUser.
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
// ...
$verificationCode->user_id = $invitingUser->id;
I use FOSElasticaBundle in my project to search a list of ads. I can get all the result but I can't order it in "asc" or "desc". I have seen different tutorial speaking about Filtering. But it's not working.
if (!empty($cati)) {
$query = new \Elastica\Query\Bool();
if((!empty($cati)) && $cati!='1')
{
$query1 = new \Elastica\Query\Match();
$query1->setFieldQuery('post.cat_id', $cati);
$query->addMust($query1);
}
}
else {
$query = new \Elastica\Query\MatchAll();
}
$elasticaQuery = new \Elastica\Query();
$elasticaQuery->setQuery($query);
$elasticaQuery->setSize($nbPerPage);
$elasticaQuery->setFrom(($page - 1) * $nbPerPage);
$elasticaQuery->addSort(array('date', array("desc"));
$repistoryManager = $this->container->get('fos_elastica.manager');
$repistory = $repistoryManager->getRepository('AdsManagerBundle:Post');
$eq = new \Elastica\Query();
$eq->setQuery($query);
$finder = $this->container->get('fos_elastica.index.ads.post');
$elasticaResultSet = $finder->search($eq);
$ed = $elasticaResultSet->getResults();
I can't get where the problem is!
You did in a mistake in your code (parse error + bad construction of the JSON syntax):
$elasticaQuery->addSort(array('date' => 'desc'));
I am doing project using mongodb and php. so here I tried to rename existing database using php. so I did following way to rename database.
first I create new database( user new database name)
read all records from old db and insert to new db
then I drop old db
this is my code.
$conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
$exist_dbs = $conn->listDBs();
foreach ($exist_dbs["databases"] as $databse) {
if ($databse['name'] == $new_name) {
$new_name_is_exist = true;
}
}
if (!$new_name_is_exist) {
$db = new \MongoDB($conn, $old_name);
//create new database
$db_new = new \MongoDB($conn, $new_name);
$collections = $db->getCollectionNames();
foreach ($collections as $collection) {
//create collection
$new_collection = new \MongoCollection($db_new, $collection);
$mongo_collection = $db->$collection;
$objects = $mongo_collection->find();
while ($document = $objects->getNext()) {
//add records
$new_collection->insert($document);
}
}
$db->drop();
$msg = 'database renamed';
} else {
$msg = 'given database name already exist';
}
$conn->close();
it works fine. but I would like to know is there any better way to rename mongo database using php?
Copy db (php + mongodb):
<?php
$rename = 'oldname';
$name = 'newname';
$mongo = (new MongoClient());
$db = $mongo->admin;
$response = $db->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => $rename,
'todb' => $name
));
print_r($response);
Drop db (php + mongodb):
<?php
$name = 'oldname';
$mongo = (new MongoClient());
$db = $mongo->$name;
$response = $db->command(array(
'dropDatabase' => 1
));
print_r($response);
$db=new new Mongo();
Copy old_db to new_db
$responseCopy = $db->admin->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => 'old_db',
'todb' =>'new_db'
));
Now drop old_db
if($responseCopy['ok']==1){
$responseDrop=$db->old_db->command(array('dropDatabase' => 1));
//OR
$responseDrop =$db->old_db->drop();
}
Show Output
print_r($responseCopy);
print_r($responseDrop);
Output will be something like this
Array ( [ok] => 1 )
Array ( [dropped] => old_db [ok] => 1 )
you can use this
$mongo = new MongoClient('_MONGODB_HOST_URL_');
$query = array("renameCollection" => "Database.OldName", "to" => "Database.NewName", "dropTarget" => "true");
$mongo->admin->command($query);