Hibernate Search Order by child-count

2020-05-04 16:20发布

问题:

Consider:

@Indexed
@Entity
public class TParent  implements java.io.Serializable {

 .....
 private Set<TChild> TChildSet = new HashSet<TChild>(0);

 @ContainedIn
 @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="TParent")
 public Set<TChild> getTChildSet() {
     return this.TChildSet;
 }

A query would be something like this:

FullTextQuery hibQuery = fullTextSession.createFullTextQuery( luceneQuery );
hibQuery.setSort( ... ) 

How can a sort-by-child-count be achieved?

In other words, the order of the TParent list returned would be dictated by the TChildSet count.

I know an @Formula can be used in SQL circumstances. I'm not sure if something similar can be used for Lucene?

Any help, pointers, comments even critique welcome.

Thanks Very Much John

回答1:

In hibernate search, you can make a custom Bridge for this purpose.

Something along the lines of:

@FieldBridge(impl = com.myco.myapp.CollectionCountBridge.class)
@ContainedIn
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="TParent")
public Set<TChild> getTChildSet() {
     return this.TChildSet;
}

With the custom bridge implementation:

public class CollectionCountBridge extends PaddedIntegerBridge {

    @Override
    public String objectToString(Object object) {
        if (object == null || (!(object instanceof Collection))) {
            return null;
        }
        Collection<?> coll = (Collection<?>) object;
        return super.objectToString(coll.size());
    }
}