feat(api): enhanced facet number handling (#2772)

This commit is contained in:
Alex
2026-10-18 09:07:15 +01:00
committed by GitHub
parent bb0e6cc1a7
commit 0cb1d73327
5 changed files with 141 additions and 10 deletions
@@ -19,10 +19,16 @@ public record FacetGroupsResponse(List<Link> links, List<FacetGroup> facets) {
} }
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public record FacetLink(@JsonSerialize(using = RelSerializer.class) List<String> rel, String href, String type, String title, String value, Properties properties) { public record FacetLink(@JsonSerialize(using = RelSerializer.class) List<String> rel, String href, String type, Boolean templated, String title, String value, Properties properties) {
public FacetLink(List<String> rel, String href, String type, String title, String value, Properties properties) {
this(rel, href, type, null, title, value, properties);
}
} }
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public record Properties(Long numberOfItems) { public record Properties(Long numberOfItems, Number min, Number max) {
public Properties(Long numberOfItems) {
this(numberOfItems, null, null);
}
} }
} }
@@ -11,6 +11,7 @@ import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root; import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.booklore.browse.FacetLogic; import org.booklore.browse.FacetLogic;
import org.booklore.browse.ParamsHash; import org.booklore.browse.ParamsHash;
@@ -31,6 +32,7 @@ import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
@Service @Service
@@ -102,8 +104,25 @@ public class BookFacetService {
new FacetDef("comic_creator", "Comic Creators", (cb, root, _) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("creatorMappings", JoinType.LEFT).join("creator", JoinType.LEFT).get("name")) new FacetDef("comic_creator", "Comic Creators", (cb, root, _) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("creatorMappings", JoinType.LEFT).join("creator", JoinType.LEFT).get("name"))
); );
private static final Set<String> NUMBER_FACETS = Set.of(
"page_count", "published_year", "file_size", "match_score",
"amazon_rating", "goodreads_rating", "hardcover_rating", "ranobedb_rating",
"lubimyczytac_rating", "audible_rating", "applebooks_rating");
private static final List<String> RATING_BANDS = List.of("0..<1", "1..<2", "2..<3", "3..<4", "4..<4.5", "4.5..*");
private static final Map<String, List<String>> NUMBER_BANDS = Map.of(
"match_score", List.of("95..*", "90..<95", "80..<90", "70..<80", "50..<70", "30..<50", "0..<30"),
"amazon_rating", RATING_BANDS,
"goodreads_rating", RATING_BANDS,
"hardcover_rating", RATING_BANDS,
"ranobedb_rating", RATING_BANDS,
"lubimyczytac_rating", RATING_BANDS,
"audible_rating", RATING_BANDS,
"applebooks_rating", RATING_BANDS);
private final AuthenticationService authenticationService; private final AuthenticationService authenticationService;
private final BookFilterSpecifications filterSpecifications; private final BookFilterSpecifications filterSpecifications;
private final BookFacetRegistry facetRegistry;
private final BookSortRegistry sortRegistry; private final BookSortRegistry sortRegistry;
private final BrowseScopeFactory scopeFactory; private final BrowseScopeFactory scopeFactory;
private final EntityManager entityManager; private final EntityManager entityManager;
@@ -130,6 +149,10 @@ public class BookFacetService {
for (FacetDef def : FACETS) { for (FacetDef def : FACETS) {
Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, scope, def.key()); Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, scope, def.key());
if (NUMBER_FACETS.contains(def.key())) {
groups.add(numberGroup(def, base, scope, builder));
continue;
}
var counts = count(def, base, scope); var counts = count(def, base, scope);
if ("file_type".equals(def.key())) { if ("file_type".equals(def.key())) {
counts = Stream.concat(counts.stream(), count(PHYSICAL_FILE_TYPE, base, scope).stream()) counts = Stream.concat(counts.stream(), count(PHYSICAL_FILE_TYPE, base, scope).stream())
@@ -175,6 +198,42 @@ public class BookFacetService {
.toList(); .toList();
} }
@SuppressWarnings("unchecked")
private FacetGroup numberGroup(FacetDef def, Specification<BookEntity> base, BrowseScope scope, FacetResponseBuilder builder) {
List<String> bands = NUMBER_BANDS.getOrDefault(def.key(), List.of());
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<BookEntity> root = cq.from(BookEntity.class);
Expression<Number> value = (Expression<Number>) def.value().apply(cb, root, scope);
List<Selection<?>> columns = new ArrayList<>();
columns.add(cb.min(value).alias("min"));
columns.add(cb.max(value).alias("max"));
for (String band : bands) {
Specification<BookEntity> inBand = facetRegistry.toSpecification(def.key(), List.of(band), FacetLogic.OR, scope.userId());
columns.add(countMatching(inBand, root, cq, cb).alias(band));
}
cq.multiselect(columns);
Predicate basePredicate = base.toPredicate(root, cq, cb);
if (basePredicate != null) {
cq.where(basePredicate);
}
Tuple row = entityManager.createQuery(cq).getSingleResult();
List<FacetResponseBuilder.FacetCount> counts = bands.stream()
.map(band -> new FacetResponseBuilder.FacetCount(band, row.get(band, Long.class)))
.toList();
return builder.numberGroup(def.key(), def.title(), counts, row.get("min", Number.class), row.get("max", Number.class));
}
// COUNT(DISTINCT CASE WHEN <filter matches> THEN id END), so one query can count several filters at once
private Expression<Long> countMatching(Specification<BookEntity> filter, Root<BookEntity> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
Expression<Long> matchingId = cb.<Long>selectCase()
.when(filter.toPredicate(root, cq, cb), root.get("id"))
.otherwise(cb.nullLiteral(Long.class));
return cb.countDistinct(matchingId);
}
private static Join<?, ?> metadata(Root<BookEntity> root) { private static Join<?, ?> metadata(Root<BookEntity> root) {
return root.join("metadata", JoinType.LEFT); return root.join("metadata", JoinType.LEFT);
} }
@@ -79,7 +79,7 @@ public class BookFilterSpecification {
return result; return result;
} }
private record NumericRange<T>(T min, T max) { private record NumericRange<T>(T min, T max, boolean maxExclusive) {
} }
private static <T extends Comparable<? super T>> List<NumericRange<T>> parseNumericRanges(List<String> values, Function<String, T> parser, String paramName) { private static <T extends Comparable<? super T>> List<NumericRange<T>> parseNumericRanges(List<String> values, Function<String, T> parser, String paramName) {
@@ -98,7 +98,7 @@ public class BookFilterSpecification {
} }
if (!invalid.isEmpty()) { if (!invalid.isEmpty()) {
throw new APIException("Invalid " + paramName + " values: " + invalid throw new APIException("Invalid " + paramName + " values: " + invalid
+ ". Expected a number, min..max, min..*, or *..max. Minimum must not exceed maximum.", HttpStatus.BAD_REQUEST); + ". Expected a number, min..max, min..*, *..max, or min..<max to exclude max. Minimum must not exceed maximum.", HttpStatus.BAD_REQUEST);
} }
return ranges; return ranges;
} }
@@ -108,11 +108,15 @@ public class BookFilterSpecification {
int separator = value.indexOf(".."); int separator = value.indexOf("..");
if (separator < 0) { if (separator < 0) {
T exact = parser.apply(value); T exact = parser.apply(value);
return new NumericRange<>(exact, exact); return new NumericRange<>(exact, exact, false);
} }
String minPart = value.substring(0, separator).trim(); String minPart = value.substring(0, separator).trim();
String maxPart = value.substring(separator + 2).trim(); String maxPart = value.substring(separator + 2).trim();
if (minPart.equals("*") && maxPart.equals("*")) { boolean maxExclusive = maxPart.startsWith("<");
if (maxExclusive) {
maxPart = maxPart.substring(1).trim();
}
if (maxPart.equals("*") && (maxExclusive || minPart.equals("*"))) {
return null; return null;
} }
T min = minPart.equals("*") ? null : parser.apply(minPart); T min = minPart.equals("*") ? null : parser.apply(minPart);
@@ -120,7 +124,7 @@ public class BookFilterSpecification {
if (min != null && max != null && min.compareTo(max) > 0) { if (min != null && max != null && min.compareTo(max) > 0) {
return null; return null;
} }
return new NumericRange<>(min, max); return new NumericRange<>(min, max, maxExclusive);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return null; return null;
} }
@@ -133,16 +137,21 @@ public class BookFilterSpecification {
if (range.min() != null && range.max() != null) { if (range.min() != null && range.max() != null) {
predicates.add(cb.and( predicates.add(cb.and(
cb.greaterThanOrEqualTo(field, range.min()), cb.greaterThanOrEqualTo(field, range.min()),
cb.lessThanOrEqualTo(field, range.max()))); upperBound(cb, field, range)));
} else if (range.min() != null) { } else if (range.min() != null) {
predicates.add(cb.greaterThanOrEqualTo(field, range.min())); predicates.add(cb.greaterThanOrEqualTo(field, range.min()));
} else { } else {
predicates.add(cb.lessThanOrEqualTo(field, range.max())); predicates.add(upperBound(cb, field, range));
} }
} }
return cb.or(predicates.toArray(Predicate[]::new)); return cb.or(predicates.toArray(Predicate[]::new));
} }
private static <T extends Comparable<? super T>> Predicate upperBound(
CriteriaBuilder cb, Expression<T> field, NumericRange<T> range) {
return range.maxExclusive() ? cb.lessThan(field, range.max()) : cb.lessThanOrEqualTo(field, range.max());
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) { private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) {
for (Join<X, ?> join : from.getJoins()) { for (Join<X, ?> join : from.getJoins()) {
@@ -10,6 +10,7 @@ import org.booklore.model.dto.browse.FacetGroupsResponse.Properties;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream;
final class FacetResponseBuilder { final class FacetResponseBuilder {
@@ -54,6 +55,16 @@ final class FacetResponseBuilder {
return new FacetGroup(new Metadata("facet", key, title), links); return new FacetGroup(new Metadata("facet", key, title), links);
} }
FacetGroup numberGroup(String key, String title, List<FacetCount> counts, Number min, Number max) {
FacetGroup group = group(key, title, counts);
if (min == null) {
return group;
}
String href = pageLink("facet=" + BrowseParams.encode(key + ":") + "{min}..{max}");
FacetLink range = new FacetLink(List.of("facet"), href, Link.JSON_TYPE, true, title, null, new Properties(null, min, max));
return new FacetGroup(group.metadata(), Stream.concat(Stream.of(range), group.links().stream()).toList());
}
List<Link> selfLinks() { List<Link> selfLinks() {
return List.of(Link.json(List.of("self"), href(facetPath))); return List.of(Link.json(List.of("self"), href(facetPath)));
} }
@@ -123,7 +123,7 @@ class BookFacetServiceTest {
.build(); .build();
} }
private void book(String title, String genre, String authorName) { private BookMetadataEntity book(String title, String genre, String authorName) {
BookEntity bookEntity = BookEntity.builder() BookEntity bookEntity = BookEntity.builder()
.library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build(); .library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build();
em.persist(bookEntity); em.persist(bookEntity);
@@ -132,6 +132,7 @@ class BookFacetServiceTest {
metadata.setAuthors(List.of(author(authorName))); metadata.setAuthors(List.of(author(authorName)));
em.persist(metadata); em.persist(metadata);
bookEntity.setMetadata(metadata); bookEntity.setMetadata(metadata);
return metadata;
} }
private CategoryEntity category(String name) { private CategoryEntity category(String name) {
@@ -300,6 +301,51 @@ class BookFacetServiceTest {
assertThat(group(response, "author").links()).hasSize(100); assertThat(group(response, "author").links()).hasSize(100);
} }
@Test
void numberFacetBoundsCoverValuesPastTheCap() {
for (int i = 1; i <= 101; i++) {
book("T" + i, "Genre", "Author").setPageCount(i);
}
em.flush();
FacetGroupsResponse response = facetService.getFacets(null, null, null);
FacetGroup pageCount = group(response, "page_count");
assertThat(pageCount.links()).hasSize(1);
FacetLink range = pageCount.links().getFirst();
assertThat(range.templated()).isTrue();
assertThat(range.href()).isEqualTo("/api/v1/books/page?facet=page_count%3A{min}..{max}");
assertThat(range.properties().min().intValue()).isEqualTo(1);
assertThat(range.properties().max().intValue()).isEqualTo(101);
assertThat(group(response, "genre").links()).noneMatch(l -> Boolean.TRUE.equals(l.templated()));
}
@Test
void ratingFacetCountsBandsAcrossEveryValue() {
for (int i = 0; i < 150; i++) {
book("R" + i, "Genre", "Author").setGoodreadsRating(3.5 + i / 1000.0);
}
book("Four", "Genre", "Author").setGoodreadsRating(4.0);
book("Edge", "Genre", "Author").setGoodreadsRating(4.5);
book("High", "Genre", "Author").setGoodreadsRating(4.8);
em.flush();
FacetGroup goodreads = group(facetService.getFacets(List.of("goodreads_rating:4..<4.5"), null, null), "goodreads_rating");
FacetLink range = goodreads.links().getFirst();
assertThat(range.templated()).isTrue();
assertThat(range.href()).isEqualTo("/api/v1/books/page?facet=goodreads_rating%3A4..%3C4.5&facet=goodreads_rating%3A{min}..{max}");
assertThat(range.properties().min().doubleValue()).isEqualTo(3.5);
assertThat(range.properties().max().doubleValue()).isEqualTo(4.8);
assertThat(goodreads.links()).filteredOn(l -> l.templated() == null).extracting(FacetLink::value)
.containsExactly("0..<1", "1..<2", "2..<3", "3..<4", "4..<4.5", "4.5..*");
assertThat(count(goodreads, "0..<1")).isZero();
assertThat(count(goodreads, "3..<4")).isEqualTo(150);
assertThat(count(goodreads, "4..<4.5")).isEqualTo(1);
assertThat(count(goodreads, "4.5..*")).isEqualTo(2);
assertThat(link(goodreads, "4..<4.5").rel()).containsExactly("self", "facet");
}
@Test @Test
void activeFacetIsMarkedSelfWithCurrentPageHref() { void activeFacetIsMarkedSelfWithCurrentPageHref() {
book("A", "Horror", "Alice"); book("A", "Horror", "Alice");