使用 Elasticsearch 查询 DSL 进行过滤

编辑

使用 Elasticsearch 查询 DSL 进行过滤

编辑

可以通过在 `filter` 参数中指定标准 Elasticsearch 查询 DSL 来过滤 SQL 将其运行的结果。

resp = client.sql.query(
    format="txt",
    query="SELECT * FROM library ORDER BY page_count DESC",
    filter={
        "range": {
            "page_count": {
                "gte": 100,
                "lte": 200
            }
        }
    },
    fetch_size=5,
)
print(resp)
response = client.sql.query(
  format: 'txt',
  body: {
    query: 'SELECT * FROM library ORDER BY page_count DESC',
    filter: {
      range: {
        page_count: {
          gte: 100,
          lte: 200
        }
      }
    },
    fetch_size: 5
  }
)
puts response
const response = await client.sql.query({
  format: "txt",
  query: "SELECT * FROM library ORDER BY page_count DESC",
  filter: {
    range: {
      page_count: {
        gte: 100,
        lte: 200,
      },
    },
  },
  fetch_size: 5,
});
console.log(response);
POST /_sql?format=txt
{
  "query": "SELECT * FROM library ORDER BY page_count DESC",
  "filter": {
    "range": {
      "page_count": {
        "gte" : 100,
        "lte" : 200
      }
    }
  },
  "fetch_size": 5
}

这将返回

    author     |                name                |  page_count   | release_date
---------------+------------------------------------+---------------+------------------------
Douglas Adams  |The Hitchhiker's Guide to the Galaxy|180            |1979-10-12T00:00:00.000Z

标准查询 DSL 过滤的一个有用且不太明显的用法是通过特定的路由键搜索文档。因为 Elasticsearch SQL 不支持routing 参数,所以可以改用terms 过滤器对_routing 字段进行过滤。

resp = client.sql.query(
    format="txt",
    query="SELECT * FROM library",
    filter={
        "terms": {
            "_routing": [
                "abc"
            ]
        }
    },
)
print(resp)
response = client.sql.query(
  format: 'txt',
  body: {
    query: 'SELECT * FROM library',
    filter: {
      terms: {
        _routing: [
          'abc'
        ]
      }
    }
  }
)
puts response
const response = await client.sql.query({
  format: "txt",
  query: "SELECT * FROM library",
  filter: {
    terms: {
      _routing: ["abc"],
    },
  },
});
console.log(response);
POST /_sql?format=txt
{
  "query": "SELECT * FROM library",
  "filter": {
    "terms": {
      "_routing": ["abc"]
    }
  }
}