ElasticSearch按更多条件排序

66bbxpm5  于 2023-01-12  发布在  ElasticSearch
关注(0)|答案(2)|浏览(152)

我有一个简单数据的索引,我必须过滤和排序它像这样:
记录是这样的:

{
"name": "Product ABC variant XYZ subvariant JKL",
"date": "2023-01-03T10:34:39+01:00"
}

我在搜索名字,它在哪里:“产品FGH
1.获取完全匹配的记录(字段名),并按日期(字段日期)对它们进行排序DESC
1.如果在1)中没有找到任何记录,或者如果没有精确匹配,但是有相似的记录,则其余记录按默认分数排序。
有没有可能在一个ElasticSearch请求中完成它?它在整个查询中应该是什么样子?
谢谢

g9icjywg

g9icjywg1#

你正在寻找的是运行Elasticsearch查询的基础上的条件,这是不可能在一个单一的查询,你需要先火第一个查询,如果它不返回任何命中,你需要火第二个.

a0zr77ik

a0zr77ik2#

使用script_query,你可以按照自己的意愿进行操作。将日期转换为毫秒,并将其分配给"_score"字段以进行精确匹配。对于非精确匹配,你可以简单地返回_score字段
1.对于精确匹配,将按日期字段desc排序。
1.对于非精确匹配,将按_score字段排序
例如:

    • Map:**
{
  "mappings": {
    "properties": {
      "name" : {"type": "keyword"},
      "date" : {"type": "date", "format": "yyyy-MM-dd HH:mm:ss"}
    }
  }
}
    • 插入:**
PUT func/_doc/1
{
  "name" : "Product ABC variant XYZ subvariant JKL",
  "date" : "2023-01-03 10:34:39"
}

PUT func/_doc/2
{
  "name" : "Product ABC variant XYZ subvariant JKL",
  "date" : "2022-12-03 10:33:39"
}

PUT func/_doc/3
{
  "name" : "Product ABC",
  "date" : "2022-11-03 10:33:39"
}

PUT func/_doc/4
{
  "name" : "Product ABC",
  "date" : "2023-01-03 10:33:39"
}
    • 查询:**
GET /func/_search
{
  "query": {
    "script_score": {
      "query": {
        "match_all": {}
    },
      "script": {
        "source": "if (doc['name'].value == params.search_term) { return doc['date'].value.toInstant().toEpochMilli(); } else return _score",
        "params": {
          "search_term": "Product ABC"
        }
      }
    }
  }
}
    • 输出:**
{
  "took": 29,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 4,
      "relation": "eq"
    },
    "max_score": 1672742040000,
    "hits": [
      {
        "_index": "func",
        "_id": "4",
        "_score": 1672742040000,
        "_source": {
          "name": "Product ABC",
          "date": "2023-01-03 10:33:39"
        }
      },
      {
        "_index": "func",
        "_id": "3",
        "_score": 1667471640000,
        "_source": {
          "name": "Product ABC",
          "date": "2022-11-03 10:33:39"
        }
      },
      {
        "_index": "func",
        "_id": "1",
        "_score": 1,
        "_source": {
          "name": "Product ABC variant XYZ subvariant JKL",
          "date": "2023-01-03 10:34:39"
        }
      },
      {
        "_index": "func",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "Product ABC variant XYZ subvariant JKL",
          "date": "2022-12-03 10:33:39"
        }
      }
    ]
  }
}

相关问题