doulvyi2172 2018-03-20 03:01
浏览 38

如何逃避查询参数?

I'm using bleve (with a http server in front) to index and query documents.

I need to execute a query as below which should query documents matching channelID value. How can escape query fields(in this case the value of channelID) in the query syntax?

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

I can't just urlencode it because if I do it won't match the field from the documented indexed(which has the value unencoded).

Update(testcase)

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()
}
  • 写回答

1条回答 默认 最新

  • duanqian3464 2018-03-20 08:16
    关注

    You just put a backslash before the special characters. You find a list of all special characters in the docs (at the bottom under escaping): http://www.blevesearch.com/docs/Query-String-Query/

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号