【问题标题】:Is there a way to translate SQL that includes UNION + TOP + ORDER BY to Elasticsearch DSL有没有办法将包含 UNION + TOP + ORDER BY 的 SQL 转换为 Elasticsearch DSL
【发布时间】:2021-06-16 11:45:48
【问题描述】:

我是 ElasticSearch 的新手,我想知道是否有办法将以下 SQL 转换为 Elasticsearch DSL:

SELECT TOP 3 1 as Priority, * FROM Customers where ContactName like 'A%' 
UNION
SELECT TOP 3 2 as Priority, * FROM Customers where NOT(ContactName like 'A%')
ORDER BY Priority, ContactName ASC;

另外,我想知道是否有一个选项可以将此查询扩展到 SQL 不支持的内容...以不同的顺序对每个查询进行排序(据我所知无法在SQL),所以从概念上讲,SQL 看起来像:

(SELECT TOP 3 1 as Priority, * FROM Customers where ContactName like 'A%'ORDER BY Priority, City ASC) 
UNION
(SELECT TOP 3 2 as Priority, * FROM Customers where NOT(ContactName like 'A%')
ORDER BY Priority, ContactName ASC);

注意:我更喜欢将所有响应对象作为一个响应来获取,而不是作为与特定源查询相关联的响应列表(类似于我将从上面的 SQL 语句中获得的响应)。

【问题讨论】:

    标签: elasticsearch dsl


    【解决方案1】:

    更好的办法是给你两个查询或msearch

    替代方法是使用terms aggregation

    {
      "size": 0, 
      "aggs": {
        "cities": {
          "terms": {
            "field": "city-name.keyword",
            "size": 10,
            "order": {
              "_term": "asc"
            }
          },
          "aggs": {
            "starts_with_A": {
              "terms": {
                "field": "customer-name.keyword",
                "include": "A.*",
                "size": 5
              }
            }
          }
        },
        "starts_Not_with_A": {
          "terms": {
            "field": "customer-name.keyword",
            "exclude": "A.*",
            "size": 10,
            "order": {
              "_term": "asc"
            }
          }
        }
      }
    }
    

    【讨论】:

    • 非常感谢!确实,msearch 给了我正确的结果
    • 谢谢@jaspreet,1) 我如何将其标记为已回答? 2) 有没有办法将所有答案作为一个对象列表(使用布尔/应该或其他机制)?
    • @Shai 应该不起作用,因为大小和排序将适用于整个查询而不是单个块。您必须在客户端合并
    猜你喜欢
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2010-10-04
    • 2011-09-17
    • 2022-11-30
    相关资源
    最近更新 更多