Skip to content

Commit

Permalink
Create search example
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN committed Aug 31, 2023
1 parent f6ce211 commit 9ea634c
Show file tree
Hide file tree
Showing 2 changed files with 151 additions and 0 deletions.
130 changes: 130 additions & 0 deletions examples/atlas-search.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php

/**
* This example demonstrates how to create a search index and perform a text search.
* It requires a MongoDB Atlas M10+ cluster with Sample Dataset loaded.
*/

declare(strict_types=1);

namespace MongoDB\Examples;

use Closure;
use MongoDB\Client;
use RuntimeException;

use function define;
use function getenv;
use function hrtime;
use function iterator_to_array;
use function preg_match;
use function sleep;

require __DIR__ . '/../vendor/autoload.php';

$uri = getenv('MONGODB_URI');
if (! $uri || ! preg_match('/\.(mongodb\.net|mongodb-dev\.net)/', $uri)) {
echo "This example requires a MongoDB Atlas cluster.\n";
echo "Make sure you set the MONGODB_URI environment variable.\n";
exit(1);
}

define('WAIT_TIMEOUT_SEC', (int) getenv('MONGODB_WAIT_TIMEOUT_SEC') ?: 300);
define('INDEX_NAME', 'default');

$client = new Client($uri);
$collection = $client->selectCollection('sample_airbnb', 'listingsAndReviews');

$count = $collection->estimatedDocumentCount();
if ($count === 0) {
echo "This example requires the sample_airbnb database with the listingsAndReviews collection.\n";
echo "Load the sample dataset in your MongoDB Atlas cluster before running this example:\n";
echo " https://www.mongodb.com/docs/atlas/sample-data/\n";
exit(1);
}

// Delete the index if it already exists.
$indexes = iterator_to_array($collection->listSearchIndexes());
foreach ($indexes as $index) {
if ($index->name === 'default') {
echo "\nThe index already exists. Dropping it.\n";
$collection->dropSearchIndex($index->name);

// Wait for the index to be deleted.
wait(function () use ($collection) {
foreach ($collection->listSearchIndexes() as $index) {
if ($index->name === 'default') {
echo '.';

return false;
}
}

echo "\n";

return true;
});
}
}

// Create the search index
echo "\nCreating the index.\n";
$collection->createSearchIndex(
// Index definition
// See: https://www.mongodb.com/docs/atlas/atlas-search/define-field-mappings/
['mappings' => ['dynamic' => true]],
// "default" is the default index name, this config can be omitted.
['name' => 'default'],
);

// Wait for the index to be ready.
wait(function () use ($collection) {
foreach ($collection->listSearchIndexes() as $index) {
if ($index->name === 'default') {
echo '.';

return $index->queryable;
}
}

return false;
});

// Perform a text search.
echo "\nPerforming a text search...\n";
$results = $collection->aggregate([
[
'$search' => [
'index' => 'default',
'text' => [
'query' => 'view beach ocean',
'path' => ['name'],
],
],
],
['$project' => ['name' => 1, 'description' => 1]],
['$limit' => 10],
])->toArray();

foreach ($results as $document) {
echo ' -', $document['name'], "\n";
}

echo "\nEnjoy MongoDB Atlas Search!\n\n";

/**
* Wait until the callback returns true or the timeout is reached.
*/
function wait(Closure $callback): void
{
$timeout = hrtime()[0] + WAIT_TIMEOUT_SEC;
while (hrtime()[0] < $timeout) {
if ($callback()) {
return;
}

sleep(5);
}

throw new RuntimeException('Time out');
}
21 changes: 21 additions & 0 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,27 @@
<code><![CDATA[$clientEncryption->decrypt($document->encryptedField)]]></code>
</MixedArgument>
</file>
<file src="examples/atlas-search.php">
<MixedArgument>
<code><![CDATA[$document['name']]]></code>
<code><![CDATA[$index->name]]></code>
</MixedArgument>
<MixedArrayAccess>
<code><![CDATA[$document['name']]]></code>
</MixedArrayAccess>
<MixedAssignment>
<code>$document</code>
<code>$index</code>
<code>$index</code>
<code>$index</code>
</MixedAssignment>
<MixedPropertyFetch>
<code><![CDATA[$index->name]]></code>
<code><![CDATA[$index->name]]></code>
<code><![CDATA[$index->name]]></code>
<code><![CDATA[$index->queryable]]></code>
</MixedPropertyFetch>
</file>
<file src="src/ChangeStream.php">
<DeprecatedConstant>
<code>self::CURSOR_NOT_FOUND</code>
Expand Down

0 comments on commit 9ea634c

Please sign in to comment.