【问题标题】:Is there a good PHP library available to parse boolean search operators to MySQL fulltext operators? [closed]是否有一个好的 PHP 库可用于将布尔搜索运算符解析为 MySQL 全文运算符? [关闭]
【发布时间】:2023-03-26 18:12:01
【问题描述】:

我们已经使用 MySQL 全文搜索好几年了,但是需求已经改变了。我们希望将 AND/OR/NOT 参数解析为 MySQL 能够理解的形式。我写了一个单元测试,很明显这很复杂。

我相信更多的人会遇到这个问题,所以我想一定有某种库可以为我解决这个问题。我试过谷歌,但不幸的是,我找不到这样的图书馆。有谁知道好的吗?

该库应该能够处理引号、括号、AND/OR/NOT 运算符,在我们的例子中,它应该默认为 AND 而不是 OR(如果没有设置运算符)。以下是我的一些预期结果:

  • “ict”变成“+ict”
  • 'ict it' 变成 '+ict +it'
  • 'ict OR it' 变成 'ict it'
  • 'NOT ict' 变为 '-ict'
  • 'it NOT ict' 变为 '+it -ict'
  • 'web AND (ict OR it)' 变为 '+web +(ict it)'
  • 'ict OR (it AND web)' 变为 'ict (+it +web)'
  • 'ict NOT (ict AND it AND web)' 变为 '+ict -(+ict +it +web)'
  • 'php OR (NOT web NOT embedded ict OR it)'变成'php (-web -embedded ict it)'
  • '(web OR embedded) (ict OR it)' 变为 '+(web embedded) +(ict it)'
  • develop AND (web OR (ict AND php))' 变为 '+develop +(web (+ict +php))'
  • '"ict' 变成 '+"ict"'
  • '"ict OR it"' 保持 '+"ict OR it"'

这是我们前几年使用的功能(不能正常使用):

/**
 * Parses search string.
 * @param string $s The unparsed search string.
 * @return string $s The parsed search string.
 */
public function parseSearchString( $s )
{
    // Place a space at the beginning.
    $s = ' ' . $s;

    // AND - Remove multiple spaces, AND, &.
    $s = preg_replace( '/\s\s+/', ' ', $s );
    $s = preg_replace( '/\sAND\s/i', ' ', $s );
    $s = preg_replace( '/\s&\s/', ' ', $s );

    // OR - Make replacements. Execute double, so we replace all occurences.
    $s = preg_replace( '/(\w+)\s(?:OR|\|)\s(\|?\w+)/i', '|\\1|\\2', $s );
    $s = preg_replace( '/(\w+)\s(?:OR|\|)\s(\|?\w+)/i', '|\\1|\\2', $s );
    $s = preg_replace( '/(\w+)\s*(?:\\\|\\/)\s*(\|?\w+)/i', '|\\1|\\2', $s );
    $s = preg_replace( '/(\w+)\s*(?:\\\|\\/)\s*(\|?\w+)/i', '|\\1|\\2', $s );

    // NOT
    $s = preg_replace( '/\bNOT\s(\w+)/i', '|-\\1', $s );

    // Quoted strings.
    $s = preg_replace( '/\s"/', ' +"', $s );

    // Place + in front of words.
    $s = preg_replace( '/\s(\w+)/', ' +\\1', $s );

    // Replace | to spaces.
    $s = preg_replace( '/\|/', ' ', $s );

    return trim( $s );
}

【问题讨论】:

  • 就个人而言,我认为这是一个了不起的问题,很想知道您是否找到了解决方案
  • 当时,我在 php 中编写了一个自定义关键字标记器和解析器,它完成了所有的魔法。它对我们来说效果很好,但并不那么漂亮。我们从未发布过代码。在切换到 Elasticsearch 之前,我们已经使用了几年。
  • 有趣的是,其他人看到了你的问题并写了一个类来回答它 - 我可以很好地补充。他们甚至使用了相同的样本数据。 github.com/DuncanOgle/BooleanSearchParser

标签: php mysql boolean-search


【解决方案1】:

这可能无法回答您的问题,但如果您需要更高级的全文搜索功能,我建议您使用 sphinx 或 apache solr 之类的东西。 https://stackoverflow.com/a/1297561/2170561

【讨论】:

  • 感谢您的回答。我们知道像 Sfinx、Xapian 和 Solr 这样的解决方案。但就目前而言,我们希望继续使用全文搜索。
  • 有人做了几个类来解析 BOOLEAN mysql 查询的字符串。 github.com/DuncanOgle/BooleanSearchParser
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 2012-12-04
  • 2013-02-17
  • 2017-06-21
  • 1970-01-01
  • 2013-06-06
  • 2014-05-31
  • 1970-01-01
相关资源
最近更新 更多