This simple tutorial shows how to expose Atlas Search functionality via an Atlas HTTPS Endpoint.
For this tutorial I'll leverage the sample_training.inspections sample dataset.
Create a default Search index on the sample_training.inspections
collection.
HTTPS endpoints allow you to define custom API endpoints for your appliciations. You access them from the Atlas Realm UI:
Set the Route to /inspections/search
Set the HTTP Method to GET and Response With Result to ON.
Create a New Function and set the Function Name to searchInspections:
Note, the HTTPS Endpoint requires a backing function, which when created from the HTTPS Endpoint, provides example code on how to access the endpoint's arguments and payload. You are welcome to create the function first, but you will see different example code if you do.
Replace the provided sample function code with the following:
// This function is the endpoint's request handler.
exports = function({ query, headers, body}, response) {
// A default value for testing from this console if searchTerm is not defined.
var searchTerm = "Fail"
if (query != undefined)
if (query.searchTerm != undefined)
searchTerm = query.searchTerm;
console.log("searchTerm: ", searchTerm);
var inspectinsCollection = context.services.get("mongodb-atlas").db("sample_training").collection("inspections");
const pipeline = [{$search: {
index: 'default',
text: {
query: searchTerm,
path: {
wildcard: '*'
}
}
}}, {$addFields: {
score: {
$meta: 'searchScore'
}
}}, {
$limit: 10
}]
return inspectinsCollection.aggregate(pipeline).toArray()
.then(inspections => {
console.log(`Successfully searched inspections for ${searchTerm}.`)
for(const inspection of inspections) {
console.log(`business_name: ${inspection.business_name}`)
}
return inspections
})
.catch(err => console.error(`Failed to search inspections: ${err}`))
};
Edit the searchInspections function and set its Authentication to System
And since the function will never be called externally, go ahead and set Private to ON.
Copy the callback URL from the HTTPS Endpoints Settings:
Paste the URL in your browser, appending ?searchTerm=<term>. For example, let's search for "health risk"