I build react app the has search bar using elasticsearch, but the problem is when I search in my search bar earthier I have to write the word not complete or I write as complete word but after I click space.
for example: if I want to search for card eathier I have to write car or card_ (cosider _ space)
can you please help me?
this is the code that create the index and load the josn data (nodejs code here)
//initialize the client
const { Client } = require("@elastic/elasticsearch");
const client = new Client({ node: "http://localhost:9200" });
// to read json files
var fs = require("fs");
/ Start reading the json file
fs.readFile("DocRes.json", { encoding: "utf-8" }, function (err, data) {
if (err) {
throw err;
}
// Build up a giant bulk request for elasticsearch.
bulk_request = data.split("\n").reduce(function (bulk_request, line) {
var obj, ncar;
try {
obj = JSON.parse(line);
} catch (e) {
console.log("Done reading 1");
return bulk_request;
}
// Rework the data slightly
ncar = {
id: obj.id,
name: obj.name,
summary: obj.summary,
image: obj.image,
approvetool: obj.approvetool,
num: obj.num,
date: obj.date,
};
bulk_request.push({
index: { _index: "ncar_index", _type: "ncar", _id: ncar.id },
});
bulk_request.push(ncar);
return bulk_request;
}, []);
// A little voodoo to simulate synchronous insert
var busy = false;
var callback = function (err, resp) {
if (err) {
console.log(err);
}
busy = false;
};
// Recursively whittle away at bulk_request, 1000 at a time.
var perhaps_insert = function () {
if (!busy) {
busy = true;
client.bulk(
{
body: bulk_request.slice(0, 1000),
},
callback
);
bulk_request = bulk_request.slice(1000);
console.log(bulk_request.length);
}
if (bulk_request.length > 0) {
setTimeout(perhaps_insert, 100);
} else {
console.log("Inserted all records.");
}
};
perhaps_insert();
});
here the code for search in react
handleChange(event) {
console.log(event.target.value);
this.setState({
search_query: event.target.value,
});
axios
.get(
`http://localhost:9200/ncar_index/ncar/_search?q=${this.state.search_query}&size=100&sort=date:desc&analyzer=whitespace`
)
.then((resp) => {
if (event?.target?.value == "") {
// if the searchbar empty set default cards
this.setState({
NCARMap: this.state.NCARMapAS,
noPlaceFound: false,
});
} else {
if (resp.data.hits.hits.length > 0 && this.state.search_query != "") {
// go for new search when there is a result and searchbar not empty
this.setState({
NCARMap: resp.data.hits.hits,
noPlaceFound: false,
});
console.log("Secssufal");
} else {
// if there is no result make noplacefount true to print a message and show no card
if (resp.data.hits.hits.length == 0) {
this.setState({ noPlaceFound: true });
console.log("Length is equal 0");
}
}
}
});
}