Search code examples
elasticsearch

Why elasticsearch can search with space?


const searchParams = {
        index: "products",
        body: {
          from: offset,
          size: limit,
          query: {
            bool: {
              must: {
                term: {
                  name: `*${fullTextSearch}*`,
                },
              },
            },
          },
        },
      };

I have a searchParams like this but when name= "gold ring". It didn't show any data. But if name input without space name = "gold", it work.

Why elasticsearch can search with space


Solution

  • My guess is that name is of type text, hence it is analyzed into tokens. Searching with a term query won't analyze the input text and will search for an exact value gold ring which probably no name field contains.

    If, however, you change your query to use match instead of term you should see results. And you should also remove the leading and closing wildcards:

    const searchParams = {
        index: "products",
        body: {
          from: offset,
          size: limit,
          query: {
            bool: {
              must: {
                match: {                       <---- change this
                  name: `${fullTextSearch}`,   <---- change this
                },
              },
            },
          },
        },
      };