0
votes

Using Elasticsearch Nest Client to search for company name store in Elasticsearch. Here is sample of my queryExtentions.

I want to change it to make sure when I search for "Starbucks", it should only return record starting with letter "Starbucks". Currently it is rerurning all the records where it has "StarBucks". Based on documentation, I need to search on "Keyword" filed in order to get the result. Need sample code to how to achieve this.

****Elastic Search Index Column"

             "name": {
                                    "type": "text",
                                    "fields": {
                                        "keyword": {
                                            "type": "keyword",
                                            "ignore_above": 256
                                        }
                                    }
                                }

Code* var escapedSearchTerm = ElasticsearchQueryExtensions.EscapeQuery(companyName); return new QueryContainerDescriptor().Bool(b => b.Must(mu => mu .QueryString(qs => qs .AllowLeadingWildcard(true) .AnalyzeWildcard(true) .Fields(f => f.Field(s => s.Company.Name).Field(s => s.Organization.CommonName)) .Query(escapedSearchTerm) )));

1

1 Answers

1
votes

I am not familiar with Elastic Search Nest Client, but in JSON format you can implement search with functionality using prefix query

Adding a working example with index data,mapping,search query and search result

Index Mapping:

{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "keyword",
          "filter": "lowercase"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "my_analyzer"
      }
    }
  }
}

Index Data:

{
    "name":"Starbucks is a American multinational chain of coffeehouses"
}
{
    "name":"coffee at Starbucks"
}

Search Query:

{
  "query": {
    "prefix": {
      "name": {
        "value": "Starbucks",
        "case_insensitive": true    // this param was introduced in 7.10.0
      }
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "67424740",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "name": "Starbucks is a American multinational chain of coffeehouses"
        }
      }
    ]