Search code examples
elasticsearch

elasticsearch autocomplete for some field values


I'm storing articles in elasticsearch such as this in an articles index:

{
  "title": "my title",
  "text": "article text",
  "date": "2023-11-28T00:00:00Z",
  "authors": ["author 1", "author 2"],
  "section": "article section"
}

With the following mapping:

{
  "title": { type: "text" },
  "text": { type: "text" },
  "date": { type: "date" },
  "authors": { type: "keyword" },
  "section": { type: "keyword" }

Now in the search UI of my application, I want to give the user a way to search the authors that are stored in all the documents so he can filter on them. The same with section.

Is there a way to query just the discrete values in the field on the articles index or do I need to have a separate index for the authors and sections?


Solution

  • Just found the Terms enum API that make it easy to do a prefix search on the values.

    GET /articles/_terms_enum
    {
        "field" : "authors",
        "string" : "searchterm"
    }
    

    Although @val suggestion can be used with any query, I think this is a better approach.