之前一直觉的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;
}
}