我正在尝试在 Elasticsearch 中的日期字段上实现部分搜索。例如,如果 startDate 存储为“2019-08-28”,我应该能够在仅查询“2019”或“2019-08”或“2019-0”时检索相同的内容。
对于其他领域我正在这样做:
{
"simple_query_string": {
"fields": [
"customer"
],
"query": "* Andrew *",
"analyze_wildcard": "true",
"default_operator": "AND"
}}
它完美地适用于文本字段,但同样不适用于日期字段。
这是映射: {"mappings":{"properties":{"startDate":{"type":"date"}}}}
有什么方法可以实现这一点,无论是改变映射还是其他查询方法?我还发现这个讨论与弹性中的部分日期有关,不确定它是否很相关,但这里是:
最佳答案
摘自ES-Docs
Internally, dates are converted to UTC (if the time-zone is specified) and stored as a long number representing milliseconds-since-the-epoch.
无法像在文本字段上那样进行搜索。但是,我们可以告诉 ES 将日期字段同时索引为日期和文本。例如
将日期字段索引为多种类型:
PUT sample
{
"mappings": {
"properties": {
"my_date": {
"type": "date",
"format": "year_month_day",//<======= yyyy-MM-dd
"fields": {
"formatted": {
"type": "text", //<========= another representation of type TEXT, can be accessed using my_date.formatted
"analyzer": "whitespace" //<======= whitespace analyzer (standard will tokenized 2020-01-01 into 2020,01 & 01)
}
}
}
}
}
}
POST dates/_doc
{
"date":"2020-01-01"
}
POST dates/_doc
{
"date":"2019-01-01"
}
使用通配符查询进行搜索:如果需要,您甚至可以在索引时使用 n-gram 来加快搜索速度。
GET dates/_search
{
"query": {
"wildcard": {
"date.formatted": {
"value": "2020-0*"
}
}
}
}
关于elasticsearch - 在elasticsearch中对日期字段进行部分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64372856/