我想为我的用户提供最相关和最好的结果。例如,我奖励具有大标题、描述、附加照片等的记录。对于上下文:记录是自行车路线,具有路线点(坐标)和照片、评论等元数据。
现在,我使用 Hibernate 为这些记录编制了索引,然后在 Hibernate Search 中使用 Lucene 在索引中进行搜索。为了对我的结果进行评分,我根据文档属性构建查询并在 should BooleanJunction 子句 中提升它们(使用 boostedTo()):
bj.should(qb.range().onField("descriptionLength").above(3000).createQuery()).boostedTo(3.0f);
bj.should(qb.range().onField("views.views").above(5000).createQuery()).boostedTo(3.0f);
bj.should(qb.range().onField("nameLength").above(20).createQuery()).boostedTo(1.0f);
bj.should(qb.range().onField("picturesLength").above(0).createQuery()).boostedTo(5.0f);
bj.should(qb.keyword().onField("routePoints.poi.participant").matching("true").createQuery()).boostedTo(10.0f);
为了尝试禁用 Lucene 的评分,我覆盖了 DefaultSimilarity 类,将所有比较设置为 1.0f 评分并通过 Hibernate 配置启用它:
public class IgnoreScoringSimilarity extends DefaultSimilarity {
@Override
public float idf(long docFreq, long numDocs) {
return 1.0f;
}
@Override
public float tf(float freq) {
return 1.0f;
}
@Override
public float coord(int overlap, int maxOverlap) {
return 1.0f;
}
@Override
public float lengthNorm(FieldInvertState state) {
return 1.0f;
}
@Override
public float queryNorm(float sumOfSquaredWeights) {
return 1.0f;
}
}
hibernate 配置:
<property name="hibernate.search.default.similarity" value="com.search.IgnoreScoringSimilarity"/>
这种方法在 90% 的时间里都有效,但是,我仍然看到一些似乎不合适的奇怪结果。我认识的模式是这些路线(文件)的尺寸非常大。一条正常的路线有大约 20-30 个路线点,但是这些不合适的结果有 100-150 个。这让我相信默认的 Lucene 评分仍在发生(由于文档大小,评分更高)。
我在禁用 Lucene 的评分方面做错了什么吗?能有别的解释吗?
最佳答案
我可以建议另一种基于自定义结果排序的方法。您可以在 answer 中阅读相关信息.这个答案有点过时,所以我根据 Lucene API 4.10.1 修改了这个例子。比较器
public abstract class CustomComparator extends FieldComparator<Double> {
double[] scoring;
double bottom;
double topValue;
private FieldCache.Ints[] currentReaderValues;
private String[] fields;
protected abstract double getScore(int[] value);
public CustomComparator(int hitNum, String[] fields) {
this.fields = fields;
scoring = new double[hitNum];
}
int[] fromReaders(int doc) {
int[] result = new int[currentReaderValues.length];
for (int i = 0; i < result.length; i++) {
result[i] = currentReaderValues[i].get(doc);
}
return result;
}
@Override
public int compare(int slot1, int slot2) {
return Double.compare(scoring[slot1], scoring[slot2]);
}
@Override
public void setBottom(int slot) {
this.bottom = scoring[slot];
}
@Override
public void setTopValue(Double top) {
topValue = top;
}
@Override
public int compareBottom(int doc) throws IOException {
double v2 = getScore(fromReaders(doc));
return Double.compare(bottom, v2);
}
@Override
public int compareTop(int doc) throws IOException {
double docValue = getScore(fromReaders(doc));
return Double.compare(topValue, docValue);
}
@Override
public void copy(int slot, int doc) throws IOException {
scoring[slot] = getScore(fromReaders(doc));
}
@Override
public FieldComparator<Double> setNextReader(AtomicReaderContext atomicReaderContext) throws IOException {
currentReaderValues = new FieldCache.Ints[fields.length];
for (int i = 0; i < fields.length; i++) {
currentReaderValues[i] = FieldCache.DEFAULT.getInts(atomicReaderContext.reader(), fields[i], null, false);
}
return this;
}
@Override
public Double value(int slot) {
return scoring[slot];
}
}
搜索示例
public class SortExample {
public static void main(String[] args) throws IOException {
final String[] fields = new String[]{"descriptionLength", "views.views", "nameLength"};
Sort sort = new Sort(
new SortField(
"",
new FieldComparatorSource() {
public FieldComparator newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException {
return new CustomComparator(numHits, fields) {
@Override
protected double getScore(int[] value) {
int descriptionLength = value[0];
int views = value[1];
int nameLength = value[2];
return -((descriptionLength > 2000.0 ? 5.0 : 0.0) +
(views > 5000.0 ? 3.0 : 0.0) +
(nameLength > 20.0 ? 1.0 : 0.0));
}
};
}
}
)
);
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_4_10_4, new StandardAnalyzer());
Directory directory = new RAMDirectory();
IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
addDoc(indexWriter, "score 0", 1000, 1000, 10);
addDoc(indexWriter, "score 5", 3000, 1000, 10);
addDoc(indexWriter, "score 3", 1000, 6000, 10);
addDoc(indexWriter, "score 1", 1000, 1000, 30);
addDoc(indexWriter, "score 4", 1000, 6000, 30);
addDoc(indexWriter, "score 6", 5000, 1000, 30);
addDoc(indexWriter, "score 9", 5000, 6000, 30);
final IndexReader indexReader = DirectoryReader.open(indexWriter, false);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new TermQuery(new Term("all", "all"));
int nDocs = 100;
final TopDocs search = indexSearcher.search(query, null, nDocs, sort);
System.out.println("Max " + search.scoreDocs.length + " " + search.getMaxScore());
for (ScoreDoc sd : search.scoreDocs) {
Document document = indexReader.document(sd.doc);
System.out.println(document.getField("name").stringValue());
}
}
private static void addDoc(IndexWriter indexWriter, String name, int descriptionLength, int views, int nameLength) throws IOException {
Document doc = new Document();
doc.add(new TextField("name", name, Field.Store.YES));
doc.add(new TextField("all", "all", Field.Store.YES));
doc.add(new IntField("descriptionLength", descriptionLength, Field.Store.YES));
doc.add(new IntField("views.views", views, Field.Store.YES));
doc.add(new IntField("nameLength", nameLength, Field.Store.YES));
indexWriter.addDocument(doc);
}
}
代码会输出
score 9
score 6
score 5
score 4
score 3
score 1
score 0
关于java - 如何在 Hibernate Search/Lucene 中禁用默认评分/提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30708833/
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问