ElasticsSearch——Query String

之前一直觉的QueryString这种查询方式挺好用的,用它的主要场合就是对同一个词针对多字段可以查询,这好像是其他方式所不支持的。今天一个Bug 出来才发现,原来还有很多不了解的地方。

queryString 是能够自动解析查询的字符串的,而且其中还可以使用正则表达式。既方便,但是对于不用这个功能的我,就显得尤为没有必要,因为我的字符串如果包含了他已经实现定义有特定意义的字符,就会报错,因为他误会我的意思了。

Query String Queryedit

On this page

A query that uses a queryparserin order to parse its content.

也就是说这种查询方式有一个自己的解析器会解析输入的查询字符串。

Multi Fieldedit

The query_string query can also run against multiple fields. Fields can be provided via the "fields"parameter (example below).

The idea of running the query_string query against multiple fields is to expand each query term to an OR clauselike this:

field1:query_term OR field2:query_term | ...

For example, the following query

{
    "query_string" : {
        "fields" : ["content", "name"],
        "query" : "this AND that"
    }
}

matches the same words as

{
    "query_string": {
      "query": "(content:this OR name:this) AND (content:that OR name:that)"
    }
}
还可以做通配符查询,模糊查询等,但是万万没想到

Reserved characters 保留字符edit

If you need to use any of the characters which function as operators in your query itself (and not as operators), then you should escape them with a leading backslash. For instance, to search for (1+1)=2, you would need to write your query as \(1\+1\)\=2.

The reserved characters are: + - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ /

Failing to escape these special characters correctly could lead to a syntax error which prevents your query from running.

下面来看看错误长什么样子吧



还是改成短语匹配吧,有时间再好好研究规避保留字符的方法。


现在贴上将字符串中所有正则表达式的字符进行转义的方法

   public class StringHelper
    {
        /// <summary>
        /// 转义字符串中所有正则特殊字符
        /// </summary>
        /// <param name="input">传入字符串</param>
        /// <returns></returns>
        public static string FilterString(string input)
        {
            input = input.Replace("\\", "\\\\");//先替换“\”,不然后面会因为替换出现其他的“\”
            var r = new Regex("[\\*\\.\\?\\+\\$\\^\\[\\]\\(\\)\\{\\}\\|\\/]");
            var ms = r.Matches(input);
            var list = new List<string>();
            foreach (Match item in ms)
            {
                if (list.Contains(item.Value))
                    continue;
                input = input.Replace(item.Value, "\\" + item.Value);
                list.Add(item.Value);
            }
            return input;
        }
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值