我想在查询中使用模糊匹配,但在结果的顶部显示完全匹配。
我已尝试过以下内容。
$return = $this->_client->search(
array(
'index' => self::INDEX,
'type' => self::TYPE,
'body' => array(
'query' => array(
'bool' => array(
'must' => array(
'multi_match' => array(
'query' => $query,
'fields' => array('name', 'brand', 'description'),
'boost' => 10,
),
'fuzzy_like_this' => array(
'like_text' => $query,
'fields' => array('name', 'brand', 'description'),
'fuzziness' => 1,
),
),
),
),
'size' => '5000',
),
)
);
由于格式错误的查询错误,这项工作无效。
有什么想法吗?
答案 0 :(得分:5)
我最终没有使用模糊匹配来解决我的问题,而是使用了ngram的。
/**
* Map - Create a new index with property mapping
*/
public function map()
{
$params['index'] = self::INDEX;
$params['body']['settings'] = array(
'index' => array(
'analysis' => array(
'analyzer' => array(
'product_analyzer' => array(
'type' => 'custom',
'tokenizer' => 'whitespace',
'filter' => array('lowercase', 'product_ngram'),
),
),
'filter' => array(
'product_ngram' => array(
'type' => 'nGram',
'min_gram' => 3,
'max_gram' => 5,
),
)
),
)
);
//all the beans
$mapping = array(
'_source' => array(
'enabled' => true
),
'properties' => array(
'id' => array(
'type' => 'string',
),
'name' => array(
'type' => 'string',
'analyzer' => 'product_analyzer',
'boost' => '10',
),
'brand' => array(
'type' => 'string',
'analyzer' => 'product_analyzer',
'boost' => '5',
),
'description' => array(
'type' => 'string',
),
'barcodes' => array(
'type' => 'string'
),
),
);
$params['body']['mappings'][self::TYPE] = $mapping;
$this->_client->indices()->create($params);
}
public function search($query)
{
$return = $this->_client->search(
array(
'index' => self::INDEX,
'type' => self::TYPE,
'body' => array(
'query' => array(
'multi_match' => array(
'query' => $query,
'fields' => array('id', 'name', 'brand', 'description', 'barcodes'),
),
),
'size' => '5000',
),
)
);
$productIds = array();
if (!empty($return['hits']['hits'])) {
foreach ($return['hits']['hits'] as $hit) {
$productIds[] = $hit['_id'];
}
}
return $productIds;
}
结果正是我所寻找的。它根据搜索查询中包含的ngram部分构造匹配。
答案 1 :(得分:0)
免责声明,我不是一个php人,但我对你的查询有一些不满:
$return = $this->_client->search(
array(
'index' => self::INDEX,
'type' => self::TYPE,
'body' => array(
'query' => array(
'bool' => array(
'should' => array(
array(
'multi_match' => array(
'query' => $query,
'fields' => array('name', 'brand', 'description'),
'boost' => 10,
),
),
array(
'fuzzy_like_this' => array(
'like_text' => $query,
'fields' => array('name', 'brand', 'description'),
'fuzziness' => 1,
),
),
),
),
),
'size' => '5000',
),
)
);
更改为应该使它只有一个查询必须匹配,而不是两者。您可以在此处阅读有关bool查询的信息:http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html