使用Python调用ElasticSearch添加范围限制查询时返回400错误
Ah, I’ve run into this exact issue before! The most common cause of that 400 Bad Request error when adding a range filter is a malformed bool clause in your query. Let me break it down:
Your original working query uses a single filter in the must field (a dictionary), but when you want to combine multiple filters (like your existing terms check plus a new range restriction), you need to wrap those filters in an array instead of keeping them as a single object.
Original Working Query (Single Filter)
This works because must is a single filter entry:
{ 'query': { 'constant_score': { 'filter': { 'bool': { 'must': { 'terms': {'id.keyword': ['d42bdc8a-a38b-43fa-9283-13b5e5c08c6e']} } } } } } }
Corrected Query (With Range Filter)
When adding your range filter, rewrite the must field as an array containing both your original terms filter and the new range condition. Here’s an example (I’ll use a date field created_at for illustration—swap this with your actual field name):
{ 'query': { 'constant_score': { 'filter': { 'bool': { 'must': [ {'terms': {'id.keyword': ['d42bdc8a-a38b-43fa-9283-13b5e5c08c6e']}}, {'range': {'created_at': {'gte': '2024-01-01', 'lte': '2024-12-31'}}} ] } } } } }
Extra Checks to Ensure Success
- Double-check your field type: Make sure the field you’re applying the range filter to is a numeric or date type—you can’t run range queries on keyword/text fields unless they’re formatted correctly.
- Look at the full error response: Elasticsearch’s 400 error usually includes a specific reason (like "expected array but found object"). Print the error details from your Python code to confirm if this is the exact issue.
- Test in Kibana Dev Tools: Paste your query there first—it’ll highlight syntax errors in real-time, making it easier to fix before moving back to Python.
Content of the question originates from Stack Exchange, question author Inkidu616

