3

I'm setting up a project with node (v 12.4.0) and elasticsearch (7.4.0) using the official module.

I'm attempting to search using

import { Client, RequestParams, ApiResponse } from '@elastic/elasticsearch'

const client = new Client({ node: 'http://localhost:9200' })
const params: RequestParams.Search = { index: 'doc', body: { query: { match: { title: "castle" } } } };
const response: ApiResponse = await client.search(params);

This gives a 200 response, but no results.

Attempting the same thing using Postman returns the 1 result.

POST http://localhost:9200/doc/_search
{
    "query": {
        "match": { "title": "castle" }
    }
}

I'm not having any luck figuring out why the search function is not working. I've also tested get, add, and delete, which all work.

To create the index, I used:

await client.indices.create({ index: "doc" });

To add a document, I use:

await client.index({
    index: 'doc',
    body: {
        title: "Castle Title",
        body: "This is text that is not the title."
    }
});

What am I doing wrong?

1 Answer 1

2

I've tested this and it works, the only thing is that elasticsearch is near real-time searchable. You need to wait 1 second before the document becomes searchable. Basically, if you are running a test or something, where you save the record just before searching you need to either:

  1. wait for 1 second before searching
  2. trigger a manual refresh https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html
  3. wait for it to be refreshed when saving https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-refresh.html
Sign up to request clarification or add additional context in comments.

1 Comment

This was the problem. I have the tests setup to clear the db by deleting and re-creating the index. Adding await client.indices.refresh({ index: "doc" }); fixes everything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.