简体   繁体   中英

Elastic search give priority to starts with match

I am using elasticsearch 6.8 version for document indexing and I have this requirement when searching. I have created an index with the following settings.

{
  "settings": {
"number_of_shards": 3,
"number_of_replicas": 2,
"analysis": {
  "analyzer": {
    "default": {
      "type": "custom",
      "tokenizer": "icu_tokenizer"
    }
  }
}
  },
      "mappings": {
"person": {
  "properties": {
    "firstName": {
      "type": "text"
    },
    "lastName": {
      "type": "text"
    },
    "technologies": {
      "type": "nested"
    }
  }
}
  }
}

For example, I am creating 3 documents with following technologies.

  • 1st document- "technologies" :["my test technology"]
  • 2nd document - "technologies" :["test technology"]
  • 3rd document "technologies" :["tech test"]

So when search by keyword - "test", it is returning all the documents, that is correct behavior, but I want the 2nd document get priority because it starts with test*. So my requirement is to get starts with value the priority as below.

Search results should be:

  • 1st result - 2nd document - "technologies" :["test technology"] Others can be in any order
  • 1st document- "technologies" :["my test technology"]
  • 3rd document "technologies" :["tech test"]

Here is my java code for searching. I am using elasticsearch-rest-high-level-client library.

SearchRequest searchRequest = new SearchRequest("profile1"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

    QueryBuilder queryBuilder = QueryBuilders
            .boolQuery()
            .must(QueryBuilders
                    .matchQuery("technologies.name", technology));

    searchSourceBuilder.query(QueryBuilders
            .nestedQuery("technologies",
                    queryBuilder,
                    ScoreMode.Avg));

    searchRequest.source(searchSourceBuilder);

    SearchResponse response =
            client.search(searchRequest, RequestOptions.DEFAULT);

Is there something I am missing searching documents? Please help me on this. Thanks.

I managed to find more useful answers from the following links.

https://www.elastic.co/blog/starts-with-phrase-matching

https://gist.github.com/polyfractal/4704772

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM