为什么我的搜索结果没有显示?

时间:2013-05-12 04:43:38

标签: google-app-engine python-2.7 full-text-search

当我在我的网络表单中搜索时,似乎找到了匹配项,但它们未显示:

enter image description here

如何进行SERP显示?我的代码是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <link rel="stylesheet" type="text/css" href="/static/css/main.css"/>
    <title>Search Demonstration App</title>
  </head>
  <body>

    <form action="/sign" method="post">
      <div>Search Demo</div>
      <div><textarea name="search" rows="1" cols="60"></textarea></div>
      <div><input type="submit" value="Search"/></div>
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Comment"/></div>
    </form>

    {{number_returned}} of {{results.number_found}} comments found <p>
    {% for scored_document in results %}
      {% for field in scored_document.fields %}
        {{field.value}} &nbsp;
      {% endfor %}
      <p>
    {% endfor %}

    <a href="{{ url }}">{{ url_linktext }}</a>

  </body>
</html>

和.py

class SearchAPI(webapp.RequestHandler):
    """Handles search requests for comments."""

    def get(self):
        """Handles a get request with a query."""
        uri = urlparse(self.request.uri)
        query = ''
        if uri.query:
            query = parse_qs(uri.query)
            query = query['query'][0]

        # sort results by author descending
        expr_list = [search.SortExpression(
            expression='author', default_value='',
            direction=search.SortExpression.DESCENDING)]
        # construct the sort options 
        sort_opts = search.SortOptions(
             expressions=expr_list)
        query_options = search.QueryOptions(
            limit=3,
            sort_options=sort_opts)
        query_obj = search.Query(query_string=query, options=query_options)
        results = search.Index(name='ad').search(query=query_obj)
    #logging.info("number of results:" +len(results))
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'results': results,
            'number_returned': len(results.results),
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'searchapi.html')
        self.response.out.write(template.render(path, template_values))

索引构建如下:

class CreateAdHandler(BaseHandler):

    def post(self):
    ad = Ad.get_by_id(self.session.get('ad_id'))
        city_entity = montaomodel.City.all().filter('name =', ad.city).get()
        region_entity = montaomodel.Region.all().filter('name =', ad.region).get()
        form = PreviewAdForm(self.request.params)
        if form.validate():
            ad.set_password(self.request.get('password'))
            ad.published = True
            ad.put()
            doc = search.Document(doc_id=str(ad.key()),
                 fields=[search.TextField(name='title', 
                           value=ad.title),search.TextField(name='text', 
                           value=ad.text),search.TextField(name='city', 
                           value=ad.city),search.TextField(name='region', 
                           value=ad.region),search.NumberField(name='cityID', 
                           value=city_entity.key().id()),search.NumberField(name='regionID', 
                           value=region_entity.key().id()),search.NumberField(name='category', 
                           value=int(ad.category)), search.NumberField(name='constant', 
                           value=1), search.NumberField(name='adID', 
                           value=ad.key().id()),                 
                 search.TextField(name='name',
                           value=ad.name
                           )],
         language='en')
            search.Index(name='ad').add(doc) # should this be "put" instead? see https://developers.google.com/appengine/docs/python/search/overview#Deleting_Documents

            self.redirect('/vi/%d.html' % (ad.key().id(), ))
        else:
            logging.info('form did not validate')
            self.render_jinja('preview', form=form, ad=ad) 

更新

通过仔细调试,显示此行不起作用:{% for f in scored_document.fields %}。我发现调试但我不知道为什么。所以至少我现在更接近解决方案但是没有完成。

更新2

我无法理解为什么不访问这些字段。我可以添加数据并将其输出到控制台:

INFO     2013-05-14 01:00:53,944 main.py:4437] result: search.ScoredDocument(doc_id=u'eb24f746-c60a-462c-9f64-a06ad6a823cb', fields=[search.TextField(name=u'author', value=u'test'), search.TextField(name=u'comment', value=u'test'), search.DateField(name=u'date', value=datetime.datetime(2013, 5, 13, 0, 0))], language=u'en', rank=74648319L)
INFO     2013-05-14 01:00:53,944 main.py:4437] result: search.ScoredDocument(doc_id=u'af0de892-0e59-4c12-bd9e-6e8caa2067d4', fields=[search.TextField(name=u'author', value=u'test'), search.TextField(name=u'comment', value=u'test'), search.DateField(name=u'date', value=datetime.datetime(2013, 5, 14, 0, 0))], language=u'en', rank=74653247L)

此日志记录现在就像这样:

for r in results:
    logging.info("result: " + str(r))

因此,如果我可以将这样的数据记录到控制台,为什么我不能将其输出到我的页面?

2 个答案:

答案 0 :(得分:1)

我认为您需要在returned_fields中加入QueryOptions属性。 (字段名称列表。)

答案 1 :(得分:1)

好像你应该在模板中迭代results.results

{% for scored_document in results.results %}