【问题标题】:How to escape query params?如何转义查询参数?
【发布时间】:2018-03-20 03:01:47
【问题描述】:

我正在使用bleve(前面有一个http 服务器)来索引和query 文档。

我需要执行如下查询,它应该查询匹配channelID 值的文档。如何在查询语法中转义查询字段(在本例中为 channelID 的值)?

 query.NewQueryStringQuery("channelID:http://example.com?some-params-with$-+badChars"). 

我不能只对其进行 urlencode,因为如果我这样做,它将与记录索引中的字段不匹配(其值未编码)。

更新(测试用例)

package main

import (
    "github.com/blevesearch/bleve"
    //"github.com/blevesearch/bleve/search"
    "github.com/blevesearch/bleve/search/query"

    "bytes"
    "flag"
    log "github.com/golang/glog"
)

type Data struct {
    ID      string
    Message string
    URI     string
}

func main() {
    flag.Parse()
    defer log.Flush()

    mapping := bleve.NewIndexMapping()
    index, err := bleve.New("example.bleve", mapping)
    if err != nil {
        panic(err)
    }
    d := Data{
        ID:      "someID",
        Message: "Hello",
        URI:     `https://www.google.co.uk/search?q=google+search&oq={}///\}ie=UTF-8`,
    }
    if err := index.Index(d.ID, d); err != nil {
        panic(err)
    }

    //index, _ := bleve.Open("example.bleve")
    query := query.NewQueryStringQuery("URI:" + Escape(d.URI))
    searchRequest := bleve.NewSearchRequest(query)
    result, _ := index.Search(searchRequest)
    log.Errorf("total hits %v", result.Total)
}

func Escape(s string) string {
    ra := []string{"+", "-", "=",
        "&", "|", ">",
        "<", "!", "(", ")", "{",
        "}", "[", "]", "^",
        `~`, `*`, `?`, `:`, `\\`, `/`, `\`, ` `}
    exists := func(v string) bool {
        for _, s := range ra {
            if v == s {
                return true
            }
        }
        return false
    }
    buf := bytes.NewBuffer(nil)
    var prevBack bool
    for _, v := range s {
        if prevBack || !exists(string(v)) {
            buf.WriteString(string(v))
            prevBack = false
        } else {
            buf.WriteString(`\`)
            buf.WriteString(string(v))
            if string(v) == `\` {
                prevBack = true
            }
        }
    }
    return buf.String()
}

【问题讨论】:

    标签: go bleve


    【解决方案1】:

    您只需在特殊字符前加一个反斜杠。您可以在文档中找到所有特殊字符的列表(在底部转义下):http://www.blevesearch.com/docs/Query-String-Query/

    【讨论】:

    • 我确实做到了,但似乎没有用。我已经用测试用例更新了问题。
    猜你喜欢
    • 2015-11-17
    • 2017-11-13
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多