如何显示pg-search多重搜索结果的摘录 [英] How to show excerpts from pg-search multisearch results

查看:65
本文介绍了如何显示pg-search多重搜索结果的摘录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Heroku的Rails应用中设置了pg_search:

I've set up pg_search in my Rails app on Heroku:

@query = 'fast'
PgSearch.multisearch(@query) #=>
[#<PgSearch::Document searchable: ferrari, :content: 'this car is really fast'>,
 #<PgSearch::Document searchable: viper, :content: 'a very fast car'>]

我想用content的摘录显示这些结果,以显示匹配发生的位置.当@query仅是一个单词时,我可以调用excerpt(content, @query)以获得我想要的内容,但是excerpt()仅处理完全匹配项,因此,如果:

I'd like to display these results with excerpts from content to show where the match occurs. I can call excerpt(content, @query) to get exactly what I want when @query is only one word, but excerpt() only handles exact matches, so if:

@query = 'car fast'
PgSearch.multisearch(@query) #=>
[#<PgSearch::Document searchable: ferrari, :content: 'this car is really fast'>,
 #<PgSearch::Document searchable: viper, :content: 'a very fast car'>]

然后excerpt(content, @query)为nil,因为content中没有出现确切的短语"car fast".

then excerpt(content, @query) is nil because nowhere in content does the exact phrase 'car fast' appear.

我认为excerpt(content, @query.split(' ').first)对于多词查询至少要显示某物,但是仍然存在诸如此类的情况:

I considered excerpt(content, @query.split(' ').first) to at least show something for multi-word queries, but there are still cases such as this:

@query = 'car?'
@results = PgSearch.multisearch(@query) #=>
[#<PgSearch::Document searchable: ferrari, :content: 'this car is really fast'>,
 #<PgSearch::Document searchable: viper, :content: 'a very fast car'>]
excerpt(@results.first.content, @query) #=> nil

那么,使用pg_search时人们如何显示搜索结果的摘录?

So, how do folks show excerpts from search results when using pg_search?

推荐答案

FWIW—按照上述nertzy的示例,我能够将其与以下代码一起使用:

FWIW— Following nertzy's example above, I was able to get this to work with the following:

PgSearch.multisearch(@query).select("ts_headline(pg_search_documents.content, plainto_tsquery('english', ''' ' || unaccent('#{@query}') || ' ''' || ':*')) AS excerpt")

我无法使plainto_tsquery(?)正常工作,因为它引发了语法错误.我上面的解决方案只是做

I was having trouble getting plainto_tsquery(?) to work, as it was throwing a syntax error. My solution above was simply the result of doing

PgSearch.multisearch(@query).select(["ts_headline(pg_search_documents.content, plainto_tsquery(?)) AS excerpt", @query]).to_sql

,然后为新的plainto_tsquery调用插入to_tsquery参数-我确定这并不是完全正确,但似乎可以正常工作.

and then plugging in the to_tsquery arguments for the new plainto_tsquery call—something I'm sure is not entirely sound, but seems to work.

这篇关于如何显示pg-search多重搜索结果的摘录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆