Elasticsearch is displaying correct result only after a space

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");

            }

          }

        }

      });

  }

I am not a hundred percent sure I understood your problem, so I will repeat. Also the code you pasted has nothing to do with a search but with indexing, so I'm wondering why you put it there?

The problem seems to be that a search is only fired after you add a space, which to me translates to "I can only find words I finished typing"? Your expectation might be that also words that are not yet complete are search for.

For this, take a look at the search as you type field type

Hope this helps as a start. If not, it also makes sense to take a look at how you sent queries.

1 Like

Hello, I apprciate your effort,

the search work fin from the start let me do scenario so it be easy to understand my situation: imagine I want to search for card

once I type "c" it search fine also with "car" but once I type the complete sentence card no results come up until I enter space after like this "card ". I think the problem that the word its self not in the beginning of the whole text in indexing.

note that when I test in postman it works fine no space need, only when I search it in my website

I don't think this is a problem with elasticsearch, but rather how the app sends the query to Elasticsearch... can you shed some light which request gets sent in that case?

1 Like

This is my get request ${this.state.search_query} has the value from the user input

 axios

      .get(

        `http://localhost:9200/ncar_index/ncar/_search?q=${this.state.search_query}&size=100&sort=date:desc&analyzer=whitespace`

      )

is it possible that you are not escaping white spaces, so that only a part of that request gets sent to elasticsearch?

This shows, how the request is sent from your app, but does not show how it is really received by Elasticsearch and that might be different. This was the reason why I was explicitely asking for a failed request that was supposed to work. If this is in browser this could be done using the developer tools I guess?

1 Like

Hi, I try to log the response of this get request and this what I get

I don't know if this will help or you want, I can also use postman as tool to do the same but I know it will work there

please do not share screenshots. this forum supports markdown and thus code snippets, allowing everyone to be able to read such things. Thank you!

Check the url: field in the second... you are sending a plain whitespace as the q parameter. Can you share a request with a concrete search term or is this a bug in your application?

1 Like

I'm sorry about that, the one you see is the problem, I already pass a term a full word, but when I enter space after it get url correct

I just solve the problem and it was on my code here:

handleChange(event) {

    // console.log(event.target.value);

    this.setState({

      search_query: event.target.value,

      highlight: event.target.value,

    });

    if (this.state.search_query_drop != "") {

      // console.log("both");

      axios

        .get(

          `http://localhost:9200/ncar_index/ncar/_search?q=${event.target.value} AND ${this.state.search_query_drop}&size=100&sort=date:desc&default_operator=AND` // HERE

        )}

I change to

${event.target.value}

insted of

${this.state.search_query}

In the end I would like to thank Mr. Alexander Reelsen for his help until the end.