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 4edad3c commit c4618ec
Showing 1 changed file with 129 additions and 0 deletions.
129 changes: 129 additions & 0 deletions examples/atlas-search.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?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 printf;
use function sleep;

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

$uri = getenv('MONGODB_URI');
if (! $uri || ! preg_match('/\.(mongodb\.net|mongodb-dev\.net)/', $uri)) {
printf("This example requires a MongoDB Atlas cluster.\n");

Check failure on line 28 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:28:5: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
printf("Make sure you set the MONGODB_URI environment variable.\n");

Check failure on line 29 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:29:5: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
exit(1);
}

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

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

Check failure on line 37 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / phpcs

Member variable "sample_airbnb" is not in valid camel caps format

$count = $collection->estimatedDocumentCount();
if ($count === 0) {
printf("This example requires the sample_airbnb database with the listingsAndReviews collection.\n");

Check failure on line 41 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:41:5: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
printf("Load the sample dataset in your MongoDB Atlas cluster before running this example:\n");

Check failure on line 42 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:42:5: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
printf(" https://www.mongodb.com/docs/atlas/sample-data/\n");

Check failure on line 43 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:43:5: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
exit(1);
}

// Delete the index if it already exists.
$indexes = iterator_to_array($collection->listSearchIndexes());
foreach ($indexes as $index) {
if ($index->name === 'default') {

Check failure on line 50 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidPropertyFetch

examples/atlas-search.php:50:9: InvalidPropertyFetch: Cannot fetch property on non-object $index of type array{id: string, latestDefinition: array<array-key, mixed>, name: string, queryable: bool, status: string} (see https://psalm.dev/029)
printf("\nThe index already exists. Dropping it.\n");

Check failure on line 51 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:51:9: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
$collection->dropSearchIndex($index->name);

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

Check failure on line 57 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidPropertyFetch

examples/atlas-search.php:57:21: InvalidPropertyFetch: Cannot fetch property on non-object $index of type array{id: string, latestDefinition: array<array-key, mixed>, name: string, queryable: bool, status: string} (see https://psalm.dev/029)
printf("Waiting for the index to be deleted...\n");

Check failure on line 58 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:58:21: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)

return false;
}
}

return true;
});
}
}

// Create the search index
printf("\nCreating the index.\n");

Check failure on line 70 in examples/atlas-search.php

View workflow job for this annotation

GitHub Actions / Psalm

RedundantFunctionCall

examples/atlas-search.php:70:1: RedundantFunctionCall: Using printf with a single argument is redundant, since there are no placeholder params to be substituted (see https://psalm.dev/280)
$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') {
printf("Waiting for the index to be ready...\n");

return $index->queryable;
}
}

return false;
});

// Perform a text search.
printf("\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) {
printf(" - %s\n", $document['name']);
}

printf("\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');
}

0 comments on commit c4618ec

Please sign in to comment.