Skip to content

Instantly share code, notes, and snippets.

@lachlanagnew
Created March 28, 2019 03:37
Show Gist options
  • Save lachlanagnew/fcd83661ef91e2714552265737106e8f to your computer and use it in GitHub Desktop.
Save lachlanagnew/fcd83661ef91e2714552265737106e8f to your computer and use it in GitHub Desktop.
const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
host: 'elasticsearch:9200'
});
app.post("/users/search", async (req, res) => {
let query = req.body.query;
console.log(`Searching users for ${query}`)
try {
const response = await client.search({
index: 'example',
type: 'users',
body: {
query: {
bool: {
should: [
{
match: {
username: query
}
},
{
wildcard: {
username: `*${query}*`
}
},
{
fuzzy: {
username: query
}
}
],
minimum_should_match: 1
}
}
}
})
if (response.hits.total > 0) {
const hits = response.hits.hits;
res.status(200).send(hits.map((user_data) => {
return {
username: user_data._source.username,
id: user_data._source.id
}
}))
} else {
res.status(200).send([]);
}
} catch (error) {
res.status(422).send(error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment