【问题标题】:Elastic search - recreating LIKE in mysqlElasticsearch - 在 mysql 中创建 LIKE
【发布时间】:2021-02-27 23:53:07
【问题描述】:

我需要在弹性搜索中实现一个搜索功能,它的工作方式与 MySQL 'LIKE' 查询相同。

我在 PHP 中有以下代码

    public function setUp($reference)
{
    $parameter = DqlPartial::uniqueParameterName('reference');

    $partial = $this->getBaseDqlPartial();
    $partial->where("IFNULL(Asset.supplierReference, '') LIKE :$parameter");
    $partial->setParameter($parameter, '%' . $reference . '%');
    $this->addJoins($partial, $partial->getWhere());
    $this->setDqlPartial($partial);

    if (strpos($reference, "*") !== false) {
        $termQuery = new SimpleQueryString($reference, ["supplierReference"]);
    } else {
        $termQuery = new MatchPhrase();
        $termQuery->setField('supplierReference', $reference);
    }
    $eqPartial = new EqPartial();
    $eqPartial->setQuery($termQuery);
    $this->setEqPartial($eqPartial);

    return $this;
}

您可以看到,如果搜索字符串在任何位置包含“*”,我正在执行 MatchPhrase 函数而不是简单查询。

问题是 MatchPhrase 是区分大小写的,我需要传递什么参数给这个函数才能让它表现得像 MySQL 中的一个简单的 LIKE 查询,像这样:

SELECT asset_id, asset_supplier_reference 
FROM assets 
WHERE asset_supplier_reference LIKE 'Opale%'

返回如下结果:Opal​​e123、OPALE33、opaletest、opale_ 等。

我发现唯一接近的是fuzziness,我不喜欢它,因为它不精确,我需要与字符串开头完全匹配的东西(无论字母大小写如何)。

P.S 我正在改进一个已经存在的系统,我不知道为什么这行不通,因为我有这条线

$partial->setParameter($parameter, '%' . $reference . '%');

 

【问题讨论】:

    标签: php mysql elasticsearch


    【解决方案1】:

    根据您是要匹配单词的开头还是短语的开头,您可以使用前缀查询或 match_phrase_prefix 查询。

    {
      "query": {
        "prefix" : { "content.description" : "cur" }
      }
    
    "match_phrase_prefix": {
          "message": {
            "query": "quick brown f"
          }
        }
    

    如果您可以修改索引映射,则可以使用 https://www.elastic.co/guide/en/elasticsearch/reference/current/index-prefixes.html 进行优化

    但是前缀查询很重。 您可以通过在您的字段上添加带有 ngram 的映射来做得更好,然后经典匹配将起作用。 https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html

    GET my-index-00001/_search
    {
      "query": {
        "match": {
          "title": {
            "query": "Quick Fo", 
            "operator": "and"
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2015-09-03
      • 2018-05-06
      • 1970-01-01
      • 2019-06-19
      相关资源
      最近更新 更多