Created
March 28, 2019 03:37
-
-
Save lachlanagnew/fcd83661ef91e2714552265737106e8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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