Skip to content

Instantly share code, notes, and snippets.

@vrsandeep
Forked from StephanHoyer/elasticsearch-example.js
Last active July 9, 2024 17:55
Show Gist options
  • Save vrsandeep/f2cf494b2b407aaf4b904389f8fe83a3 to your computer and use it in GitHub Desktop.
Save vrsandeep/f2cf494b2b407aaf4b904389f8fe83a3 to your computer and use it in GitHub Desktop.
Simple example how to use elastic search with node.js using standard and ngram tokenizer
'use strict';
var elasticsearch = require('elasticsearch');
var log = console.log.bind(console);
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
function dropIndex() {
return client.indices.delete({
index: 'test',
});
}
function dropNgIndex() {
return client.indices.delete({
index: 'ngind',
});
}
function createIndex() {
return client.indices.create({
index: 'test',
mapping: {
house: {
name: {
type: 'string'
}
}
}
});
}
function createNgIndex() {
var settings = {
"analysis": {
"tokenizer": {
"my_ngram_tokenizer": {
"type": "nGram",
"min_gram": "2",
"max_gram": "3",
"token_chars": ["letter", "digit"]
}
},
"analyzer": {
"my_ngram_analyzer": {
"tokenizer": "my_ngram_tokenizer",
"type": "custom"
}
}
}
};
var mapping = {
"house": {
"properties": {
"name": {
"type": "string",
"term_vector": "yes",
"analyzer": "my_ngram_analyzer"
}
}
}
};
return client.indices.create({
index: 'ngind',
body: {
settings: settings,
mappings: mapping
}
});
}
function addToIndex() {
return client.index({
index: 'test',
type: 'house',
id: '1',
body: {
name: 'huhu'
}
});
}
function addToNgIndex() {
return client.index({
index: 'ngind',
type: 'house',
id: '1',
body: {
name: 'huhu'
}
});
}
function search() {
return client.search({
index: 'test',
q: 'huhu'
}).then(log);
}
function searchNg() {
return client.search({
index: 'ngind',
q: 'huhu'
}).then(log);
}
function closeConnection() {
client.close();
}
function getFromIndex() {
return client.get({
id: 1,
index: 'test',
type: 'house',
}).then(log);
}
function getFromNgIndex() {
return client.get({
id: 1,
index: 'ngind',
type: 'house',
}).then(log);
}
function waitForIndexing() {
log('Wait for indexing ....');
return new Promise(function(resolve) {
setTimeout(resolve, 2000);
});
}
return Promise.resolve()
.then(dropNgIndex)
.then(createNgIndex)
.then(addToNgIndex)
.then(getFromNgIndex)
.then(waitForIndexing)
.then(searchNg)
.then(closeConnection);
/*return Promise.resolve()
.then(dropIndex)
.then(createIndex)
.then(addToIndex)
.then(getFromIndex)
.then(waitForIndexing)
.then(search)
.then(closeConnection);
*/
@erfanyousefi
Copy link

👌🏼👌🏼 perfect ✋

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment