弹性搜索和日期范围过滤器

时间:2012-12-21 12:20:08

标签: python elasticsearch

我正在尝试使用rawes python绑定按日期过滤弹性搜索查询。如果我删除数据库,请指定datetime字段为date_optional_time,在弹性搜索数据库中插入几行,然后使用datetime上的range filter进行查询} field,我没有得到任何结果(见下文)。知道我做错了吗?

>>> result = es.delete(root_url)
>>> result = es.put(root_url+"_mapping", data={
    "tweet": {
        "properties": {
            "datetime": {
                "type": "date", 
                "format": "date_optional_time"
            },
        }
    },
})
>>> result = es.post(root_url, data={
    "datetime": "2012-12-20 12:00:00",
    "name": "freddy",
    "text": "hello world",
})
>>> result = es.post(root_url, data={
    "datetime": "2012-11-20 12:00:00",
    "name": "julie",
    "text": "welcome to the wonderful world of cooking",
})
>>> result = es.get(root_url+"_search", data={
    "query": {
        "range": {  # expect this to return the one result on 2012-12-20
            "datetime": {
                "gte":"2012-12-01", # do not append "T00:00:00"; too slow!
                "lte":"2012-12-31", # do not append "T23:59:59"; too slow! 
            }
        }
    }
})
>>> pprint.pprint(result)
{u'_shards': {u'failed': 0, u'successful': 5, u'total': 5},
 u'hits': {u'hits': [], u'max_score': None, u'total': 0},
 u'timed_out': False,
 u'took': 4}

2 个答案:

答案 0 :(得分:5)

问题显然在于我如何将日期编码为字符串(请注意字符串中的“T”)。这有效:

>>> result = es.post(root_url, data={
    "datetime": "2012-12-20T12:00:00",
    "name": "freddy",
    "text": "hello world",
})
>>> result = es.post(root_url, data={
    "datetime": "2012-11-20T12:00:00",
    "name": "julie",
    "text": "welcome to the wonderful world of cooking",
})
>>> result = es.get(root_url+"_search", data={
    "query": {
        "range": {  # expect this to return the one result on 2012-12-20
            "datetime": {
                "gte":"2012-12-01", 
                "lte":"2012-12-31",
            }
        }
    }
})

答案 1 :(得分:1)

您可以尝试使用post而不是get来启动您的请求吗? 我不知道如何工作,但在其他客户端,使用GET而不是POST时不会发送有效负载。

>>> result = es.post(root_url+"_search", data={
    "query": {
        "range": {  # expect this to return the one result on 2012-12-20
            "datetime": {
                "gte":"2012-12-01", 
                "lte":"2012-12-31",
            }
        }
    }
})

有效吗?