How to implement autosuggestions with gender typeahead using Elastic search and Java

226 Views Asked by At

I am trying include gender in the autosuggestions returned from backend.

Present setup : As I type in the search bar, let us say "Sh", it gives autosuggestions like shoes, shirts etc.

New requirement :

As I type in the search bar, let us say "Sh", it should return personalized autosuggestions like below based on gender in user's profile.

Example : If user is a female, return below

"shoes for women"

"shirts for women"

If user is male, return below

"shoes for men"

"shirts for men"

Can someone help me how to implement this in elastic search and java springboot.

1

There are 1 best solutions below

0
brugia On

There are several ways to implement this in Elasticsearch.

Use the completion suggester. To each entry in the completion suggestion field, add the gender as a category context. While sending requests to elasticsearch, add the gender of your signed in user to the the query context.

Simple implementation:

PUT store_item
{
  "mappings": {
    "properties": {
      "suggest": {
        "type": "completion",
        "contexts": [
          {                                 
            "name": "gender",
            "type": "category"
          }
        ]
      }
    }
  }
}

PUT store_item/_doc/1
{
  "suggest": {
   "input": [ "shoes" ],
    "contexts": {
      "gender": ["male"]                    
    }
  }
}

PUT store_item/_doc/2
{
  "suggest": {
   "input": [ "shoes" ],
    "contexts": {
      "gender": ["female"]                    
    }
  }
}

Make the Query:

POST store_item/_search?pretty
      {
    "suggest": {
      "place_suggestion": {
        "prefix": "sh",
        "completion": {
          "field": "suggest",
          "size": 10,
          "contexts": {
            "gender": [                             
              { "context": "male" }
            ]
          }
        }
      }
    }
  }

You will get all the entries that have a "Male" context and start with "sh". You can simply append the string "for men" to the end of every result, in your client application.

To implement this in Spring Boot : You need to refer to this link that highlights how to implement the Completion Suggester via the Spring Boot Api.

Medium Article shows a sample Spring Boot Implementation

Please note that you structure the index like I demoed in my answer. The exact API implementaion in Java/Spring Boot just wraps the REST API.