首页 > 解决方案 > Elasticsearch query: syntax for range restriction gives 400

问题描述

I'm using python to communicate with an ElasticSearch server. I'm using the elasticsearch package, and I'm formatting queries and feeding them to the search function in the body parameter.

Sending queries worked just fine. For example, this query works:

{'query': {'constant_score': {'filter': {'bool': {'must': {'terms': {'id.keyword': ['d42bdc8a-a38b-43fa-9283-13b5e5c08c6e']}}}}}}}

I now want to restrict the range, so I add a little segment (indentation for clarity):

{'query': 
    {'constant_score': 
        {'filter': 
            {'bool': 
                {'must': 
                    {'range': 
                        {'startTime': 
                            {'format': "yyyy-MM-dd'T'HH:mm:ss.SSS",
                             'gte': '2018-01-20T17:19:43.393',
                             'lte': '2018-04-01T17:19:43.393'}
                        },
                     'terms':
                         {'id.keyword':
                             ['d42bdc8a-a38b-43fa-9283-13b5e5c08c6e']
                         }
                     }
                 }
             }
         }
     }
}

A query that looks identical (to me) worked in R. I'm getting a status 400 though (bad request). Does anyone see what the problem is?

标签: pythonrestelasticsearch

解决方案


你快到了,这是正确的查询:

{'query': 
    {'constant_score': 
        {'filter': 
            {'bool': 
                {'must': [
                    {'range': 
                        {'startTime': 
                            {'format': "yyyy-MM-dd'T'HH:mm:ss.SSS",
                             'gte': '2018-01-20T17:19:43.393',
                             'lte': '2018-04-01T17:19:43.393'}
                        }
                    },
                    {
                     'terms':
                         {'id.keyword':
                             ['d42bdc8a-a38b-43fa-9283-13b5e5c08c6e']
                         }
                    }
                 ]
               }
             }
         }
     }
}

推荐阅读