简体   繁体   English

将python字典翻译成Solr查询字符串

[英]Translate a python dict into a Solr query string

I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax. 我刚刚开始使用Python,但是我坚持将一组request.POST参数转换为Solr的查询语法所需的语法。

The use case is a form defined like this: 用例是这样定义的一种形式:

class SearchForm(forms.Form):
    text = forms.CharField()
    metadata = forms.CharField()
    figures = forms.CharField()

Upon submission, the form needs to generate a url-encoded string to pass to a URL client that looks like this: 提交后,表单需要生成一个url编码的字符串,以传递给如下所示的URL客户端:

text:myKeyword1+AND+metadata:myKeyword2+AND+figures:myKeyword3

Seems like there should be a simple way to do this. 似乎应该有一种简单的方法来执行此操作。 The closest I can get is 我能得到的最接近的是

for f, v in request.POST.iteritems():
   if v:
       qstring += u'%s\u003A%s+and+' % (f,v)

However in that case the colon (\:) generates a Solr error because it is not getting encoded properly. 但是,在那种情况下,冒号(\\ u003A)会产生Solr错误,因为它没有得到正确的编码。

What is the clean way to do this? 干净的方法是什么?

Thanks! 谢谢!

I would recommend creating a function in the form to handle this rather than in the view. 我建议在窗体中创建一个函数来处理此功能,而不是在视图中创建一个功能。 So after you call form.isValid() to ensure the data is acceptable. 因此,在调用form.isValid()以确保数据可以接受之后。 You can invoke a form.generateSolrQuery() (or whatever name you would like). 您可以调用form.generateSolrQuery()(或您想要的任何名称)。

class SearchForm(forms.Form):
  text = forms.CharField()
  metadata = forms.CharField()
  figures = forms.CharField()

  def generateSolrQuery(self):
    return "+and+".join(["%s\u003A%s" % (f,v) for f,v in self.cleaned_data.items()])

Isn't u'\:' simply the same as u':' , which is escaped in URLs as %3A ? u'\:'是否与u':'完全相同,后者在URL中以%3A转义?

qstring = '+AND+'.join(
    [ u'%s%%3A%s'%(f,v) for f,v in request.POST.iteritems() if f]
    ) 

Use django-haystack . 使用django-haystack It takes care of all the interfacing with Solr - both indexing and querying. 它负责与Solr的所有接口-索引和查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM