Elasticsearch Query DSLを使用したフィルタリング

標準のElasticsearch Query DSLを使用して、フィルターパラメータにクエリを指定することで、SQLが実行する結果をフィルタリングできます。

Python

  1. resp = client.sql.query(
  2. format="txt",
  3. query="SELECT * FROM library ORDER BY page_count DESC",
  4. filter={
  5. "range": {
  6. "page_count": {
  7. "gte": 100,
  8. "lte": 200
  9. }
  10. }
  11. },
  12. fetch_size=5,
  13. )
  14. print(resp)

Ruby

  1. response = client.sql.query(
  2. format: 'txt',
  3. body: {
  4. query: 'SELECT * FROM library ORDER BY page_count DESC',
  5. filter: {
  6. range: {
  7. page_count: {
  8. gte: 100,
  9. lte: 200
  10. }
  11. }
  12. },
  13. fetch_size: 5
  14. }
  15. )
  16. puts response

Js

  1. const response = await client.sql.query({
  2. format: "txt",
  3. query: "SELECT * FROM library ORDER BY page_count DESC",
  4. filter: {
  5. range: {
  6. page_count: {
  7. gte: 100,
  8. lte: 200,
  9. },
  10. },
  11. },
  12. fetch_size: 5,
  13. });
  14. console.log(response);

Console

  1. POST /_sql?format=txt
  2. {
  3. "query": "SELECT * FROM library ORDER BY page_count DESC",
  4. "filter": {
  5. "range": {
  6. "page_count": {
  7. "gte" : 100,
  8. "lte" : 200
  9. }
  10. }
  11. },
  12. "fetch_size": 5
  13. }

次のように返されます:

テキスト

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

標準のQuery DSLフィルタリングの便利であまり明白でない使用法は、特定のルーティングキーでドキュメントを検索することです。Elasticsearch SQLはroutingパラメータをサポートしていないため、termsフィルタを_routingフィールドに指定できます代わりに:

Python

  1. resp = client.sql.query(
  2. format="txt",
  3. query="SELECT * FROM library",
  4. filter={
  5. "terms": {
  6. "_routing": [
  7. "abc"
  8. ]
  9. }
  10. },
  11. )
  12. print(resp)

Ruby

  1. response = client.sql.query(
  2. format: 'txt',
  3. body: {
  4. query: 'SELECT * FROM library',
  5. filter: {
  6. terms: {
  7. _routing: [
  8. 'abc'
  9. ]
  10. }
  11. }
  12. }
  13. )
  14. puts response

Js

  1. const response = await client.sql.query({
  2. format: "txt",
  3. query: "SELECT * FROM library",
  4. filter: {
  5. terms: {
  6. _routing: ["abc"],
  7. },
  8. },
  9. });
  10. console.log(response);

Console

  1. POST /_sql?format=txt
  2. {
  3. "query": "SELECT * FROM library",
  4. "filter": {
  5. "terms": {
  6. "_routing": ["abc"]
  7. }
  8. }
  9. }