I want to index a .json file that includes the world's city names. I have my custom settings and mapping while I create the index. My code is:
const elasticsearchLoading = require("elasticsearch");
const indexNameLoading = "cities";
const dataJsonFile = "./cities.json";
const loadIndexclient = new elasticsearchLoading.Client({
hosts: ["http://localhost:9200"],
});
// create a new index
loadIndexclient.indices.create({
index: indexNameLoading,
}, function (error, response, status) {
if (error) {
console.log(error);
}
else {
console.log("created a new index", response);
}
});
// add 1 data to the index that has already been created
loadIndexclient.index({
index: indexNameLoading,
type: "cities_list",
body: {
name: "Content for key one"
},
}, function (error, response, status) {
console.log(response);
});
// require the array of cities that was downloaded
const cities = require(dataJsonFile);
// declare an empty array called bulk
let bulk = [];
cities.forEach((city) => {
bulk.push({
index: {
_index: indexNameLoading,
_type: "cities_list",
},
});
bulk.push(city);
});
//perform bulk indexing of the data passed
loadIndexclient.bulk({ body: bulk }, function (err, response) {
if (err) {
// @ts-ignore
console.log("Failed Bulk operation".red, err);
}
else {
// @ts-ignore
console.log("Successfully imported ", cities.length);
}
});
When I run this code, it actually runs and creates the index but the mapping and settings is created by default. But I want the add the following settings and mapping while i create the index.
"settings": {
"analysis": {
"filter": {
"my_ascii_folding": {
"type": "asciifolding",
"preserve_original": true
}
},
"analyzer": {
"turkish_analyzer": {
"tokenizer": "standard",
"filter": [
"lowercase",
"my_ascii_folding"
]
}
}
}
},
"mappings": {
"test": {
"properties": {
"name": {
"type": "string",
"analyzer": "turkish_analyzer"
}
}
}
}
Is it possible to do it?
Sure, you can pass the configuration as indices.create body
param.
Documentation: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#_indices_create
// create a new index
loadIndexclient.indices.create({
index: indexNameLoading,
body: {
"settings": {
"analysis": {
"filter": {
"my_ascii_folding": {
"type": "asciifolding",
"preserve_original": true
}
},
"analyzer": {
"turkish_analyzer": {
"tokenizer": "standard",
"filter": [
"lowercase",
"my_ascii_folding"
]
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "string",
"analyzer": "turkish_analyzer"
}
}
}
}
}, function (error, response, status) {
if (error) {
console.log(error);
}
else {
console.log("created a new index", response);
}
});