不为失败找理由,要为成功找方法。

elasticsearch两个类型的关联查询排序问题

Elasticsearch | 作者 edison | 发布于2016年11月02日 | 阅读数:5024

问题描述
  一个索引中存在两个type, parent type 为 hotel, child type 为 dayPrice。 hotel 与 dayPrice 为一对多关系。
----------------------------------------------------------------------------------
parent  hotel 数据为:

{
    _id: 21400,
    title: "Bike",
    recommend: 1
    ...
},
{
    _id: 21500,
    title: "Bike",
    recommend: 2
    ...
}
 
 
-------------------------------------------------------------------------------
child dayPrice 数据为:
{
    _parent: 21400,
    day: "2016-10-01",
    available: 2, 
    price: 100
},
{
    _parent: 21400,
    day: "2016-10-02",
    available: 2, 
    price: 120
},
{
    _parent: 21400,
    day: "2016-10-03",
    available: 2, 
    price: 140
}
,
{
    _parent: 21500,
    day: "2016-10-03",
    available: 2, 
    price: 140
}
  
   实现需求:查询parent hotel 与之关联的child的day, 然后再求均值 child dayPrice的 price 作为hotel其中一个排序.  简单来说就是需要对hotel进行价格排序,但是价格是在另外一个type里面按天类型等区分开的。


网上搜索发现其中有一个和当前的需求非常类似,但是还不完全理解。求大神指点迷津
http://elasticsearch-users.115 ... .html
已邀请:

szwx855 - Easy Simple

赞同来自:

官网说明:
Sortingedit

Parent documents can’t be sorted by fields in matching child documents via the regular sort options. If you need to sort parent document by field in the child documents then you can should use the function_score query and then just sort by _score.

Sorting blogs by child documents' click_count field:GET /_search { "query": { "has_child" : { "type" : "blog_tag", "score_mode" : "max", "query" : { "function_score" : { "script_score": { "script": "_score * doc['click_count'].value" } } } } } }
 
 
我弄的视频例子:

 
代码:
{
  "query": {
    "has_child": {
      "type": "dayPrice",
      "score_mode": "max",
      "query": {
        "function_score": {
          "script_score": {
            "script": "_score * doc['price'].value"
          }
        }
      }
    }
  },
  "sort": {
    "_score": {
      "order": "asc"
    }
  }
}
你直接mhk贴入应该就可以查询。我完全按照你mapping的
{
  "mappings": {
    "hotel": {
      "properties": {
        "id": {
          "type": "long"
        },
        "title": {
          "type": "keyword"
        },
        "recommend": {
          "type": "keyword"
        }
      }
    },
    "dayPrice": {
      "properties": {
        "day": {
          "type": "date"
        },
        "available": {
          "type": "long"
        },
        "price": {
          "type": "double"
        }
      },
      "_parent": {
        "type": "hotel"
      }
    }
  }
}
经本地查询测试,是可以排序的。

要回复问题请先登录注册