带有has_child的PHP ElasticSearch复合查询

时间:2017-08-03 12:40:28

标签: php elasticsearch

当我向Elasticsearch查询特定制造商的产品时,这可行:

  $params = ['index' => 'products',
     'type' => 'product',
     'body' => ['query' =>
        ['match' => ['manufacturers_id' => $query],],
     ],
  ];

但是当我还想添加产品颜色为Silver的条件时,我将其作为子记录添加到产品记录中,我收到语法错误:

 $params = ['index' => 'products',
     'type' => 'product',
     'body' => ['query' =>
        ['match' => ['manufacturers_id' => $query],],
        ['query' =>
          ['has_child' =>
            ['type' => 'attributes',
            ['query' =>
              ['color' => 'Silver'],],
            ],
            ],
        ],
     ],
  ];

错误是

{
    "error": {
        "col": 49,
        "line": 1,
        "reason": "Unknown key for a START_OBJECT in [0].",
        "root_cause": [
            {
                "col": 49,
                "line": 1,
                "reason": "Unknown key for a START_OBJECT in [0].",
                "type": "parsing_exception"
            }
        ],
        "type": "parsing_exception"
    },
    "status": 400
}

也试过

  $params = ['index' => 'products',
     'type' => 'product',
     'body' => ["query"=> [
                    "match"=> [
                        "manufacturers_id"=> [11]
                    ],
                    "has_child"=> [
                        "type"=> "attributes",
                        "query"=> [
                            "match"=> [
                                "color"=> "silver"
                            ],
                        ],
                    ],
                ],
     ],
  ];

我得到"无法在1:39的START_ARRAY上获取文字。"

2 个答案:

答案 0 :(得分:1)

试试这个:

"query"=> [
    "match"=> [
        "manufacturers_id"=> [1,2,3]
    ],
    "has_child"=> [
        "type"=> "attributes",
        "query"=> [
            "match"=> [
                "color"=> "silver"
            ]
        ]
    ]
]

我还推荐Sense,它是Chrome浏览器的插件,可以帮助编写ES查询。 See the screenshot

答案 1 :(得分:0)

终于有了这个工作。非常感谢@pawle对Sense的建议,这确实有帮助。

  $params = ['index' => 'products',
     'type' => 'product',
     'body' =>
        [
           "query" => [
              "bool" => [
                 "must" => [[
                    "has_child" => [
                       "type" => "attributes",
                       "query" => [
                          "match" => [
                             "attributes_value" => "silver"
                          ]
                       ]
                    ]
                 ],
                    [
                       "match" => [
                          "manufacturers_id" => 4
                       ]
                    ]
                 ]
              ]
           ]
        ],
  ];