简体   繁体   中英

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-encoded 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 (\:) 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'\:' 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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