diff --git a/examples/atlas-search.php b/examples/atlas-search.php new file mode 100644 index 000000000..80bce6628 --- /dev/null +++ b/examples/atlas-search.php @@ -0,0 +1,129 @@ +sample_airbnb->listingsAndReviews; + +$count = $collection->estimatedDocumentCount(); +if ($count === 0) { + printf("This example requires the sample_airbnb database with the listingsAndReviews collection.\n"); + printf("Load the sample dataset in your MongoDB Atlas cluster before running this example:\n"); + printf(" 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') { + printf("\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') { + printf("Waiting for the index to be deleted...\n"); + + return false; + } + } + + return true; + }); + } +} + +// Create the search index +printf("\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') { + 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'); +}