havij
havij

Reputation: 1170

Using `MatchPhrasePrefix` in query DSL of Elasticsearch

I am new to Elasticsearch.

Can someone please explain why this search (NEST 6):

var searchResponse1 = this.elasticClient.Search<dynamic>(
    s => s.AllTypes().AllIndices().IgnoreUnavailable().Size(100).From(0)
        .Query(q => q.Bool(b => b.Must(m => m.SimpleQueryString(c => c.Query("query"))))));

correctly results in the following request (I got this using Fiddler):

POST https://someUrl.com/_search?pretty=true&error_trace=true&typed_keys=true&ignore_unavailable=true HTTP/1.1
{
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "simple_query_string": {
            "query": "query"
          }
        }
      ]
    }
  },
  "size": 100
}

But both of the following searches for 'MatchPhrasePrefix':

var searchResponse2 = this.elasticClient.Search<dynamic>(
    s => s.AllTypes().AllIndices().IgnoreUnavailable().Size(100).From(0)
        .Query(q => q.Bool(b => b.Must(m => m.MatchPhrasePrefix(c => c.Query("query"))))));

var searchResponse3 = this.elasticClient.Search<dynamic>(
    s => s.AllTypes().AllIndices().IgnoreUnavailable().Size(100).From(0)
        .Query(q => q.MatchPhrasePrefix(p => p.Query("query"))));

result in:

POST https://someUrl.com/_search?pretty=true&error_trace=true&typed_keys=true&ignore_unavailable=true HTTP/1.1
{
  "from": 0,
  "size": 100
}

What am I missing here?

Upvotes: 0

Views: 200

Answers (1)

Russ Cam
Russ Cam

Reputation: 125498

MatchPhrasePrefix query must also specify a field to target. For example

var searchResponse2 = client.Search<dynamic>(s => s
    .AllTypes()
    .AllIndices()
    .IgnoreUnavailable()
    .Size(100)
    .From(0)
    .Query(q => q
        .Bool(b => b
            .Must(m => m
                .MatchPhrasePrefix(c => c
                    .Field("some_field") // <-- target the "some_field" field
                    .Query("query")
                )
            )
        )
    )
);

which results in the query

POST /_search
{
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase_prefix": {
            "some_field": {
              "query": "query"
            }
          }
        }
      ]
    }
  },
  "size": 100
}

Without specifying the field, the query is considered conditionless in the client, and will be omitted from the response. There's an issue to discuss whether conditionless queries should be removed in the next major version.

Upvotes: 1

Related Questions