Home > Net >  How to apply term query with match_prefix in elasticsearch
How to apply term query with match_prefix in elasticsearch

Time:07-13

My document is below

[
{'id':1, 'name': 'sachin messi', 'description': '[email protected]', 'type': 'football', 'var':'sports'},
{'id':2, 'name': 'lionel messi', 'description': '[email protected]','type': 'soccer','var':'sports'},
{'id':3, 'name': 'sachin', 'description': 'was', 'type': 'cricket', 'var':'sports'}
]
  • I need to search on if var.keyword = sports
  • I need to highlight on it
  • It has to prefix query

DSL query is below

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "var.keyword": [
              "sports"
            ]
          }
        },
        {
          "match_phrase_prefix": {
            "name": {
              "query": "lio"
            }
          },
          "highlight": {
            "fields": {
              "name": {}
            }
          }
        }
      ]
    }
  }
}

Getting error

RequestError: RequestError(400, 'x_content_parse_exception', '[match_phrase_prefix] malformed query, expected [END_OBJECT] but found [FIELD_NAME]')

My expected out is only id:2

CodePudding user response:

Highlight schould be outside query clause and not inside query.

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "var.keyword": [
              "sports"
            ]
          }
        },
        {
          "match_phrase_prefix": {
            "name": {
              "query": "lio"
            }
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "name":{}
    }
  }
}

CodePudding user response:

You are almost there, but you need to have highlight parallel to query in your JSON, not inside the query. Correct query would be

{
    "query": {
        "bool": {
            "must": [
                {
                    "terms": {
                        "var.keyword": [
                            "sports"
                        ]
                    }
                },
                {
                    "match_phrase_prefix": {
                        "name": {
                            "query": "lio"
                        }
                    }
                }
            ]
        }
    },
    "highlight": {
        "fields": {
            "name": {}
        }
    }
}
  • Related