当前位置:   article > 正文

Elasticsearch:Elasticsearch SQL介绍及实例(二)_ztod

ztod

在之前的文章 “Elasticsearch:Elasticsearch SQL 介绍及实例” 里,我们简要介绍了新的 Elasticsearch SQL 功能以及 _translate API。 这篇特定的文章通过探索更复杂的功能来继续该系列。如果你还没准备好自己的数据,请先阅读我前面指出来的文章。

复杂的例子和 Elasticsearch 的优点

Grouping

Elasticsearch 的聚合框架(能够汇总数十亿个数据点)代表了堆栈中最强大和最受欢迎的功能之一。 从功能的角度来看,它与 SQL 中的 GROUP BY 运算符具有自然的等效性。 除了提供一些 GROUP BY 功能的示例外,我们还将再次使用 translation API 来显示等效的聚合。

找到飞往伦敦的每个来源目的地国家的平均飞行时间。 按照国家的字母顺序排列。

  1. sql> SELECT AVG(FlightTimeHour) Avg_Flight_Time, OriginCountry FROM flights GROUP BY OriginCountry ORDER BY OriginCountry LIMIT 5;
  2. Avg_Flight_Time | OriginCountry
  3. ------------------+---------------
  4. 9.342180244924574 |AE
  5. 13.49582274385201 |AR
  6. 4.704097126921018 |AT
  7. 15.081367354940724|AU
  8. 7.998943401875511 |CA

检查此查询的 DSL 将显示 “composite aggregation” 的使用。

  1. GET flights/_search
  2. {
  3. "size": 0,
  4. "_source": false,
  5. "stored_fields": "_none_",
  6. "aggs": {
  7. "groupby": {
  8. "composite": {
  9. "size": 1000,
  10. "sources": [
  11. {
  12. "3471": {
  13. "terms": {
  14. "field": "OriginCountry.keyword",
  15. "order": "asc"
  16. }
  17. }
  18. }
  19. ]
  20. },
  21. "aggs": {
  22. "3485": {
  23. "avg": {
  24. "field": "FlightTimeHour"
  25. }
  26. }
  27. }
  28. }
  29. }
  30. }

这里使用的是 composite aggregation。它可以帮我实现在 aggregration 里的 scroll 功能。如果大家对这个不是很明白的话,请参阅我的另外一篇文章 “在 Elasticsearch 中的 Composite Aggregation”。上面查询的结果返回的是:

  1. {
  2. "took" : 21,
  3. "timed_out" : false,
  4. "_shards" : {
  5. "total" : 1,
  6. "successful" : 1,
  7. "skipped" : 0,
  8. "failed" : 0
  9. },
  10. "hits" : {
  11. "total" : {
  12. "value" : 10000,
  13. "relation" : "gte"
  14. },
  15. "max_score" : null,
  16. "hits" : [ ]
  17. },
  18. "aggregations" : {
  19. "groupby" : {
  20. "after_key" : {
  21. "3471" : "ZA"
  22. },
  23. "buckets" : [
  24. {
  25. "key" : {
  26. "3471" : "AE"
  27. },
  28. "doc_count" : 385,
  29. "3485" : {
  30. "value" : 9.342180244924574
  31. }
  32. },
  33. {
  34. "key" : {
  35. "3471" : "AR"
  36. },
  37. "doc_count" : 258,
  38. "3485" : {
  39. "value" : 13.49582274385201
  40. }
  41. },
  42. {
  43. "key" : {
  44. "3471" : "AT"
  45. },
  46. "doc_count" : 120,
  47. "3485" : {
  48. "value" : 4.704097126921018
  49. }
  50. },
  51. {
  52. "key" : {
  53. "3471" : "AU"
  54. },
  55. "doc_count" : 518,
  56. "3485" : {
  57. "value" : 15.081367354940724
  58. }
  59. },
  60. ...

我们还可以使用函数对 select 中定义的别名字段进行分组。

查找每月航班的数量和平均飞行时间。

  1. POST /_sql?format=txt
  2. {
  3. "query":"SELECT COUNT(*), MONTH_OF_YEAR(timestamp) AS month_of_year, AVG(FlightTimeHour) AS Avg_Flight_Time FROM flights GROUP BY month_of_year"
  4. }

上面的查询结果是:

  1. COUNT(*) | month_of_year | Avg_Flight_Time
  2. ---------------+---------------+-----------------
  3. 5687 |4 |8.578573065474027
  4. 7372 |5 |8.472684454688286

Composite aggregation 的使用具有一个主要优点-可以确保 GROUP BY 实现甚至可扩展用于高基数字段,并提供一种机制来流传输特定聚合的所有存储桶,类似于滚动对文档所做的操作。 这也确保了实现不会像使用术语聚合那样遭受相同的内存限制。 我们可以通过如下命令来翻译相对应的 composite aggregation:

  1. POST /_sql/translate
  2. {
  3. "query":"SELECT AVG(FlightTimeHour) Avg_Flight_Time, OriginCountry FROM flights GROUP BY OriginCountry ORDER BY Avg_Flight_Time"
  4. }

相应的翻译的结果是:

  1. {
  2. "size" : 0,
  3. "_source" : false,
  4. "stored_fields" : "_none_",
  5. "aggregations" : {
  6. "groupby" : {
  7. "composite" : {
  8. "size" : 1000,
  9. "sources" : [
  10. {
  11. "bee1e422" : {
  12. "terms" : {
  13. "field" : "OriginCountry.keyword",
  14. "missing_bucket" : true,
  15. "order" : "asc"
  16. }
  17. }
  18. }
  19. ]
  20. },
  21. "aggregations" : {
  22. "803ccc93" : {
  23. "avg" : {
  24. "field" : "FlightTimeHour"
  25. }
  26. }
  27. }
  28. }
  29. }
  30. }

Filtering Groups

为了过滤组,我们可以利用 HAVING 运算符,该运算符也可以利用 SELECT 子句中指定的别名。 这对于某些 SQL 专家可能是不寻常的,因为在基于 RDBMS 的实现中通常是不可能的,因为 SELECT 是在 HAVING 之后执行的。 在这里,HAVING 子句使用的是在执行阶段声明的别名。 但是,我们的分析器足够聪明,可以向前看,并选择要在 HAVING 中使用的声明。

找到每个出发城市的航班数量,平均飞行距离和第95个百分位,平均距离在3000到4000英里之间。

  1. sql> SELECT OriginCityName, ROUND(AVG(DistanceKilometers)) avg_distance, COUNT(*) c, ROUND(PERCENTILE(DistanceKilometers,95)) AS percentile_distance FROM flights GROUP BY OriginCityName HAVING avg_distance BETWEEN 3000 AND 4000;
  2. OriginCityName | avg_distance | c |percentile_distance
  3. ---------------+---------------+---------------+-------------------
  4. Verona |3078.0 |120 |7927.0
  5. Vienna |3596.0 |120 |7436.0
  6. Xi'an |3842.0 |114 |7964.0

为了实现 HAVING 功能,SQL Elasticsearch 利用 Bucket Selector 管道聚合,使用参数化的 painless 脚本过滤值。 请注意下面的内容,将自动为聚合选择 OriginCityName 字段的关键字变体,而不是尝试使用标准文本变体,这可能由于未启用字段数据而失败。 avg 和 percentile 指标聚合提供与 SQL 变体等效的功能。

  1. POST /_sql/translate
  2. {
  3. "query": """
  4. SELECT OriginCityName, ROUND(AVG(DistanceKilometers)) avg_distance, COUNT(*) c, ROUND(PERCENTILE(DistanceKilometers,95)) AS percentile_distance FROM flights GROUP BY OriginCityName HAVING avg_distance BETWEEN 3000 AND 4000
  5. """
  6. }

上面翻译的结果是:

  1. {
  2. "size" : 0,
  3. "_source" : false,
  4. "stored_fields" : "_none_",
  5. "aggregations" : {
  6. "groupby" : {
  7. "composite" : {
  8. "size" : 1000,
  9. "sources" : [
  10. {
  11. "ff6ca116" : {
  12. "terms" : {
  13. "field" : "OriginCityName.keyword",
  14. "missing_bucket" : true,
  15. "order" : "asc"
  16. }
  17. }
  18. }
  19. ]
  20. },
  21. "aggregations" : {
  22. "b54e054" : {
  23. "avg" : {
  24. "field" : "DistanceKilometers"
  25. }
  26. },
  27. "7171c519" : {
  28. "percentiles" : {
  29. "field" : "DistanceKilometers",
  30. "percents" : [
  31. 95.0
  32. ],
  33. "keyed" : true,
  34. "tdigest" : {
  35. "compression" : 100.0
  36. }
  37. }
  38. },
  39. "having.8bcff206" : {
  40. "bucket_selector" : {
  41. "buckets_path" : {
  42. "a0" : "b54e054",
  43. "a1" : "b54e054"
  44. },
  45. "script" : {
  46. "source" : "InternalSqlScriptUtils.nullSafeFilter(InternalSqlScriptUtils.and(InternalSqlScriptUtils.gte(InternalSqlScriptUtils.round(params.a0,params.v0), params.v1), InternalSqlScriptUtils.lte(InternalSqlScriptUtils.round(params.a1,params.v2), params.v3)))",
  47. "lang" : "painless",
  48. "params" : {
  49. "v0" : null,
  50. "v1" : 3000,
  51. "v2" : null,
  52. "v3" : 4000
  53. }
  54. },
  55. "gap_policy" : "skip"
  56. }
  57. }
  58. }
  59. }
  60. }
  61. }

文字运算符和相关性

与传统的 RDBMS 相比,Elasticsearch 作为搜索引擎的独特功能之一是它能够通过使用相关性计算来考虑文本数据的属性,从而对匹配进行评分,而不仅仅是简单的“是/否”。扩展 SQL 语法使我们可以公开此功能,并且超越了传统 RDBMS 可能提供的功能。

因此,我们引入了两个新的运算符:QUERY 和 MATCH。对于熟悉 Elasticsearch 的人员,这些等效于基础的 multi_match 和 query_string 运算符。 Kibana 的用户将熟悉 query_string 运算符的行为,因为它用于为默认搜索栏提供动力。它提供了智能的解析功能,并允许自然的语言风格的查询。这两个运算符的详细信息不在本博客的讨论范围之内,但是 权威的指南条目 对这些概念进行了很好的介绍。

例如,请考虑以下内容:

查找按日期排序的2018-06-06至2018-06-17之间所有往返Kastrup机场的延迟航班。

Edmonton一座服务于加拿大阿尔伯塔省埃德蒙顿市及周边地区的国际机场,全称是“Edmonton International Airport”。 使用 QUERY 运算符,我们只需搜索 Edmonton。

  1. sql> SELECT timestamp, FlightNum, OriginCityName, DestCityName FROM flights WHERE QUERY('Edmonton') AND FlightDelay=true AND timestamp > '2018-06-20' AND timestamp < '2020-06-27' ORDER BY timestamp;
  2. timestamp | FlightNum |OriginCityName | DestCityName
  3. ------------------------+---------------+---------------+---------------
  4. 2020-04-14T22:19:48.000Z|1C0ZWE9 |Cologne |Edmonton
  5. 2020-04-16T04:55:07.000Z|48DVRFT |Edmonton |Torino
  6. 2020-04-16T19:17:14.000Z|14KTFQB |Edmonton |Oslo
  7. 2020-04-19T06:25:17.000Z|EN9FHUD |Detroit |Edmonton
  8. 2020-04-21T20:35:16.000Z|H5Y0MJK |Edmonton |Palermo
  9. 2020-04-23T02:03:18.000Z|KCNMKVI |Edmonton |Erie
  10. 2020-04-23T09:34:02.000Z|XH9H5H3 |Paris |Edmonton
  11. 2020-04-25T04:22:28.000Z|GJTJ47T |Edmonton |Bangalore
  12. 2020-04-26T13:23:09.000Z|PPZN0Y7 |Edmonton |Indianapolis
  13. 2020-04-27T00:20:57.000Z|IKFEGFL |Edmonton |Warsaw
  14. 2020-04-27T22:11:51.000Z|300JHDQ |Green Bay |Edmonton
  15. 2020-04-30T15:02:33.000Z|PK1ETRA |Rome |Edmonton
  16. 2020-05-01T17:52:50.000Z|A2NRDPQ |Edmonton |Manchester
  17. 2020-05-01T22:19:38.000Z|S9AY152 |Edmonton |Buenos Aires
  18. 2020-05-03T15:52:05.000Z|PJXXO9P |Edmonton |Buenos Aires
  19. 2020-05-05T09:00:47.000Z|QTPABGR |Edmonton |Jeju City
  20. 2020-05-05T18:49:49.000Z|YVEUZNO |Edmonton |Ottawa
  21. 2020-05-06T12:46:16.000Z|TCPDEBY |Edmonton |Bergamo
  22. 2020-05-07T00:00:00.000Z|SW1HB5M |Abu Dhabi |Edmonton
  23. 2020-05-07T12:47:25.000Z|0HZ3PHM |Cape Town |Edmonton
  24. 2020-05-08T15:26:39.000Z|T5YFSWW |Paris |Edmonton
  25. 2020-05-08T16:35:16.000Z|E92FNK2 |Edmonton |Vienna
  26. 2020-05-09T02:34:40.000Z|PB8BSSH |Edmonton |Tokyo
  27. 2020-05-10T14:06:58.000Z|ADWMNQL |Edmonton |Zurich
  28. 2020-05-11T15:21:31.000Z|YB4FNOI |Edmonton |Vienna
  29. 2020-05-12T22:16:10.000Z|TCE99LO |Copenhagen |Edmonton
  30. 2020-05-14T00:19:45.000Z|RBJT1ZG |Edmonton |Palermo
  31. 2020-05-15T12:35:39.000Z|M1NHZTB |Edmonton |Guangzhou
  32. 2020-05-17T15:23:49.000Z|WC862JS |Dublin |Edmonton
  33. 2020-05-18T19:39:08.000Z|99R1VXK |Edmonton |Naples
  34. 2020-05-21T05:30:11.000Z|PJP5R9L |Edmonton |Portland
  35. 2020-05-21T07:59:04.000Z|PK7R8IF |Edmonton |Winnipeg
  36. 2020-05-22T00:00:00.000Z|RLMOSMO |Edmonton |Rome
  37. 2020-05-22T17:10:22.000Z|K0SUJFG |Tokoname |Edmonton
  38. 2020-05-22T19:06:34.000Z|ECEIAND |Edmonton |Treviso
  39. 2020-05-23T01:20:52.000Z|VG2K3M9 |Amsterdam |Edmonton
  40. 2020-05-23T22:34:45.000Z|8FXIRFY |Edmonton |Miami

注意,这里没有要求指定该字段。 只需使用 QUERY 运算符搜索 Edmonton 就足够了。 此外,请注意,我们往返卡斯特鲁普的航班都延迟了。 Elasticsearch 查询在这里:

  1. POST /_sql/translate
  2. {
  3. "query": """
  4. SELECT timestamp, FlightNum, OriginCityName, DestCityName FROM flights WHERE QUERY('Edmonton') AND FlightDelay=true AND timestamp > '2018-06-20' AND timestamp < '2020-06-27' ORDER BY timestamp
  5. """
  6. }
  1. {
  2. "size" : 1000,
  3. "query" : {
  4. "bool" : {
  5. "must" : [
  6. {
  7. "bool" : {
  8. "must" : [
  9. {
  10. "query_string" : {
  11. "query" : "Edmonton",
  12. "fields" : [ ],
  13. "type" : "best_fields",
  14. "default_operator" : "or",
  15. "max_determinized_states" : 10000,
  16. "enable_position_increments" : true,
  17. "fuzziness" : "AUTO",
  18. "fuzzy_prefix_length" : 0,
  19. "fuzzy_max_expansions" : 50,
  20. "phrase_slop" : 0,
  21. "escape" : false,
  22. "auto_generate_synonyms_phrase_query" : true,
  23. "fuzzy_transpositions" : true,
  24. "boost" : 1.0
  25. }
  26. },
  27. {
  28. "term" : {
  29. "FlightDelay" : {
  30. "value" : true,
  31. "boost" : 1.0
  32. }
  33. }
  34. }
  35. ],
  36. "adjust_pure_negative" : true,
  37. "boost" : 1.0
  38. }
  39. },
  40. {
  41. "range" : {
  42. "timestamp" : {
  43. "from" : "2018-06-20",
  44. "to" : "2020-06-27",
  45. "include_lower" : false,
  46. "include_upper" : false,
  47. "boost" : 1.0
  48. }
  49. }
  50. }
  51. ],
  52. "adjust_pure_negative" : true,
  53. "boost" : 1.0
  54. }
  55. },
  56. "_source" : {
  57. "includes" : [
  58. "FlightNum",
  59. "OriginCityName",
  60. "DestCityName"
  61. ],
  62. "excludes" : [ ]
  63. },
  64. "docvalue_fields" : [
  65. {
  66. "field" : "timestamp",
  67. "format" : "epoch_millis"
  68. }
  69. ],
  70. "sort" : [
  71. {
  72. "timestamp" : {
  73. "order" : "asc",
  74. "missing" : "_last",
  75. "unmapped_type" : "date"
  76. }
  77. }
  78. ]
  79. }

对于 Elasticsearch 的新用户来说,这代表了一个相对复杂的查询。 我们有一个带有嵌套范围,术语限制和查询字符串运算符的布尔查询。 对于从 SQL 迁移应用程序的用户而言,这在传统上可能是一项相当艰巨的任务,甚至在担心最终查询在功能上是否正确和最佳之前也是如此。 实际的 query_string 运算符已嵌套在过滤器中,因为不需要相关性(我们按日期排序),从而使我们能够利用过滤器缓存,跳过评分并缩短响应时间。

这些运算符的参数也在 SQL 中公开。 最后一个示例说明了如何将 MATCH 查询与跨多个字段的多个搜索词一起使用以限制结果。

“找到往返巴塞罗那的天气晴朗的航班”

出于示例目的,我们还通过 Score()  函数进行排序并显示相关性得分。

  1. sql> SELECT Score(), timestamp, FlightNum, OriginCityName, DestCityName, DestWeather, OriginWeather FROM flights WHERE MATCH('*Weather,*City*', 'Lightning Barcelona', 'type=cross_fields;operator=AND') ORDER BY Score() DESC LIMIT 5;
  2. Score() | timestamp | FlightNum |OriginCityName | DestCityName | DestWeather | OriginWeather
  3. ---------------+------------------------+---------------+---------------+---------------+---------------+-------------------
  4. 6.917009 |2020-04-16T06:00:41.000Z|L637ISB |Barcelona |Santiago |Rain |Thunder & Lightning
  5. 6.917009 |2020-04-16T01:58:51.000Z|ZTOD7RQ |Barcelona |Dubai |Sunny |Thunder & Lightning
  6. 6.917009 |2020-04-22T14:02:34.000Z|QSQA5CT |Barcelona |Naples |Rain |Thunder & Lightning
  7. 6.917009 |2020-04-29T12:23:44.000Z|0GIHB62 |Barcelona |Buenos Aires |Clear |Thunder & Lightning
  8. 6.917009 |2020-04-30T07:42:21.000Z|L09W9TV |Barcelona |Dubai |Cloudy |Thunder & Lightning

我们使用通配符模式来指定要匹配的字段,并要求匹配为布尔 AND。 跨字段参数不需要术语全部出现在一个字段中,而是允许它们出现在不同的字段中,前提是两个字段都存在。 给定数据的结构,这对于匹配至关重要。

这里的示例返回列和组。 但是,QUERY 和 MATCH 运算符也可以与 GROUP BY 一起使用-有效地过滤到 Elasticsearch 的聚合。

交叉索引搜索和别名

到目前为止,我们的查询仅针对单个表/索引。 如果我们复制flights索引,并通过 reindex 请求将文档复制到新的命名版本,则只要两个索引具有相同的映射,就可以同时查询这两个索引。 映射中的任何差异都可能导致查询在分析时出错。 为了一起查询多个索引,用户可以将它们添加到 Elasticsearch 别名中,也可以在 WHERE 子句中使用通配符。如果大家还记得的话,在上一篇文章 “Elasticsearch:Elasticsearch SQL介绍及实例” 中,我们已经把之前的索引 kibana_sample_data_flights 通过 reindex 的方法导入到 flight1 索引中。现在我们也可以通过如下的方法复制这个索引到索引 flight2 中。

  1. POST _reindex
  2. {
  3. "source": {
  4. "index": "flight1"
  5. },
  6. "dest": {
  7. "index": "flight2"
  8. }
  9. }

我们可以通过如下的方法来设置 flight1 和 flight2 的别名为 f_alias:

  1. POST /_aliases
  2. {
  3. "actions": [
  4. {
  5. "add": {
  6. "index": "flight1",
  7. "alias": "f_alias"
  8. }
  9. },
  10. {
  11. "add": {
  12. "index": "flight2",
  13. "alias": "f_alias"
  14. }
  15. }
  16. ]
  17. }

那么我们可以通过如下的方法来查询:

  1. sql> SELECT FlightNum, OriginCityName, DestCityName, DestWeather, OriginWeather FROM f_alias ORDER BY timestamp DESC LIMIT 2;
  2. FlightNum |OriginCityName | DestCityName | DestWeather | OriginWeather
  3. ---------------+---------------+---------------+---------------+---------------
  4. GDZWNB0 |London |Shanghai |Rain |Clear
  5. GDZWNB0 |London |Shanghai |Rain |Clear

JOINs

传统 RDBMS SQL 实现中的 JOIN 允许通过单独的表格响应中的相关列来合并不同的表格。 与 Elasticsearch 本地可用的选项 相比,这允许数据的关系建模,并且代表了一个重要的主题。 尽管 Elasticsearch SQL 当前不支持 JOIN 运算符,但它确实允许用户利用嵌套文档,该文档提供了一对多的简单关系建模。 嵌套文档 的查询对用户是透明的。 为了演示此功能,我们需要一个包含此类数据的索引。 该索引的文档代表电子商务网站的订单,并包含诸如 order_date,billing_city 和 customer_last_name 之类的字段。 此外,“products” 字段包含订单中每个产品的嵌套子文档。 为了加载这个文档,我们安装之前文章 “Elasticsearch:Elasticsearch SQL介绍及实例 (一)” 中介绍的那样,只不过这次我们加载的是 eCommerce 的数据:

一旦数据加载完毕,我们可以在 Kibana 中找到一个叫做 kibana_sample_data_ecommerce 的索引。它的文档的一个例子:

  1. {
  2. "category" : [
  3. "Men's Clothing"
  4. ],
  5. "currency" : "EUR",
  6. "customer_first_name" : "Eddie",
  7. "customer_full_name" : "Eddie Underwood",
  8. "customer_gender" : "MALE",
  9. "customer_id" : 38,
  10. "customer_last_name" : "Underwood",
  11. "customer_phone" : "",
  12. "day_of_week" : "Monday",
  13. "day_of_week_i" : 0,
  14. "email" : "eddie@underwood-family.zzz",
  15. "manufacturer" : [
  16. "Elitelligence",
  17. "Oceanavigations"
  18. ],
  19. "order_date" : "2020-05-04T09:28:48+00:00",
  20. "order_id" : 584677,
  21. "products" : [
  22. {
  23. "base_price" : 11.99,
  24. "discount_percentage" : 0,
  25. "quantity" : 1,
  26. "manufacturer" : "Elitelligence",
  27. "tax_amount" : 0,
  28. "product_id" : 6283,
  29. "category" : "Men's Clothing",
  30. "sku" : "ZO0549605496",
  31. "taxless_price" : 11.99,
  32. "unit_discount_amount" : 0,
  33. "min_price" : 6.35,
  34. "_id" : "sold_product_584677_6283",
  35. "discount_amount" : 0,
  36. "created_on" : "2016-12-26T09:28:48+00:00",
  37. "product_name" : "Basic T-shirt - dark blue/white",
  38. "price" : 11.99,
  39. "taxful_price" : 11.99,
  40. "base_unit_price" : 11.99
  41. },
  42. {
  43. "base_price" : 24.99,
  44. "discount_percentage" : 0,
  45. "quantity" : 1,
  46. "manufacturer" : "Oceanavigations",
  47. "tax_amount" : 0,
  48. "product_id" : 19400,
  49. "category" : "Men's Clothing",
  50. "sku" : "ZO0299602996",
  51. "taxless_price" : 24.99,
  52. "unit_discount_amount" : 0,
  53. "min_price" : 11.75,
  54. "_id" : "sold_product_584677_19400",
  55. "discount_amount" : 0,
  56. "created_on" : "2016-12-26T09:28:48+00:00",
  57. "product_name" : "Sweatshirt - grey multicolor",
  58. "price" : 24.99,
  59. "taxful_price" : 24.99,
  60. "base_unit_price" : 24.99
  61. }
  62. ],
  63. "sku" : [
  64. "ZO0549605496",
  65. "ZO0299602996"
  66. ],
  67. "taxful_total_price" : 36.98,
  68. "taxless_total_price" : 36.98,
  69. "total_quantity" : 2,
  70. "total_unique_products" : 2,
  71. "type" : "order",
  72. "user" : "eddie",
  73. "geoip" : {
  74. "country_iso_code" : "EG",
  75. "location" : {
  76. "lon" : 31.3,
  77. "lat" : 30.1
  78. },
  79. "region_name" : "Cairo Governorate",
  80. "continent_name" : "Africa",
  81. "city_name" : "Cairo"
  82. }
  83. }

通常,查询这些文档将要求用户理解为什么我们要对产品字段使用嵌套的数据类型,并且还要了解嵌套的查询语法。 但是,通过 Elasticsearch SQL,我们能够查询这些嵌套文档,就好像每个嵌套文档都使用其父级字段代表一个单独的行一样(即,我们有效地扁平化了表示结构)。 考虑上面有两个产品的订单。 当从产品子文档中请求字段时,查询时将其显示为两行。 如果需要,每一行还可以包含父订单的字段。 例如:

查找航班584677所使用的帐单名称和购买的产品。

如果我们查看一下 kibana_sample_data_ecommerce,我们发现这个索引的 products 字段并不是我们想象的 nested 类型。为此,我们需要重新定义它的 mapping:

  1. PUT orders
  2. {
  3. "mappings": {
  4. "properties": {
  5. "category": {
  6. "type": "text",
  7. "fields": {
  8. "keyword": {
  9. "type": "keyword"
  10. }
  11. }
  12. },
  13. "currency": {
  14. "type": "keyword"
  15. },
  16. "customer_birth_date": {
  17. "type": "date"
  18. },
  19. "customer_first_name": {
  20. "type": "text",
  21. "fields": {
  22. "keyword": {
  23. "type": "keyword",
  24. "ignore_above": 256
  25. }
  26. }
  27. },
  28. "customer_full_name": {
  29. "type": "text",
  30. "fields": {
  31. "keyword": {
  32. "type": "keyword",
  33. "ignore_above": 256
  34. }
  35. }
  36. },
  37. "customer_gender": {
  38. "type": "keyword"
  39. },
  40. "customer_id": {
  41. "type": "keyword"
  42. },
  43. "customer_last_name": {
  44. "type": "text",
  45. "fields": {
  46. "keyword": {
  47. "type": "keyword",
  48. "ignore_above": 256
  49. }
  50. }
  51. },
  52. "customer_phone": {
  53. "type": "keyword"
  54. },
  55. "day_of_week": {
  56. "type": "keyword"
  57. },
  58. "day_of_week_i": {
  59. "type": "integer"
  60. },
  61. "email": {
  62. "type": "keyword"
  63. },
  64. "geoip": {
  65. "properties": {
  66. "city_name": {
  67. "type": "keyword"
  68. },
  69. "continent_name": {
  70. "type": "keyword"
  71. },
  72. "country_iso_code": {
  73. "type": "keyword"
  74. },
  75. "location": {
  76. "type": "geo_point"
  77. },
  78. "region_name": {
  79. "type": "keyword"
  80. }
  81. }
  82. },
  83. "manufacturer": {
  84. "type": "text",
  85. "fields": {
  86. "keyword": {
  87. "type": "keyword"
  88. }
  89. }
  90. },
  91. "order_date": {
  92. "type": "date"
  93. },
  94. "order_id": {
  95. "type": "keyword"
  96. },
  97. "products": {
  98. "type": "nested",
  99. "properties": {
  100. "_id": {
  101. "type": "text",
  102. "fields": {
  103. "keyword": {
  104. "type": "keyword",
  105. "ignore_above": 256
  106. }
  107. }
  108. },
  109. "base_price": {
  110. "type": "half_float"
  111. },
  112. "base_unit_price": {
  113. "type": "half_float"
  114. },
  115. "category": {
  116. "type": "text",
  117. "fields": {
  118. "keyword": {
  119. "type": "keyword"
  120. }
  121. }
  122. },
  123. "created_on": {
  124. "type": "date"
  125. },
  126. "discount_amount": {
  127. "type": "half_float"
  128. },
  129. "discount_percentage": {
  130. "type": "half_float"
  131. },
  132. "manufacturer": {
  133. "type": "text",
  134. "fields": {
  135. "keyword": {
  136. "type": "keyword"
  137. }
  138. }
  139. },
  140. "min_price": {
  141. "type": "half_float"
  142. },
  143. "price": {
  144. "type": "half_float"
  145. },
  146. "product_id": {
  147. "type": "long"
  148. },
  149. "product_name": {
  150. "type": "text",
  151. "fields": {
  152. "keyword": {
  153. "type": "keyword"
  154. }
  155. },
  156. "analyzer": "english"
  157. },
  158. "quantity": {
  159. "type": "integer"
  160. },
  161. "sku": {
  162. "type": "keyword"
  163. },
  164. "tax_amount": {
  165. "type": "half_float"
  166. },
  167. "taxful_price": {
  168. "type": "half_float"
  169. },
  170. "taxless_price": {
  171. "type": "half_float"
  172. },
  173. "unit_discount_amount": {
  174. "type": "half_float"
  175. }
  176. }
  177. },
  178. "sku": {
  179. "type": "keyword"
  180. },
  181. "taxful_total_price": {
  182. "type": "half_float"
  183. },
  184. "taxless_total_price": {
  185. "type": "half_float"
  186. },
  187. "total_quantity": {
  188. "type": "integer"
  189. },
  190. "total_unique_products": {
  191. "type": "integer"
  192. },
  193. "type": {
  194. "type": "keyword"
  195. },
  196. "user": {
  197. "type": "keyword"
  198. }
  199. }
  200. }
  201. }

在上面,我们对原有的 mapping 做了如下的修改:

  1. "products": {
  2. "type": "nested",
  3. "properties": {
  4. "_id": {
  5. "type": "text",
  6. "fields": {
  7. "keyword": {
  8. "type": "keyword",
  9. "ignore_above": 256
  10. }
  11. }
  12. },
  13. "base_price": {
  14. "type": "half_float"
  15. },
  16. "base_unit_price": {
  17. "type": "half_float"
  18. },
  19. "category": {
  20. "type": "text",
  21. "fields": {
  22. "keyword": {
  23. "type": "keyword"
  24. }
  25. }
  26. },
  27. "created_on": {
  28. "type": "date"
  29. },
  30. "discount_amount": {
  31. "type": "half_float"
  32. },
  33. "discount_percentage": {
  34. "type": "half_float"
  35. },
  36. "manufacturer": {
  37. "type": "text",
  38. "fields": {
  39. "keyword": {
  40. "type": "keyword"
  41. }
  42. }
  43. },
  44. "min_price": {
  45. "type": "half_float"
  46. },
  47. "price": {
  48. "type": "half_float"
  49. },
  50. "product_id": {
  51. "type": "long"
  52. },
  53. "product_name": {
  54. "type": "text",
  55. "fields": {
  56. "keyword": {
  57. "type": "keyword"
  58. }
  59. },
  60. "analyzer": "english"
  61. },
  62. "quantity": {
  63. "type": "integer"
  64. },
  65. "sku": {
  66. "type": "keyword"
  67. },
  68. "tax_amount": {
  69. "type": "half_float"
  70. },
  71. "taxful_price": {
  72. "type": "half_float"
  73. },
  74. "taxless_price": {
  75. "type": "half_float"
  76. },
  77. "unit_discount_amount": {
  78. "type": "half_float"
  79. }
  80. }
  81. }

在上面我加入了如下的一句:

     "type": "nested",

这样我们把 products 这个字段设置为 nested 数据类型。如果大家对 nested 数据类型还是不太清楚的话,请参阅我之前的文字 “Elasticsearch: nested 对象”。我们使用如下命令来做 reindex:

  1. POST _reindex
  2. {
  3. "source": {
  4. "index": "kibana_sample_data_ecommerce"
  5. },
  6. "dest": {
  7. "index": "orders"
  8. }
  9. }

我们通过如下的方式来继续查询:

  1. sql> SELECT customer_last_name, customer_first_name, products.price, products.product_id FROM orders WHERE order_id=584677;
  2. customer_last_name|customer_first_name| products.price |products.product_id
  3. ------------------+-------------------+------------------+-------------------
  4. Underwood |Eddie |11.989999771118164|6283
  5. Underwood |Eddie |24.989999771118164|19400

_translate API 将显示如何使用嵌套查询构造此查询:

  1. POST /_sql/translate
  2. {
  3. "query": """
  4. SELECT customer_last_name, customer_first_name, products.price, products.product_id FROM orders WHERE order_id=584677
  5. """
  6. }

上面的显示结果是:

  1. {
  2. "size" : 1000,
  3. "query" : {
  4. "bool" : {
  5. "must" : [
  6. {
  7. "term" : {
  8. "order_id" : {
  9. "value" : 584677,
  10. "boost" : 1.0
  11. }
  12. }
  13. },
  14. {
  15. "nested" : {
  16. "query" : {
  17. "match_all" : {
  18. "boost" : 1.0
  19. }
  20. },
  21. "path" : "products",
  22. "ignore_unmapped" : false,
  23. "score_mode" : "none",
  24. "boost" : 1.0,
  25. "inner_hits" : {
  26. "name" : "products_1",
  27. "ignore_unmapped" : false,
  28. "from" : 0,
  29. "size" : 99,
  30. "version" : false,
  31. "seq_no_primary_term" : false,
  32. "explain" : false,
  33. "track_scores" : false,
  34. "_source" : {
  35. "includes" : [
  36. "products.product_id",
  37. "products.price"
  38. ],
  39. "excludes" : [ ]
  40. }
  41. }
  42. }
  43. }
  44. ],
  45. "adjust_pure_negative" : true,
  46. "boost" : 1.0
  47. }
  48. },
  49. "_source" : {
  50. "includes" : [
  51. "customer_last_name",
  52. "customer_first_name"
  53. ],
  54. "excludes" : [ ]
  55. },
  56. "sort" : [
  57. {
  58. "_doc" : {
  59. "order" : "asc"
  60. }
  61. }
  62. ]
  63. }

相反,如果仅查询父字段,则仅显示一行:

查找航班用于订单584677的帐单名称

  1. sql> SELECT customer_last_name, customer_first_name FROM orders WHERE order_id=584677;
  2. customer_last_name|customer_first_name
  3. ------------------+-------------------
  4. Underwood |Eddie

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/822485
推荐阅读
相关标签
  

闽ICP备14008679号