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.
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-encod开发者_C百科ed string to pass to a URL client that looks like this:
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 (\u003A) generates a Solr error because it is not getting encoded properly.
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. You can invoke a form.generateSolrQuery() (or whatever name you would like).
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'\u003A'
simply the same as u':'
, which is escaped in URLs as %3A
?
qstring = '+AND+'.join(
[ u'%s%%3A%s'%(f,v) for f,v in request.POST.iteritems() if f]
)
Use django-haystack. It takes care of all the interfacing with Solr - both indexing and querying.
精彩评论