json – 如何在ElasticSearch中“加入”两个索引

前端之家收集整理的这篇文章主要介绍了json – 如何在ElasticSearch中“加入”两个索引前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个必须分开的索引:
  1. // index = `order_item`
  2. {
  3. "ID": 1,"Name": "Shoes","Price": 9.99,"OrderID": 82
  4. },{
  5. "ID": 1,"Name": "Hat","Price": 19.99,"OrderID": 82
  6. }
  7.  
  8. // index = `order`
  9. {
  10. "ID": 82,"Customer": "John Smith"
  11. }

我将如何在搜索中“加入”这两个表格,以便它返回以下内容

  1. results = {
  2. "ID": 1,"Order.ID": 82,"Customer": "John Smith"
  3. },"Customer": "John Smith"
  4. }

解决方法

正如在 your other question中所回答的,没有什么可以阻止您在索引时将每个order_item文档中的客户名称存储,同时仍然具有包含客户数据的专用索引订单.请记住,这一切都是为了巧妙地对数据进行非规范化,以便您的每个文档都可以根据需要“自包含”.
  1. curl -XPUT localhost:9200/order_items/order_item/1 -d '{
  2. "ID": 1,"OrderID": 82,"Customer": "John Smith"
  3. }'
  4.  
  5. curl -XPUT localhost:9200/order_items/order_item/2 -d '{
  6. "ID": 2,"Customer": "John Smith"
  7. }

解决方案的优点是每个订单项都是完全自包含的,您可以在OrderID上对它们进行分组/聚合,以获取给定订单的所有项目.

另外,正如@JohnAment在他的评论中提到的,order / order_item用例也是使用它们的一个很好的候选者

> parent/child relationship
>或nested objects.

在第一种情况下,你有一个订单“父”文件……

  1. curl -XPUT localhost:9200/orders/order/82 -d '{
  2. "ID": 82,"Customer": "John Smith"
  3. }'

以及使用其父ID编制索引的几个order_item“子”文档:

  1. curl -XPUT localhost:9200/order_items/order_item/1?parent=82 -d '{
  2. "ID": 1,"Price": 9.99
  3. }'
  4. curl -XPUT localhost:9200/order_items/order_item/2?parent=82 -d '{
  5. "ID": 2,"Price": 19.99
  6. }'

在第二种情况下,您的订单文档将包含嵌套的OrderItems属性中的所有订单商品,如下所示:

  1. curl -XPUT localhost:9200/orders/order/82 -d '{
  2. "ID": 82,"Customer": "John Smith"
  3. "OrderItems": [
  4. {
  5. "ID": 1,"Price": 9.99
  6. },{
  7. "ID": 2,"Price": 19.99
  8. }
  9. ]
  10. }'

猜你在找的JavaScript相关文章