How to make a WHERE categoryId = 1 OR categoryId = 2 query with Elastica ? I'm doing this but I got 0 result :
$query = new \Elastica\Query();
$boolOr = new \Elastica\Filter\BoolOr();
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '1')));
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '2')));
$filtered = new \Elastica\Query\Filtered(new \Elastica\Query\MatchAll(), $boolOr);
$query->setQuery($filtered);
$products = $type->search($query)->getResults();
Here is a working example:
$index = $this->_createIndex();
$type = $index->getType('test');
$doc1 = new Document('', array('categoryId' => 1));
$doc2 = new Document('', array('categoryId' => 2));
$doc3 = new Document('', array('categoryId' => 3));
$type->addDocument($doc1);
$type->addDocument($doc2);
$type->addDocument($doc3);
$index->refresh();
$boolOr = new \Elastica\Filter\BoolOr();
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '1')));
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '2')));
$resultSet = $type->search($boolOr);
You don't need to use the filtered and matchall query. The working example can be found here: https://github.com/ruflin/Elastica/pull/887/files
Related
So I have the following code to get a document from a collection in my database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document);
}
I'm able to successfully retrieve a document by searching for the username, so if $uname is "Jon", I get the following output:
stdClass Object ( [username] => Jon [email] => Jon#mail.com [passwd] => pass123 )
However, what I want to do is just return a single value from the document, so if I wanted to get the value for email, it would return:
Jon#mail.com
...so then I could store that value as a variable.
How would I do this?
Std class objects can be accessed via -> operator. So you can user $document->email to access individual email. Is this what you are looking for
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document->email);
}
I am using the Google API to add rows to a Google Sheet. This is all working well, but the new rows are being added to the end (using the append method).
I would like to insert the row at the top, below the heading, in my case Row 2.
This is my working code for adding to the end. How can I specify where I want to insert the row at a given position.
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $CredentialFile);
$client = new \Google_Client;
$client->useApplicationDefaultCredentials();
$client->setApplicationName("MyApp");
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
ServiceRequestFactory::setInstance(new DefaultServiceRequest($accessToken));
$SheetId = "MySheetId";
$service = new \Google_Service_Sheets($client);
$sheet = $service->spreadsheets->get($SheetId);
$sheets = $sheet->getSheets();
$SheetTitle = $sheets[0]->properties->title;
$range = "{$SheetTitle}!A:D";
$values = [];
$row = [];
$row[] = "Tom";
$row[] = "Thumb";
$row[] = "tomthumb";
$row[] = "tom#thumb.com"
$values[] = $row;
$body = new \Google_Service_Sheets_ValueRange([
'values' => $values
]);
$params = [
'valueInputOption' => "RAW"
];
$result = $service->spreadsheets_values->append($SheetId, $range, $body, $params);
You are using values.append which by definition appends values to the first empty row
If you want to insert your values in a range that is not the first empty row of the sheet, you need to use instead the method values.batchUpdate
Sample:
$range="Sheet1!A2:D2";
$values = array(
array(
"Tom", "Thumb", "tomthumb", "tom#thumb.com"
)
);
$data = array();
$data[] = new Google_Service_Sheets_ValueRange(array(
'range' => $range,
'values' => $values
)
);
$body = new Google_Service_Sheets_BatchUpdateValuesRequest(array(
'valueInputOption' => 'RAW',
'data' => $data
)
);
$result = $service->spreadsheets_values->batchUpdate($SheetId, $body);
UPDATE
I you want to insert a row with with data rather than pasting data into an already existing row - you need to create the additional row first.
This can be done with a InsertDimensionRequest.
Sample:
$request = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => array(
'insertDimension' => array(
'range' => array(
"startIndex": 1,
"endIndex": 2,
"dimension": "ROWS",
"sheetId": 0
)
)
)
));
$request->setRequests($body);
$result = $service->spreadsheets->batchUpdate($SheetId, $request);
I have a mongo collection and I'd like to obtain all the document whose names start with a given letter on PHP. My code:
$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");
$regex = new MongoDB\BSON\Regex ("^$letter", "i");
$query = array('name' => $regex); // 1
$query = array('name' => $regex, array( 'sort' => array( 'OrderBy' => 1 ) )); // 2
$query = new MongoDB\Driver\Query( array('name' => $regex), array( 'sort' => array( 'OrderBy' => 1 ) ) ); // 3
$cursor = $pme->find($query);
Whe I use query 1. I got all documents starting with letter c but not ordered. When I use query 2, I got nothing. And finally when I use query 3 I get almost every document, not just those starting with with 'c'. What I am doing wrong here?
In mongo method sort should be applied on cursor obtained by find:
$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");
$regex = new MongoDB\BSON\Regex ("^$letter", "i");
$query = array('name' => $regex);
// sort by field `name` happens here
$options = array("sort" => array("name" => 1), );
$cursor = $pme->find($query, $options);
I have been install Mongodb v.2.6.7 with php mongo driver v.1.6.3
When I get data all it work normally but if I use where query It return empty array back to me.
<?php
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');
// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));
$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
var_dump($doc);
}
source
I tried using the fields() method on the cursor:
<?php
$mongo = new Mongo("mongodb://localhost");
print_r($mongo);
$db = $mongo->test;
// access collection
$collection = $db->test;
// execute query
// retrieve all documents
print_r($test);
$cursor = $collection->find();
print_r($cursor);
$fields = $cursor->fields(array("summary" => true));
print_r($fields);
The output is:
Mongo Object ( [connected] => 1 [status] => [server:protected] => [persistent:protected] => )
MongoCursor Object ( )
MongoCursor Object ( )
Looks like the driver and the connection work but I can't retrieve the distinct summarization of the fields.
Assume that we have access to mongodb database with the name db, are going to retrieve data from MyCollection and use MongoDB\Driver\Manager:
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then we retrieve data in this case by name with a limit 2 documents and want to get only fields name, age and address among many others. Projection option can be used to specify which fields should be returned using 0 to exclude and 1 to include:
$filter = ['name' => 'John'];
$options = [ 'projection' => ['_id' => 0, 'name' => 1, 'age' => 1, 'address' => 1], 'limit' => 2 ];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
If we need to get all columns, then we simply omit projection option at all as the following:
$filter = ['name' => 'daniel'];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'test';
const COLLECTION = 'test';
$connectionString = sprintf('mongodb://%s:%d', HOST, PORT);
try {
$connection = new Mongo($connectionString);
$database = $connection->selectDB(DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
$collection = $database->selectCollection(COLLECTION);
try{
$query = array();
$specifyKey = array("summary" => true);
$cursor = $collection->find($query , $specifyKey);
}catch(MongoException $e) {
die('Failed to find One data '.$e->getMessage());
}catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
while ($cursor->hasNext()){
$nextCursor = $cursor->getNext();
//process next cursor
}
After the $cursor variable try an foreach instead. It goes through the cursor results.
foreach($cursor as $document) {
var_dump($document);
}