mharray mharray - 8 months ago 42
Java Question

Hibernate Search 5.5.3 - Sort by collection size no longer working

I've been trying to migrate from Hibernate Search 5.5.2 to 5.5.3, and I've run into an issue with one of my sort fields. This is the code that was working with 5.5.2 (or maybe it wasn't working, and just wasn't throwing errors?)

public class CollectionCountBridge implements MetadataProvidingFieldBridge {

public void configureFieldMetadata(String name, FieldMetadataBuilder builder) {
builder.field(name, FieldType.INTEGER).sortable(true);

public void set(String name, Object object, Document document, LuceneOptions luceneOptions) {
if (object == null || (!(object instanceof Collection))) {
Collection<?> coll = (Collection<?>) object;
int size = coll.size();

IntField field = new IntField(name, size, (luceneOptions.getStore() != Store.NO) ? Field.Store.YES : Field.Store.NO);



@Field(analyze = Analyze.NO, norms = Norms.YES, index = Index.YES)
@FieldBridge(impl = CollectionCountBridge.class)
public Set<MyCollection> getMyCollection() {
return myCollection;

The code essentially stores the size of the collection as a sortable field. This was based on the documentation which suggested if I need to define a sortable field via a bridge, then I have to implement MetadataProvidingFieldBridge to mark it sortable. The documentation however shows only an example for a string field, whereas I need to use a numeric field.

So following the upgrade to 5.5.3 I started getting errors like: HSEARCH000307: Sort type INT is not compatible with string type of field 'myCollection'

I've tried adding the field to the document in a variety of ways, and nothing seems to work. Some things I've tried:

luceneOptions.addNumericFieldToDocument(name, size, document);

document.add(new SortedNumericDocValuesField(name, size));
//this throws an error on index
java.lang.IllegalArgumentException: cannot change DocValues type from SORTED_NUMERIC to NUMERIC for field "myCollection"

public class CollectionCountBridge extends NumberBridge

So, my question is, what is the correct way to add a sortable numeric field to the index, via a bridge, as of 5.5.3?


It seems you've hit a bug here. For a custom bridge as yours we are failing to properly detect the numeric encoding type. I've filed HSEARCH-2292 for this.

As a work-around, you may create a transient property in your entity which exposes the collection size. To this property, you add @Field and @SortableField which should add the required fields to the index, using the correct types.