您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Elastic search模糊匹配,精确匹配显示在前

Elastic search模糊匹配,精确匹配显示在前

我最终没有使用模糊匹配来解决我的问题,而是使用了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部分构造匹配项。

其他 2022/1/1 18:24:25 有542人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶