lucene 使用定序的Hibernate搜寻排序

6rvt4ljy  于 2022-11-07  发布在  Lucene
关注(0)|答案(3)|浏览(199)

我把Hibernate搜索从4.3.0.Final升级到了最新的稳定版本5.4.12.Final。除了排序挪威语单词之外,其他都很好。在旧版本的Hibernate中,构造函数中有带locale的SortField:

/**Creates a sort, possibly in reverse, by terms in the given field sorted
   * according to the given locale.
   * @param field  Name of field to sort by, cannot be <code>null</code>.
   * @param locale Locale of values in the field.
   */
  public SortField (String field, Locale locale, boolean reverse) {
    initFieldType(field, STRING);
    this.locale = locale;
    this.reverse = reverse;
  }

但是在新的Hibernate搜索中,SortField没有locale。根据Hibernate参考文档(https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#_analysis),对于外语中的排序词,我们应该使用CollationKeyFilterFactory和normalizer。但是在这个版本的Hibernate搜索中没有这样的类。Maven pom:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-search-orm</artifactId>
   <version>5.11.5.Final</version>
</dependency>

的问题:我应该使用/创建什么在Hibernate搜索排序挪威语单词?
现在我有这样的排序顺序:
测试,测试,测试,测试,测试,测试
正确顺序:
测试,测试,测试,测试,测试,测试
有CollationKeyAnalyzer类,但我不知道如何使用它进行排序:

public final class CollationKeyAnalyzer extends Analyzer {
  private final CollationAttributeFactory factory;

  /**
   * Create a new CollationKeyAnalyzer, using the specified collator.
   *
   * @param collator CollationKey generator
   */
  public CollationKeyAnalyzer(Collator collator) {
    this.factory = new CollationAttributeFactory(collator);
  }

  @Override
  protected TokenStreamComponents createComponents(String fieldName) {
    KeywordTokenizer tokenizer = new KeywordTokenizer(factory, KeywordTokenizer.DEFAULT_BUFFER_SIZE);
    return new TokenStreamComponents(tokenizer, tokenizer);
  }
}

非常相似的问题没有答案:How to do case insensitive sorting of Norwegian characters (Æ, Ø, and Å) using Hibernate Lucene Search?

af7jpaap

af7jpaap1#

我不知道它对你有多大帮助,但是CollationKeyFilterFactory已经过时了,实际上已经被删除了。
在类“Javadoc”中,它表示:
不建议使用。
请改用CollationKeyAnalyzer
您可以找到Javadoc here

jutyujz0

jutyujz02#

但是在这个版本的Hibernate搜索中没有这样的类。
文档的这一部分看起来过时了,我会考虑更新它。
我找到了CollationKeyAnalyzer,但是javadoc声明它已经过时了,应该使用ICUCollationKeyAnalyzer
尝试将此依赖项添加到POM:

<dependency>
   <groupId>org.apache.lucene</groupId>
   <artifactId>lucene-analyzers-icu</artifactId>
   <version>5.5.5</version>
</dependency>

然后创建您自己的分析器类,它使用硬编码的语言环境重新实现ICUCollationKeyAnalyzer

public class MyCollationKeyAnalyzer extends Analyzer {
    private final ICUCollationAttributeFactory factory;

    public MyCollationKeyAnalyzer(Version luceneVersion) {
        this.factory = new ICUCollationAttributeFactory( Collactor.getInstance( Locale.getInstance( "nb_NO" ) ) );
    }

    @Override
    protected TokenStreamComponents createComponents(String fieldName) {
        KeywordTokenizer tokenizer = new KeywordTokenizer(factory, KeywordTokenizer.DEFAULT_BUFFER_SIZE);
        return new TokenStreamComponents(tokenizer, tokenizer);
    }
}

然后创建字段:

@Entity
@Indexed
public class MyEntity {

    // ...

    @Field(name = "title_sort", index = Index.NO, normalizer = @Normalizer(impl = MyCollationKeyAnalyzer.class))
    @SortableField(forField = "title_sort")
    private String title;

   // ...
}

然后按如下方式对该字段进行排序:

FullTextEntityManager ftEm = Search.getFullTextEntityManager( entityManager );
QueryBuilder qb = ...; // The usual
Query luceneQuery = ...; // The usual
FullTextQuery ftQuery = ftEm.createFullTextQuery( luceneQuery, MyEntity.class );
ftQuery.setSort( qb.sort().byField( "title_sort" ).createSort() );
ftQuery.setMaxResults( 20 );
List<MyEntity> hits = ftQuery.getResultList();

我没有尝试过这个,所以让我们知道如果它为您工作。

deyfvvtc

deyfvvtc3#

为了解决排序问题,我创建了自己的NorwegianCollationFactory。这不是完美的解决方案,因为我从旧版本的Hibernate搜索(IndexableBinaryStringTools.class)中复制了代码,但它工作得很好。

挪威语排序规则工厂类

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.util.TokenFilterFactory;

import java.text.Collator;
import java.util.Locale;
import java.util.Map;

public final class NorwegianCollationFactory extends TokenFilterFactory {

    public NorwegianCollationFactory(Map<String, String> args) {
        super(args);
    }

    @Override
    public TokenStream create(TokenStream input) {
        Collator norwegianCollator = Collator.getInstance(new Locale("no", "NO"));
        return new CollationKeyFilter(input, norwegianCollator);
    }

}

排序规则键筛选器类

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

import java.io.IOException;
import java.text.Collator;
import java.util.Objects;

public final class CollationKeyFilter extends TokenFilter {

    // This code is copied from IndexableBinaryStringTools.class from the old version of hibernate search  4.3.0.Final
    private static final CollationKeyFilter.CodingCase[] CODING_CASES = {
            new CollationKeyFilter.CodingCase(7, 1),
            new CollationKeyFilter.CodingCase(14, 6, 2),
            new CollationKeyFilter.CodingCase(13, 5, 3),
            new CollationKeyFilter.CodingCase(12, 4, 4),
            new CollationKeyFilter.CodingCase(11, 3, 5),
            new CollationKeyFilter.CodingCase(10, 2, 6),
            new CollationKeyFilter.CodingCase(9, 1, 7),
            new CollationKeyFilter.CodingCase(8, 0)
    };

    private final Collator collator;
    private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);

    public CollationKeyFilter(TokenStream input, Collator collator) {
        super(input);
        this.collator = (Collator) collator.clone();
    }

    @Override
    public boolean incrementToken() throws IOException {
        if (input.incrementToken()) {
            byte[] collationKey = collator.getCollationKey(termAtt.toString()).toByteArray();
            int encodedLength = getBinaryStringEncodedLength(collationKey.length);
            termAtt.resizeBuffer(encodedLength);
            termAtt.setLength(encodedLength);
            encodeToBinaryString(collationKey, collationKey.length, termAtt.buffer());
            return true;
        } else {
            return false;
        }
    }

    // This code is copied from IndexableBinaryStringTools class from the old version of hibernate search  4.3.0.Final
    private void encodeToBinaryString(byte[] inputArray, int inputLength, char[] outputArray) {
        if (inputLength > 0) {
            int inputByteNum = 0;
            int caseNum = 0;
            int outputCharNum = 0;
            CollationKeyFilter.CodingCase codingCase;
            for (; inputByteNum + CODING_CASES[caseNum].numBytes <= inputLength; ++outputCharNum) {
                codingCase = CODING_CASES[caseNum];
                if (codingCase.numBytes == 2) {
                    outputArray[outputCharNum] = (char) (((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift)
                            + (((inputArray[inputByteNum + 1] & 0xFF) >>> codingCase.finalShift) & codingCase.finalMask) & (short) 0x7FFF);
                } else {
                    outputArray[outputCharNum] = (char) (((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift)
                            + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift)
                            + (((inputArray[inputByteNum + 2] & 0xFF) >>> codingCase.finalShift) & codingCase.finalMask) & (short) 0x7FFF);
                }
                inputByteNum += codingCase.advanceBytes;
                if (++caseNum == CODING_CASES.length) {
                    caseNum = 0;
                }
            }
            codingCase = CODING_CASES[caseNum];
            if (inputByteNum + 1 < inputLength) {
                outputArray[outputCharNum++] = (char) ((((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift)
                        + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift)) & (short) 0x7FFF);
                outputArray[outputCharNum] = (char) 1;
            } else if (inputByteNum < inputLength) {
                outputArray[outputCharNum++] = (char) (((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) & (short) 0x7FFF);
                outputArray[outputCharNum] = caseNum == 0 ? (char) 1 : (char) 0;
            } else {
                outputArray[outputCharNum] = (char) 1;
            }
        }
    }

    // This code is copied from IndexableBinaryStringTools class from the old version of hibernate search 4.3.0.Final
    private int getBinaryStringEncodedLength(int inputLength) {
        return (int) ((8L * inputLength + 14L) / 15L) + 1;
    }

    // This code is copied from IndexableBinaryStringTools class from the old version of hibernate search 4.3.0.Final
    private static class CodingCase {
        int numBytes;
        int initialShift;
        int middleShift;
        int finalShift;
        int advanceBytes = 2;
        short middleMask;
        short finalMask;

        CodingCase(int initialShift, int middleShift, int finalShift) {
            this.numBytes = 3;
            this.initialShift = initialShift;
            this.middleShift = middleShift;
            this.finalShift = finalShift;
            this.finalMask = (short) ((short) 0xFF >>> finalShift);
            this.middleMask = (short) ((short) 0xFF << middleShift);
        }

        CodingCase(int initialShift, int finalShift) {
            this.numBytes = 2;
            this.initialShift = initialShift;
            this.finalShift = finalShift;
            this.finalMask = (short) ((short) 0xFF >>> finalShift);
            if (finalShift != 0) {
                advanceBytes = 1;
            }
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        CollationKeyFilter that = (CollationKeyFilter) o;
        return Objects.equals(collator, that.collator) &&
                Objects.equals(termAtt, that.termAtt);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), collator, termAtt);
    }

}

实体Map示例:

@Entity
@NormalizerDef(name = "textSortNormalizer",
        filters = {
                @TokenFilterDef(factory = LowerCaseFilterFactory.class),
                @TokenFilterDef(factory = PatternReplaceFilterFactory.class, params = {
                        @Parameter(name = "pattern", value = "('-&\\.,\\(\\))"),
                        @Parameter(name = "replacement", value = " "),
                        @Parameter(name = "replace", value = "all")
                }),
                @TokenFilterDef(factory = PatternReplaceFilterFactory.class, params = {
                        @Parameter(name = "pattern", value = "([^0-9\\p{L} ])"),
                        @Parameter(name = "replacement", value = ""),
                        @Parameter(name = "replace", value = "all")
                }),
                @TokenFilterDef(factory = NorwegianCollationFactory.class)
        }
)
public class Entity {

    @Field(name = "name_for_sort", normalizer = @Normalizer(definition = "textSortNormalizer"))
    @SortableField(forField = "name_for_sort")
    private String name;

}

相关问题