我有一个类似http://drive.google.com的链接,我想匹配出链接中的"谷歌".

I have:

query: {
    bool : {
        must: {
            match: { text: 'google'} 
        }
    }
}

But this only matches if the whole text is 'google' (case insensitive, so it also matches Google or GooGlE etc). How do I match for the 'google' inside of another string?

推荐答案

重点是您正在使用的ElasticSearch正则表达式requires a full string match:

Lucene’s patterns are always anchored. The pattern provided must match the entire string.

因此,要匹配任何字符(但换行符除外),可以使用.*模式:

match: { text: '.*google.*'}
                ^^      ^^

In ES6+, use regexp insted of match:

"query": {
   "regexp": { "text": ".*google.*"} 
}

还有一个变化是针对字符串可以有换行符的情况:match: { text: '(.|\n)*google(.|\n)*'}.在ElasticSearch中,这个糟糕的(.|\n)*是必须的,因为这个regex风格不允许任何[\s\S]解决方案,也不允许任何DOTALL/Singleline标志."The Lucene regular expression engine is not Perl-compatible but supports a smaller range of operators."

However,如果您不打算匹配任何复杂的模式,也不需要进行单词边界判断,那么使用wildcard search就可以更好地执行regex搜索一个简单的子字符串:

{
    "query": {
        "wildcard": {
            "text": {
                "value": "*google*",
                "boost": 1.0,
                "rewrite": "constant_score"
            }
        }
    }
} 

See Wildcard search for more details.

NOTE:通配符模式还需要匹配整个输入字符串,因此

  • google* finds all strings starting with google
  • *google*查找所有字符串containing google
  • *google查找所有字符串ending with google

Also, bear in mind the only pair of special characters in wildcard patterns:

?, which matches any single character
*, which can match zero or more characters, including an empty one

Json相关问答推荐

输入请求中不存在null的条件抖动

当有嵌套数组而没有嵌套数组时,展平JSON

Vega图表计数聚合如果数据值为空数组则不显示任何内容,如何解决此问题?

jq 对特定键进行过滤并将值整理到单个 csv 单元格中

使用jq根据对象中键的值查找对象

打印与 JSON 和 PowerShell 中的模式匹配的子项的父项名称

jq json - 按键名 Select

如何在 Android Studio 中将 List 字段作为空列表[]返回?

在 postgresql 中将行转换为 json 对象

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

如何使用 LINQ 在 C# 中重构对象?

如何使用 C# 将 JSON 文本转换为对象

如何从Typescript 中的json响应中获取日期对象

使用 JSON 的 javascript 深拷贝

Rails 中奇怪的 JSON Javascript 问题

消息通知产生此内容无法显示

在android中读取Json数组

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

如何将 mysqli 结果转换为 JSON?

从调试器获取 IntelliJ Idea 中的 JSON 对象