如何解决如果状态为true,Elasticsearch bool查询按日期排序
我在Elasticsearch索引中有一个如下所示的JSON文件。如果广告没有过期并且状态为true,我需要对数据进行排序,然后将它们排序为desc。我该如何实现?
我尝试使用end_date排序,但是没有用。另外,我需要显示所有end_date过期的过期数据。
advertisement = [
{
"id": 1,"name": "test","status": True,"start_date": "2020-08-09","end_date": "2020-09-09",},{
"id": 2,"name": "test2","status": False,"end_date": "2020-08-09",}]
这是我的弹性搜索方法。
def elastic_search(category=None):
client = Elasticsearch(host="localhost",port=9200)
query_all = {
'size': 10000,'query': {
"bool": {
"filter": [
{
"match": {
"name": "test"
}
}]
},"sort": [
{
"end_date": {
"type": "date","order": 'desc'
}
}
]
}
resp = client.search(
index="my-index",body=query_all
)
return resp
这是我的回复
http:// localhost:9200 / my-index / _search
{
"took":96,"timed_out":false,"_shards":{
"total":5,"successful":5,"skipped":0,"failed":0
},"hits":{
"total":36,"max_score":1.0,"hits":[
{
"_index":"my-index","_type":"doc","_id":"52","_score":1.0,"_source":{
"id": 1,}
},{
"_index":"my-index","_id":"60","name": "English test","_id":"40","name": "Designw test","status": false,"_id":"41","name": "Designw New","_id":"59","_id":"62",}
}
]
}
}
这是我的映射http:// localhost:9200 / my-index / _mapping响应。
"my-index":{
"mappings":{
"_doc":{
"properties":{
"address":{
"properties":{
"name":{
"type":"text","fields":{
"keyword":{
"type":"keyword","ignore_above":256
}
}
},"start_date":{
"type":"text","end_date":{
"type":"text","id":{
"type":"long"
},"status":{
"type":"text","ignore_above":256
}
}
}
}
}
}
}
}
}
}
解决方法
关于映射的两件事:
- 在您的实际文档中找不到一个
address
字段。删除它。 - 您的日期应该使用
date
数据类型正确映射。
正确的映射如下:
{
"properties":{
"end_date":{
"type":"date","format":"yyyy-MM-dd"
},"start_date":{
"type":"date",//...other properties
}
}
一旦映射正确,此查询将查找所有具有真实状态的未过期广告,并按运行时间最长的顺序进行排序:
{
"query": {
"bool": {
"must": [
{
"range": {
"end_date": {
"gt": "now"
}
}
},{
"term": {
"status": {
"value": true
}
}
}
]
}
},"sort": [
{
"end_date": {
"order": "desc"
}
}
]
}
或者,如果您要查找过期的,请将gt
更改为lt
,代表less-than。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。