4

I have a MongoDb that has a collection of cars which includes fields like:

price: "49,500"
brand: "Mercedes-benz",
model: "E 400d"
power: "340 PS"
engine: "2995 cmc"
etc.

On my Springboot backend I want to create and endpoint which will return search suggestions based on the user input.

For example if the user searches for: "mer", "Mer", "Mercedes", "Mercedes benz","Nercedes"(fuzzy search N instead of M), "benz", "E400"(without spaces and missing d), "E 400"(missing d), "400d"(missing E), "E400 d" (missplaced whitespace), "E400d"( no whitespaces) and other similar use cases I want to return to the user the correct results.

My current index:

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "brand": {
        "maxGrams": 20,
        "tokenization": "edgeGram",
        "type": "autocomplete"
      },
      "model": {
        "maxGrams": 20,
        "tokenization": "edgeGram",
        "type": "autocomplete"
      },
      "power": {
        "maxGrams": 20,
        "tokenization": "edgeGram",
        "type": "autocomplete"
      }
    }
  }
}

Example java query: val collection = mongoTemplate.getCollection("cars")

    val agg = Document(
            "\$search", Document(
            "autocomplete", Document("query", searchInput)
            .append("path", "brand")
            .append("fuzzy", Document("maxEdits", 1))
    )
 )

    collection.aggregate(
            listOf(
                    agg,
                    limit(20),
                    project(fields(include("brand", "model", "power")))
            )
    )

0 Answers0