feat(api): individual facet endpoint (#2779)
This commit is contained in:
@@ -118,6 +118,24 @@ public class BookController {
|
|||||||
return ResponseEntity.ok(bookFacetService.getFacets(facet, facetLogic, query));
|
return ResponseEntity.ok(bookFacetService.getFacets(facet, facetLogic, query));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Get one book facet", description = "Values and counts for a single facet, scoped by the same facet, facet_logic, and query parameters as the page endpoint. The facet omits its own selections from its counts.")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Facet values returned successfully")
|
||||||
|
@GetMapping("/facets/{facetName}")
|
||||||
|
public ResponseEntity<FacetGroupsResponse> getBookFacet(
|
||||||
|
@Parameter(description = "Facet name (for example author, genre, page_count, or goodreads_rating)")
|
||||||
|
@PathVariable String facetName,
|
||||||
|
@Parameter(hidden = true) Pageable pageable,
|
||||||
|
@Parameter(description = "Facet selection in key:value form; repeatable")
|
||||||
|
@RequestParam(required = false) List<String> facet,
|
||||||
|
@Parameter(description = "How facet values combine within a group: and, or, or not")
|
||||||
|
@RequestParam(name = "facet_logic", required = false) String facetLogic,
|
||||||
|
@Parameter(description = "Free-text search applied to the counts")
|
||||||
|
@RequestParam(required = false) String query,
|
||||||
|
@Parameter(description = "Case-insensitive text the values must contain; author, genre, tag, mood, series, publisher, language, narrator, and comic facets only")
|
||||||
|
@RequestParam(required = false) String search) {
|
||||||
|
return ResponseEntity.ok(bookFacetService.getFacet(facetName, facet, facetLogic, query, search, pageable));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get matching book ids", description = "Returns every book id matching the given sort, facet, facet_logic, and query parameters, in sort order. For select-all over the current filters.")
|
@Operation(summary = "Get matching book ids", description = "Returns every book id matching the given sort, facet, facet_logic, and query parameters, in sort order. For select-all over the current filters.")
|
||||||
@ApiResponse(responseCode = "200", description = "Matching book ids returned successfully")
|
@ApiResponse(responseCode = "200", description = "Matching book ids returned successfully")
|
||||||
@GetMapping("/ids")
|
@GetMapping("/ids")
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import jakarta.persistence.Tuple;
|
|||||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
import jakarta.persistence.criteria.CriteriaQuery;
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
import jakarta.persistence.criteria.Expression;
|
import jakarta.persistence.criteria.Expression;
|
||||||
|
import jakarta.persistence.criteria.From;
|
||||||
import jakarta.persistence.criteria.Join;
|
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;
|
||||||
@@ -14,8 +15,10 @@ import jakarta.persistence.criteria.Root;
|
|||||||
import jakarta.persistence.criteria.Selection;
|
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.Link;
|
||||||
import org.booklore.browse.ParamsHash;
|
import org.booklore.browse.ParamsHash;
|
||||||
import org.booklore.config.security.service.AuthenticationService;
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
|
import org.booklore.exception.ApiError;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
||||||
@@ -23,6 +26,7 @@ import org.booklore.model.entity.BookEntity;
|
|||||||
import org.booklore.model.entity.BookFileEntity;
|
import org.booklore.model.entity.BookFileEntity;
|
||||||
import org.booklore.model.entity.UserBookProgressEntity;
|
import org.booklore.model.entity.UserBookProgressEntity;
|
||||||
import org.booklore.model.enums.ReadStatus;
|
import org.booklore.model.enums.ReadStatus;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.jpa.domain.Specification;
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
@@ -120,6 +124,10 @@ public class BookFacetService {
|
|||||||
"audible_rating", RATING_BANDS,
|
"audible_rating", RATING_BANDS,
|
||||||
"applebooks_rating", RATING_BANDS);
|
"applebooks_rating", RATING_BANDS);
|
||||||
|
|
||||||
|
private static final Set<String> NAME_FACETS = Set.of(
|
||||||
|
"author", "genre", "tag", "mood", "series", "publisher", "language", "narrator",
|
||||||
|
"comic_character", "comic_team", "comic_location", "comic_creator");
|
||||||
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final BookFilterSpecifications filterSpecifications;
|
private final BookFilterSpecifications filterSpecifications;
|
||||||
private final BookFacetRegistry facetRegistry;
|
private final BookFacetRegistry facetRegistry;
|
||||||
@@ -149,37 +157,90 @@ 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(facetGroup(def, base, scope, builder));
|
||||||
groups.add(numberGroup(def, base, scope, builder));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
var counts = count(def, base, scope);
|
|
||||||
if ("file_type".equals(def.key())) {
|
|
||||||
counts = Stream.concat(counts.stream(), count(PHYSICAL_FILE_TYPE, base, scope).stream())
|
|
||||||
.sorted(
|
|
||||||
Comparator.comparingLong(FacetResponseBuilder.FacetCount::count)
|
|
||||||
.reversed()
|
|
||||||
.thenComparing(FacetResponseBuilder.FacetCount::value)
|
|
||||||
)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
groups.add(builder.group(def.key(), def.title(), counts));
|
|
||||||
}
|
}
|
||||||
return new FacetGroupsResponse(builder.selfLinks(), groups);
|
return new FacetGroupsResponse(builder.selfLinks(), groups);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public FacetGroupsResponse getFacet(String facetName, List<String> facet, String facetLogicParam, String query, String search, Pageable pageable) {
|
||||||
|
FacetDef def = findFacet(facetName);
|
||||||
|
boolean nameFacet = NAME_FACETS.contains(def.key());
|
||||||
|
String term = search == null || search.isBlank() ? null : search.trim();
|
||||||
|
if (term != null && !nameFacet) {
|
||||||
|
throw ApiError.INVALID_FACET.createException("Facet cannot be searched: " + facetName);
|
||||||
|
}
|
||||||
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
|
BrowseScope scope = scopeFactory.from(user);
|
||||||
|
|
||||||
|
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||||
|
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||||
|
String preserved = BrowseParams.preserved(facet, facetLogicParam, query);
|
||||||
|
Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, scope, def.key());
|
||||||
|
String path = FACET_PATH + "/" + def.key();
|
||||||
|
FacetResponseBuilder builder = new FacetResponseBuilder(PAGE_PATH, path, preserved, facet);
|
||||||
|
|
||||||
|
if (!nameFacet) {
|
||||||
|
FacetGroup group = facetGroup(def, base, scope, builder);
|
||||||
|
return new FacetGroupsResponse(builder.selfLinks(), List.of(group));
|
||||||
|
}
|
||||||
|
|
||||||
|
int page = pageable.getPageNumber();
|
||||||
|
int limit = Math.min(pageable.getPageSize(), MAX_VALUES);
|
||||||
|
int offset = page * limit;
|
||||||
|
// One extra value shows whether a next page exists
|
||||||
|
List<FacetResponseBuilder.FacetCount> counts = count(def, base, scope, term, offset, limit + 1);
|
||||||
|
boolean hasNext = counts.size() > limit;
|
||||||
|
FacetGroup group = builder.group(def.key(), def.title(), hasNext ? counts.subList(0, limit) : counts);
|
||||||
|
|
||||||
|
String pagePreserved = term == null ? preserved : joinParams(preserved, "search=" + BrowseParams.encode(term));
|
||||||
|
List<Link> links = new ArrayList<>();
|
||||||
|
links.add(Link.json(List.of("self"), href(path, joinParams(pagePreserved, "page=" + page + "&size=" + limit))));
|
||||||
|
if (hasNext) {
|
||||||
|
links.add(Link.json(List.of("next"), href(path, joinParams(pagePreserved, "page=" + (page + 1) + "&size=" + limit))));
|
||||||
|
}
|
||||||
|
return new FacetGroupsResponse(links, List.of(group));
|
||||||
|
}
|
||||||
|
|
||||||
// Package-private: lets tests reset the shared singleton cache between runs.
|
// Package-private: lets tests reset the shared singleton cache between runs.
|
||||||
void clearCache() {
|
void clearCache() {
|
||||||
cache.invalidateAll();
|
cache.invalidateAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private FacetDef findFacet(String facetName) {
|
||||||
|
return FACETS.stream()
|
||||||
|
.filter(def -> def.key().equals(facetName))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> ApiError.INVALID_FACET.createException("Unknown facet: " + facetName));
|
||||||
|
}
|
||||||
|
|
||||||
|
private FacetGroup facetGroup(FacetDef def, Specification<BookEntity> base, BrowseScope scope, FacetResponseBuilder builder) {
|
||||||
|
if (NUMBER_FACETS.contains(def.key())) {
|
||||||
|
return numberGroup(def, base, scope, builder);
|
||||||
|
}
|
||||||
|
var counts = count(def, base, scope);
|
||||||
|
if ("file_type".equals(def.key())) {
|
||||||
|
counts = Stream.concat(counts.stream(), count(PHYSICAL_FILE_TYPE, base, scope).stream())
|
||||||
|
.sorted(
|
||||||
|
Comparator.comparingLong(FacetResponseBuilder.FacetCount::count)
|
||||||
|
.reversed()
|
||||||
|
.thenComparing(FacetResponseBuilder.FacetCount::value)
|
||||||
|
)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
return builder.group(def.key(), def.title(), counts);
|
||||||
|
}
|
||||||
|
|
||||||
private List<FacetResponseBuilder.FacetCount> count(FacetDef def, Specification<BookEntity> base, BrowseScope scope) {
|
private List<FacetResponseBuilder.FacetCount> count(FacetDef def, Specification<BookEntity> base, BrowseScope scope) {
|
||||||
|
return count(def, base, scope, null, 0, MAX_VALUES);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<FacetResponseBuilder.FacetCount> count(FacetDef def, Specification<BookEntity> base, BrowseScope scope, String term, int offset, int limit) {
|
||||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||||
Root<BookEntity> root = cq.from(BookEntity.class);
|
Root<BookEntity> root = cq.from(BookEntity.class);
|
||||||
Expression<?> value = def.value().apply(cb, root, scope);
|
Expression<?> value = def.value().apply(cb, root, scope);
|
||||||
Expression<Long> count = cb.countDistinct(root.get("id"));
|
|
||||||
|
|
||||||
List<Predicate> predicates = new ArrayList<>();
|
List<Predicate> predicates = new ArrayList<>();
|
||||||
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
||||||
@@ -187,13 +248,20 @@ public class BookFacetService {
|
|||||||
predicates.add(basePredicate);
|
predicates.add(basePredicate);
|
||||||
}
|
}
|
||||||
predicates.add(cb.isNotNull(value));
|
predicates.add(cb.isNotNull(value));
|
||||||
|
if (term != null) {
|
||||||
|
predicates.add(cb.like(cb.lower((Expression<String>) value), "%" + term.toLowerCase() + "%"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Expression<Long> count = countBooks(root.get("id"), root, cb);
|
||||||
cq.multiselect(value.alias("value"), count.alias("count"));
|
cq.multiselect(value.alias("value"), count.alias("count"));
|
||||||
cq.where(predicates.toArray(Predicate[]::new));
|
cq.where(predicates.toArray(Predicate[]::new));
|
||||||
cq.groupBy(value);
|
cq.groupBy(value);
|
||||||
cq.orderBy(cb.desc(count), cb.asc(value));
|
cq.orderBy(cb.desc(count), cb.asc(value));
|
||||||
|
|
||||||
return entityManager.createQuery(cq).setMaxResults(MAX_VALUES).getResultList().stream()
|
return entityManager.createQuery(cq)
|
||||||
|
.setFirstResult(offset)
|
||||||
|
.setMaxResults(limit)
|
||||||
|
.getResultList().stream()
|
||||||
.map(tuple -> new FacetResponseBuilder.FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
|
.map(tuple -> new FacetResponseBuilder.FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
@@ -206,15 +274,18 @@ public class BookFacetService {
|
|||||||
Root<BookEntity> root = cq.from(BookEntity.class);
|
Root<BookEntity> root = cq.from(BookEntity.class);
|
||||||
Expression<Number> value = (Expression<Number>) def.value().apply(cb, root, scope);
|
Expression<Number> value = (Expression<Number>) def.value().apply(cb, root, scope);
|
||||||
|
|
||||||
|
List<Expression<Long>> matchingIds = bands.stream()
|
||||||
|
.map(band -> matchingId(facetRegistry.toSpecification(def.key(), List.of(band), FacetLogic.OR, scope.userId()), root, cq, cb))
|
||||||
|
.toList();
|
||||||
|
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
||||||
|
|
||||||
List<Selection<?>> columns = new ArrayList<>();
|
List<Selection<?>> columns = new ArrayList<>();
|
||||||
columns.add(cb.min(value).alias("min"));
|
columns.add(cb.min(value).alias("min"));
|
||||||
columns.add(cb.max(value).alias("max"));
|
columns.add(cb.max(value).alias("max"));
|
||||||
for (String band : bands) {
|
for (int i = 0; i < bands.size(); i++) {
|
||||||
Specification<BookEntity> inBand = facetRegistry.toSpecification(def.key(), List.of(band), FacetLogic.OR, scope.userId());
|
columns.add(countBooks(matchingIds.get(i), root, cb).alias(bands.get(i)));
|
||||||
columns.add(countMatching(inBand, root, cq, cb).alias(band));
|
|
||||||
}
|
}
|
||||||
cq.multiselect(columns);
|
cq.multiselect(columns);
|
||||||
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
|
||||||
if (basePredicate != null) {
|
if (basePredicate != null) {
|
||||||
cq.where(basePredicate);
|
cq.where(basePredicate);
|
||||||
}
|
}
|
||||||
@@ -226,12 +297,27 @@ public class BookFacetService {
|
|||||||
return builder.numberGroup(def.key(), def.title(), counts, row.get("min", Number.class), row.get("max", Number.class));
|
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> matchingId(Specification<BookEntity> filter, Root<BookEntity> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
|
||||||
private Expression<Long> countMatching(Specification<BookEntity> filter, Root<BookEntity> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
|
return cb.<Long>selectCase()
|
||||||
Expression<Long> matchingId = cb.<Long>selectCase()
|
|
||||||
.when(filter.toPredicate(root, cq, cb), root.get("id"))
|
.when(filter.toPredicate(root, cq, cb), root.get("id"))
|
||||||
.otherwise(cb.nullLiteral(Long.class));
|
.otherwise(cb.nullLiteral(Long.class));
|
||||||
return cb.countDistinct(matchingId);
|
}
|
||||||
|
|
||||||
|
private static Expression<Long> countBooks(Expression<Long> bookId, From<?, ?> root, CriteriaBuilder cb) {
|
||||||
|
return hasCollectionJoin(root) ? cb.countDistinct(bookId) : cb.count(bookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasCollectionJoin(From<?, ?> from) {
|
||||||
|
return from.getJoins().stream().anyMatch(join ->
|
||||||
|
join.getAttribute().isCollection() || hasCollectionJoin(join));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String joinParams(String preserved, String params) {
|
||||||
|
return preserved.isBlank() ? params : preserved + "&" + params;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String href(String path, String preserved) {
|
||||||
|
return preserved.isBlank() ? path : path + "?" + preserved;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Join<?, ?> metadata(Root<BookEntity> root) {
|
private static Join<?, ?> metadata(Root<BookEntity> root) {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
|||||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
|
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
|
||||||
import org.booklore.model.entity.AuthorEntity;
|
import org.booklore.model.entity.AuthorEntity;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
|
import org.booklore.model.entity.BookFileEntity;
|
||||||
import org.booklore.model.entity.BookLoreUserEntity;
|
import org.booklore.model.entity.BookLoreUserEntity;
|
||||||
import org.booklore.model.entity.BookMetadataEntity;
|
import org.booklore.model.entity.BookMetadataEntity;
|
||||||
import org.booklore.model.entity.CategoryEntity;
|
import org.booklore.model.entity.CategoryEntity;
|
||||||
@@ -21,6 +22,7 @@ import org.booklore.model.entity.UserContentRestrictionEntity;
|
|||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.booklore.model.enums.ContentRestrictionMode;
|
import org.booklore.model.enums.ContentRestrictionMode;
|
||||||
import org.booklore.model.enums.ContentRestrictionType;
|
import org.booklore.model.enums.ContentRestrictionType;
|
||||||
|
import org.booklore.service.opds.MagicShelfBookService;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
import org.flywaydb.core.Flyway;
|
import org.flywaydb.core.Flyway;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -31,6 +33,7 @@ import org.springframework.boot.test.context.TestConfiguration;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Import;
|
import org.springframework.context.annotation.Import;
|
||||||
import org.springframework.context.annotation.Primary;
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.test.context.TestPropertySource;
|
import org.springframework.test.context.TestPropertySource;
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
@@ -44,6 +47,7 @@ import java.util.Optional;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@@ -75,6 +79,8 @@ class BookFacetServiceTest {
|
|||||||
private ObjectMapper springMapper;
|
private ObjectMapper springMapper;
|
||||||
@MockitoBean
|
@MockitoBean
|
||||||
private AuthenticationService authenticationService;
|
private AuthenticationService authenticationService;
|
||||||
|
@MockitoBean
|
||||||
|
private MagicShelfBookService magicShelfBookService;
|
||||||
|
|
||||||
@PersistenceContext
|
@PersistenceContext
|
||||||
private EntityManager em;
|
private EntityManager em;
|
||||||
@@ -157,6 +163,14 @@ class BookFacetServiceTest {
|
|||||||
.findFirst().orElseThrow();
|
.findFirst().orElseThrow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private FacetGroup facet(String key, List<String> selection) {
|
||||||
|
return facet(key, selection, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private FacetGroup facet(String key, List<String> selection, String facetLogic) {
|
||||||
|
return group(facetService.getFacet(key, selection, facetLogic, null, null, PageRequest.of(0, 100)), key);
|
||||||
|
}
|
||||||
|
|
||||||
private Long count(FacetGroup group, String value) {
|
private Long count(FacetGroup group, String value) {
|
||||||
Optional<FacetLink> link = group.links().stream().filter(l -> value.equals(l.value())).findFirst();
|
Optional<FacetLink> link = group.links().stream().filter(l -> value.equals(l.value())).findFirst();
|
||||||
return link.map(l -> l.properties().numberOfItems()).orElse(null);
|
return link.map(l -> l.properties().numberOfItems()).orElse(null);
|
||||||
@@ -168,6 +182,60 @@ class BookFacetServiceTest {
|
|||||||
.findFirst().orElseThrow();
|
.findFirst().orElseThrow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void scalarValuesAndRatingBandsCountMatchingBooks() {
|
||||||
|
BookMetadataEntity first = book("A", "Horror", "Alice");
|
||||||
|
first.setLanguage("en");
|
||||||
|
first.setGoodreadsRating(3.5);
|
||||||
|
BookMetadataEntity second = book("B", "Romance", "Bob");
|
||||||
|
second.setLanguage("en");
|
||||||
|
second.setGoodreadsRating(4.5);
|
||||||
|
BookMetadataEntity third = book("C", "Fantasy", "Cara");
|
||||||
|
third.setLanguage("fr");
|
||||||
|
third.setGoodreadsRating(3.5);
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
assertThat(count(facet("language", null), "en")).isEqualTo(2);
|
||||||
|
assertThat(count(facet("language", null), "fr")).isEqualTo(1);
|
||||||
|
FacetGroup ratings = facet("goodreads_rating", List.of("language:en"));
|
||||||
|
assertThat(count(ratings, "3..<4")).isEqualTo(1);
|
||||||
|
assertThat(count(ratings, "4.5..*")).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void repeatedAuthorCreditsAndFileTypesCountEachBookOnce() {
|
||||||
|
BookMetadataEntity metadata = book("A", "Horror", "Alice");
|
||||||
|
metadata.setAuthors(List.of(author("Alice"), author("Alice")));
|
||||||
|
for (String name : List.of("first.epub", "second.epub")) {
|
||||||
|
em.persist(BookFileEntity.builder().book(metadata.getBook())
|
||||||
|
.fileName(name).fileSubPath("").isBookFormat(true)
|
||||||
|
.bookType(BookFileType.EPUB).build());
|
||||||
|
}
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
assertThat(count(facet("author", null), "Alice")).isEqualTo(1);
|
||||||
|
assertThat(count(facet("file_type", null), "EPUB")).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nestedCollectionFilterKeepsScalarAndBandCountsDistinct() {
|
||||||
|
BookMetadataEntity first = book("A", "Horror", "Alice");
|
||||||
|
first.setAuthors(List.of(author("Alice"), author("Bob")));
|
||||||
|
first.setLanguage("en");
|
||||||
|
first.setGoodreadsRating(3.5);
|
||||||
|
BookMetadataEntity second = book("B", "Romance", "Alice");
|
||||||
|
second.setLanguage("en");
|
||||||
|
second.setGoodreadsRating(3.5);
|
||||||
|
when(magicShelfBookService.toSpecification(userEntity.getId(), 99L))
|
||||||
|
.thenReturn((root, query, cb) ->
|
||||||
|
cb.isNotNull(root.join("metadata").join("authors").get("id")));
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
List<String> selection = List.of("shelf:magic:99");
|
||||||
|
assertThat(count(facet("language", selection), "en")).isEqualTo(2);
|
||||||
|
assertThat(count(facet("goodreads_rating", selection), "3..<4")).isEqualTo(2);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void countsDiscreteFacetsWithCounts() {
|
void countsDiscreteFacetsWithCounts() {
|
||||||
book("A", "Horror", "Alice");
|
book("A", "Horror", "Alice");
|
||||||
@@ -301,6 +369,40 @@ class BookFacetServiceTest {
|
|||||||
assertThat(group(response, "author").links()).hasSize(100);
|
assertThat(group(response, "author").links()).hasSize(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void individualFacetPagesWithNextLink() {
|
||||||
|
book("A", "Horror", "Alice");
|
||||||
|
book("B", "Romance", "Alice");
|
||||||
|
book("C", "Fantasy", "Bob");
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
List<String> selection = List.of("genre:Horror", "author:Alice");
|
||||||
|
FacetGroupsResponse first = facetService.getFacet("genre", selection, null, null, null, PageRequest.of(0, 1));
|
||||||
|
FacetGroupsResponse last = facetService.getFacet("genre", selection, null, null, null, PageRequest.of(1, 1));
|
||||||
|
|
||||||
|
assertThat(group(first, "genre").links()).extracting(FacetLink::value).containsExactly("Horror");
|
||||||
|
assertThat(group(first, "genre").links().getFirst().rel()).containsExactly("self", "facet");
|
||||||
|
assertThat(first.links().getLast().href())
|
||||||
|
.isEqualTo("/api/v1/books/facets/genre?facet=genre%3AHorror&facet=author%3AAlice&page=1&size=1");
|
||||||
|
assertThat(group(last, "genre").links()).extracting(FacetLink::value).containsExactly("Romance");
|
||||||
|
assertThat(last.links()).extracting(Link::rel).containsExactly(List.of("self"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void individualNumberFacetsMatchTheOverallEndpoint() {
|
||||||
|
BookMetadataEntity metadata = book("A", "Genre", "Author");
|
||||||
|
metadata.setPageCount(120);
|
||||||
|
metadata.setGoodreadsRating(4.2);
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
FacetGroupsResponse overall = facetService.getFacets(null, null, null);
|
||||||
|
for (String key : List.of("page_count", "goodreads_rating")) {
|
||||||
|
FacetGroupsResponse single = facetService.getFacet(key, null, null, null, null, PageRequest.of(0, 1));
|
||||||
|
assertThat(single.facets()).containsExactly(group(overall, key));
|
||||||
|
assertThat(single.links()).extracting(Link::rel).containsExactly(List.of("self"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void numberFacetBoundsCoverValuesPastTheCap() {
|
void numberFacetBoundsCoverValuesPastTheCap() {
|
||||||
for (int i = 1; i <= 101; i++) {
|
for (int i = 1; i <= 101; i++) {
|
||||||
@@ -346,6 +448,26 @@ class BookFacetServiceTest {
|
|||||||
assertThat(link(goodreads, "4..<4.5").rel()).containsExactly("self", "facet");
|
assertThat(link(goodreads, "4..<4.5").rel()).containsExactly("self", "facet");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void individualFacetSearchesValuesPastTheTopHundred() {
|
||||||
|
for (int i = 0; i < 120; i++) {
|
||||||
|
book("T" + i, "Genre" + i, "Author");
|
||||||
|
}
|
||||||
|
book("Rare", "Zebra Fiction", "Author");
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
FacetGroupsResponse response = facetService.getFacet("genre", null, null, null, "zebra", PageRequest.of(0, 20));
|
||||||
|
|
||||||
|
assertThat(group(response, "genre").links()).extracting(FacetLink::value).containsExactly("Zebra Fiction");
|
||||||
|
assertThat(response.links().getFirst().href()).isEqualTo("/api/v1/books/facets/genre?search=zebra&page=0&size=20");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void individualFacetSearchIsLimitedToNameFacets() {
|
||||||
|
assertThatThrownBy(() -> facetService.getFacet("page_count", null, null, null, "12", PageRequest.of(0, 20)))
|
||||||
|
.hasMessage("Facet cannot be searched: page_count");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void activeFacetIsMarkedSelfWithCurrentPageHref() {
|
void activeFacetIsMarkedSelfWithCurrentPageHref() {
|
||||||
book("A", "Horror", "Alice");
|
book("A", "Horror", "Alice");
|
||||||
|
|||||||
Reference in New Issue
Block a user