使用Laravel

时间:2019-07-10 05:29:35

标签: php laravel elasticsearch

我关注了这篇文章,以连接laravel和ElasticSearch: https://madewithlove.be/how-to-integrate-your-laravel-app-with-elasticsearch/

我在MySQL数据库中有一个表,该表具有树字段:“标题”,“描述”和“价格”。 “标题”和“描述是字符串类型。所以我在下面编写了用于搜索的代码,此代码可以正常工作:

private function searchOnElasticsearch(string $query): array
{
    $instance = new Article;

    $items = $this->search->search([
        'index' => $instance->getSearchIndex(),
        'type' => $instance->getSearchType(),
        'body' => [
            'query' => [
                'multi_match' => [
                    'fields' => ['title', 'description'],
                    'query' => $query,
                ],
            ],
        ],
    ]);

    return $items;
}

但是,现在,我需要像其他两个字段一样检查属于 bigInt类型的“价格”字段:'fields' => ['title', 'description','price'],

更新

当我在字段中添加“价格”时,在laravel中出现此错误:

  

{“错误”:{“ root_cause”:[{“类型”:“ query_shard_exception”,“原因”:“失败   创建查询:{\ n \“ multi_match \”:{\ n \“ query \”:\“坏\”,\ n   \“ fields \”:[\ n \“描述^ 1.0 \”,\ n \“价格^ 1.0 \”,\ n   \“ tags ^ 1.0 \”,\ n \“ title ^ 1.0 \” \ n],\ n \“ type \”:\“最佳字段\”,\ n   \“ operator \”:\“ OR \”,\ n \“ slop \”:0,\ n \“ prefix_length \”:0,\ n   \“ max_expansions \”:50,\ n \“ zero_terms_query \”:\“ NONE \”,\ n   \“ auto_generate_synonyms_phrase_query \”:true,\ n   \“ fuzzy_transpositions \”:true,\ n \“ boost \”:1.0 \ n   } \ n}“,” index_uuid“:” mm787GxMS4WjjjqwRD5YIw“,” index“:”商品“}],”类型“:” search_phase_execution_exception“,”原因“:”全部   分片   失败”,“阶段”:“查询”,“分组”:true,“ failed_shards”:[{“ shard”:0,“ index”:“ commodities”,“ node”:“ JYWiIdbLQtu3aWkm_F-e9Q”,“ reason” :{“类型”:“ query_shard_exception”,“原因”:“失败   创建查询:{\ n \“ multi_match \”:{\ n \“ query \”:\“坏\”,\ n   \“ fields \”:[\ n \“描述^ 1.0 \”,\ n \“价格^ 1.0 \”,\ n   \“ tags ^ 1.0 \”,\ n \“ title ^ 1.0 \” \ n],\ n \“ type \”:\“最佳字段\”,\ n   \“ operator \”:\“ OR \”,\ n \“ slop \”:0,\ n \“ prefix_length \”:0,\ n   \“ max_expansions \”:50,\ n \“ zero_terms_query \”:\“ NONE \”,\ n   \“ auto_generate_synonyms_phrase_query \”:true,\ n   \“ fuzzy_transpositions \”:true,\ n \“ boost \”:1.0 \ n   } \ n}“,” index_uuid“:” mm787GxMS4WjjjqwRD5YIw“,” index“:”商品“,” caused_by“:{” type“:” number_format_exception“,” reason“:” For   输入字符串:\“ bad \”“}}}]},”状态“:400}

1 个答案:

答案 0 :(得分:1)

我建议使用类似的方法,即将查询分为两部分,一部分用于文本字段,另一部分用于数字字段。但是,仅当$query确实是数字时,才在数字字段上添加匹配项:

$body = [
    'query' => [
        'bool' => [
            'should' => [
                [
                   'multi_match' => [
                       'fields' => ['title', 'description'],
                       'query' => $query
                   ]
                ]
            ]
        ]
    ]
];

// if the query is numeric add an additional clause for the price field
if (is_numeric($query)) {
    $body['query']['bool']['should'][] = [ 'match' => [ 'price' => $query]];
}

$items = $this->search->search([
    'index' => $instance->getSearchIndex(),
    'type' => $instance->getSearchType(),
    'body' => $body
]);