# Search for startsWith and contains combined with sorting

**URL:** <https://discuss.elastic.co/t/search-for-startswith-and-contains-combined-with-sorting/220323>\
**Category:** Elasticsearch\
**Created:** [February 21, 2020, 9:40am UTC](https://discuss.elastic.co/t/search-for-startswith-and-contains-combined-with-sorting/220323 "2020-02-21T09:40:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![krisbude](https://avatars.discourse-cdn.com/v4/letter/k/9e8a1a/32.png) [@krisbude](https://discuss.elastic.co/u/krisbude)\
**Post date:** [February 21, 2020, 9:40am UTC](https://discuss.elastic.co/t/search-for-startswith-and-contains-combined-with-sorting/220323/1 "2020-02-21T09:40:28Z")

</div>

Hello,

I have a query that looks like the following:

```
    {
    "sort": [
        {
            "_score": "DESC",
            "name.sort": "ASC"
        }
    ],
    "size": "250",
    "query": {
        "bool": {
            "should": [
                {
                    "match_phrase": {
                        "name": "ka"
                    }
                },
                {
                    "match_phrase": {
                        "name.prefix": {
                            "query": "ka",
                            "boost": "10.0"
                        }
                    }
                }
            ],
            "minimum_should_match": 1
        }
    }
}

```

What I try to achieve is the following. When I query for 'ka', I want my result to first contain all the documents where 'name' starts with 'ka' (sorted alphabetically) and then the documents that where 'ka' appears in the 'name' but not starts with it, also sorted alphabetically.

so the result should look like something like this:  
kabel  
kado  
kat  
daka  
podoka  
...

I hope the question is clear. Is there an easy solution for this? It seems such a common practise.  
I have tried with constant\_score... my hope was to have all the documents with startsWith a constant score of 1, and the other words that just contain a score with 0. Then I could sort first by score and the by name in order to achieve this.

Any ideas?

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [March 20, 2020, 9:40am UTC](https://discuss.elastic.co/t/search-for-startswith-and-contains-combined-with-sorting/220323/2 "2020-03-20T09:40:28Z")

</div>

Closed on March 20, 2020, 9:40am UTC

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
