feat(search): Add denormalized search_text column for better book search (#1791)
* fix(search): Optimize book search with denormalized search_text column Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * fix(search): Enhance search text normalization for diacritics in author names Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * fix(migration): Implement batch processing for populating search text and enhance error handling Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * fix(search): Manually trigger search text update after author modifications and enhance special character handling Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * fix(search): Update special character handling to be more permissive in search text normalization Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * feat(AppMigrationService): add FileService dependency for enhanced file handling Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * feat(database): add search_text column to book_metadata for improved search functionality Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * feat(database): add search_text column to book_metadata for improved search functionality Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * fix(database): correct join condition and ordering in findBooksForMigrationBatch query Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+10
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
@@ -232,6 +233,15 @@ public class BookMetadataEntity {
|
||||
@Column(name = "embedding_updated_at")
|
||||
private Instant embeddingUpdatedAt;
|
||||
|
||||
@Column(name = "search_text", columnDefinition = "TEXT")
|
||||
private String searchText;
|
||||
|
||||
@PrePersist
|
||||
@PreUpdate
|
||||
public void updateSearchText() {
|
||||
this.searchText = BookUtils.buildSearchText(this);
|
||||
}
|
||||
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@MapsId
|
||||
@JoinColumn(name = "book_id")
|
||||
|
||||
+2
-10
@@ -74,12 +74,8 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
|
||||
@Query("""
|
||||
SELECT DISTINCT b.id FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
m.searchText LIKE CONCAT('%', :text, '%')
|
||||
)
|
||||
ORDER BY b.addedOn DESC
|
||||
""")
|
||||
@@ -96,14 +92,10 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
|
||||
@Query("""
|
||||
SELECT DISTINCT b.id FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
m.searchText LIKE CONCAT('%', :text, '%')
|
||||
)
|
||||
ORDER BY b.addedOn DESC
|
||||
""")
|
||||
|
||||
+19
-10
@@ -72,26 +72,35 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
""")
|
||||
List<BookEntity> findAllFullBooks();
|
||||
|
||||
@Query(value = """
|
||||
SELECT DISTINCT b.* FROM book b
|
||||
LEFT JOIN book_metadata m ON b.id = m.book_id
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
ORDER BY b.id
|
||||
LIMIT :limit OFFSET :offset
|
||||
""", nativeQuery = true)
|
||||
List<BookEntity> findBooksForMigrationBatch(@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN FETCH b.metadata m
|
||||
LEFT JOIN FETCH m.authors
|
||||
WHERE b.id IN :bookIds
|
||||
""")
|
||||
List<BookEntity> findBooksWithMetadataAndAuthors(@Param("bookIds") List<Long> bookIds);
|
||||
|
||||
@Query(value = """
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
m.searchText LIKE CONCAT('%', :text, '%')
|
||||
)
|
||||
""",
|
||||
countQuery = """
|
||||
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
m.searchText LIKE CONCAT('%', :text, '%')
|
||||
)
|
||||
""")
|
||||
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
|
||||
|
||||
+1
@@ -83,6 +83,7 @@ public class BookCreatorService {
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
|
||||
bookEntity.getMetadata().updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
|
||||
}
|
||||
|
||||
private String truncate(String input, int maxLength) {
|
||||
|
||||
+3
-2
@@ -76,7 +76,6 @@ public class BookMetadataUpdater {
|
||||
|
||||
boolean thumbnailRequiresUpdate = StringUtils.hasText(newMetadata.getThumbnailUrl());
|
||||
boolean hasMetadataChanges = MetadataChangeDetector.isDifferent(newMetadata, metadata, clearFlags);
|
||||
boolean hasValueChanges = MetadataChangeDetector.hasValueChanges(newMetadata, metadata, clearFlags);
|
||||
if (!thumbnailRequiresUpdate && !hasMetadataChanges) {
|
||||
log.info("No changes in metadata for book ID {}. Skipping update.", bookId);
|
||||
return;
|
||||
@@ -90,7 +89,6 @@ public class BookMetadataUpdater {
|
||||
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean writeToFile = settings.isSaveToOriginalFile();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
BookFileType bookType = bookEntity.getBookType();
|
||||
|
||||
boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags);
|
||||
@@ -226,11 +224,14 @@ public class BookMetadataUpdater {
|
||||
if (replaceAll) {
|
||||
if (!merge) e.getAuthors().clear();
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
|
||||
} else if (replaceMissing && e.getAuthors().isEmpty()) {
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
|
||||
} else if (replaceMode == null) {
|
||||
if (!merge) e.getAuthors().clear();
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -112,6 +112,7 @@ public class MetadataManagementService {
|
||||
for (BookMetadataEntity metadata : booksWithOldAuthor) {
|
||||
metadata.getAuthors().remove(oldAuthor);
|
||||
metadata.getAuthors().addAll(targetAuthors);
|
||||
metadata.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldAuthor);
|
||||
|
||||
+45
@@ -3,11 +3,13 @@ package com.adityachandel.booklore.service.migration;
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.AppMigrationRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookQueryService;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.transaction.Transactional;
|
||||
@@ -42,6 +44,49 @@ public class AppMigrationService {
|
||||
private AppProperties appProperties;
|
||||
private FileService fileService;
|
||||
|
||||
@Transactional
|
||||
public void populateSearchTextOnce() {
|
||||
if (migrationRepository.existsById("populateSearchText")) return;
|
||||
|
||||
int batchSize = 1000;
|
||||
int processedCount = 0;
|
||||
int offset = 0;
|
||||
|
||||
while (true) {
|
||||
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize);
|
||||
if (bookBatch.isEmpty()) break;
|
||||
|
||||
List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList();
|
||||
List<BookEntity> books = bookRepository.findBooksWithMetadataAndAuthors(bookIds);
|
||||
|
||||
for (BookEntity book : books) {
|
||||
BookMetadataEntity m = book.getMetadata();
|
||||
if (m != null) {
|
||||
try {
|
||||
m.setSearchText(BookUtils.buildSearchText(m));
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to build search text for book {}: {}", book.getId(), ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bookRepository.saveAll(books);
|
||||
processedCount += books.size();
|
||||
offset += batchSize;
|
||||
|
||||
log.info("Migration progress: {} books processed", processedCount);
|
||||
|
||||
if (bookBatch.size() < batchSize) break;
|
||||
}
|
||||
|
||||
log.info("Migration 'populateSearchText' completed. Total books processed: {}", processedCount);
|
||||
migrationRepository.save(new AppMigrationEntity(
|
||||
"populateSearchText",
|
||||
LocalDateTime.now(),
|
||||
"Populate search_text column for all books"
|
||||
));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void populateMissingFileSizesOnce() {
|
||||
if (migrationRepository.existsById("populateFileSizes")) {
|
||||
|
||||
+1
@@ -17,6 +17,7 @@ public class AppMigrationStartup {
|
||||
appMigrationService.populateMetadataScoresOnce();
|
||||
appMigrationService.populateFileHashesOnce();
|
||||
appMigrationService.populateCoversAndResizeThumbnails();
|
||||
appMigrationService.populateSearchTextOnce();
|
||||
appMigrationService.moveIconsToDataFolder();
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.repository.BookOpdsRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -78,19 +79,19 @@ public class OpdsBookService {
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
|
||||
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), Set.of(libraryId), page, size)
|
||||
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
return query != null && !query.isBlank()
|
||||
? searchByMetadataPageInternal(query, page, size)
|
||||
? searchByMetadataPageInternal(BookUtils.normalizeForSearch(query), page, size)
|
||||
: getAllBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, userLibraryIds, page, size)
|
||||
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), userLibraryIds, page, size)
|
||||
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import lombok.experimental.UtilityClass;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
@@ -8,9 +10,49 @@ import java.util.regex.Pattern;
|
||||
public class BookUtils {
|
||||
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[.,\\-\\[\\]{}()!@#$%^&*_=+|~`<>?/\";:]");
|
||||
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[!@$%^&*_=|~`<>?/\"]");
|
||||
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
|
||||
|
||||
public static String buildSearchText(BookMetadataEntity e) {
|
||||
if (e == null) return null;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (e.getTitle() != null) sb.append(e.getTitle()).append(" ");
|
||||
if (e.getSubtitle() != null) sb.append(e.getSubtitle()).append(" ");
|
||||
if (e.getSeriesName() != null) sb.append(e.getSeriesName()).append(" ");
|
||||
|
||||
try {
|
||||
if (e.getAuthors() != null) {
|
||||
for (AuthorEntity author : e.getAuthors()) {
|
||||
if (author != null && author.getName() != null) {
|
||||
sb.append(author.getName()).append(" ");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// LazyInitializationException or similar - authors won't be included in search text
|
||||
}
|
||||
|
||||
return normalizeForSearch(sb.toString().trim());
|
||||
}
|
||||
|
||||
public static String normalizeForSearch(String term) {
|
||||
if (term == null) {
|
||||
return null;
|
||||
}
|
||||
String s = java.text.Normalizer.normalize(term, java.text.Normalizer.Form.NFD);
|
||||
s = s.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
|
||||
s = s.replace("ø", "o").replace("Ø", "O")
|
||||
.replace("ł", "l").replace("Ł", "L")
|
||||
.replace("æ", "ae").replace("Æ", "AE")
|
||||
.replace("œ", "oe").replace("Œ", "OE")
|
||||
.replace("ß", "ss");
|
||||
|
||||
// Use cleanSearchTerm instead of cleanAndTruncateSearchTerm
|
||||
s = cleanSearchTerm(s);
|
||||
return s.toLowerCase();
|
||||
}
|
||||
|
||||
public static String cleanFileName(String fileName) {
|
||||
String name = fileName;
|
||||
if (name == null) {
|
||||
@@ -25,13 +67,18 @@ public class BookUtils {
|
||||
return name;
|
||||
}
|
||||
|
||||
public static String cleanAndTruncateSearchTerm(String term) {
|
||||
public static String cleanSearchTerm(String term) {
|
||||
if (term == null) {
|
||||
return "";
|
||||
}
|
||||
String s = term;
|
||||
s = SPECIAL_CHARACTERS_PATTERN.matcher(s).replaceAll("").trim();
|
||||
s = WHITESPACE_PATTERN.matcher(s).replaceAll(" ");
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String cleanAndTruncateSearchTerm(String term) {
|
||||
String s = cleanSearchTerm(term);
|
||||
if (s.length() > 60) {
|
||||
String[] words = WHITESPACE_PATTERN.split(s);
|
||||
if (words.length > 1) {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE book_metadata ADD COLUMN IF NOT EXISTS search_text TEXT;
|
||||
+87
-11
@@ -1,21 +1,97 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import java.util.Set;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BookMetadataEntityTest {
|
||||
|
||||
@Test
|
||||
void builderShouldRespectDefaultValues() {
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder().build();
|
||||
void updateSearchText_populatesSearchText() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Jo Nesbø Book");
|
||||
metadata.setSubtitle("Murder Mystery");
|
||||
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build()));
|
||||
|
||||
assertThat(metadata.getTitleLocked()).isFalse();
|
||||
assertThat(metadata.getSubtitleLocked()).isFalse();
|
||||
assertThat(metadata.getPublisherLocked()).isFalse();
|
||||
metadata.updateSearchText();
|
||||
|
||||
assertThat(metadata.getAuthorsLocked()).isFalse();
|
||||
assertThat(metadata.getCoverLocked()).isFalse();
|
||||
|
||||
assertThat(metadata.getReviews()).isNotNull().isEmpty();
|
||||
String searchText = metadata.getSearchText();
|
||||
assertNotNull(searchText);
|
||||
assertTrue(searchText.contains("jo nesbo book"));
|
||||
assertTrue(searchText.contains("murder mystery"));
|
||||
assertTrue(searchText.contains("jo nesbo"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateSearchText_normalizesAuthorWithDiacritics() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("The Snowman");
|
||||
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build()));
|
||||
|
||||
metadata.updateSearchText();
|
||||
|
||||
String searchText = metadata.getSearchText();
|
||||
assertNotNull(searchText);
|
||||
// Verify that 'ø' is normalized to 'o'
|
||||
assertTrue(searchText.contains("nesbo"), "Should contain 'nesbo': " + searchText);
|
||||
assertFalse(searchText.contains("ø"), "Should not contain 'ø': " + searchText);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateSearchText_handlesFrenchGermanAndSpanishDiacritics() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Müller's Café");
|
||||
metadata.setSubtitle("À la française");
|
||||
metadata.setSeriesName("José's Stories");
|
||||
metadata.setAuthors(Set.of(
|
||||
AuthorEntity.builder().name("François Müller").build(),
|
||||
AuthorEntity.builder().name("José García").build()
|
||||
));
|
||||
|
||||
metadata.updateSearchText();
|
||||
|
||||
String searchText = metadata.getSearchText();
|
||||
assertNotNull(searchText);
|
||||
|
||||
assertTrue(searchText.contains("muller"), "Should contain 'muller': " + searchText);
|
||||
assertTrue(searchText.contains("cafe"), "Should contain 'cafe': " + searchText);
|
||||
assertTrue(searchText.contains("a la francaise"), "Should contain 'a la francaise': " + searchText);
|
||||
assertTrue(searchText.contains("jose"), "Should contain 'jose': " + searchText);
|
||||
assertTrue(searchText.contains("garcia"), "Should contain 'garcia': " + searchText);
|
||||
assertTrue(searchText.contains("francois muller"), "Should contain 'francois muller': " + searchText);
|
||||
|
||||
assertFalse(searchText.contains("ü"), "Should not contain 'ü': " + searchText);
|
||||
assertFalse(searchText.contains("é"), "Should not contain 'é': " + searchText);
|
||||
assertFalse(searchText.contains("à"), "Should not contain 'à': " + searchText);
|
||||
assertFalse(searchText.contains("í"), "Should not contain 'í': " + searchText);
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchSimulation_withDiacritics() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("The Bat");
|
||||
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build()));
|
||||
metadata.updateSearchText();
|
||||
|
||||
String storedSearchText = metadata.getSearchText();
|
||||
|
||||
String searchQuery1 = BookUtils.normalizeForSearch("nesbo"); // without ø
|
||||
String searchQuery2 = BookUtils.normalizeForSearch("Nesbø"); // with ø
|
||||
String searchQuery3 = BookUtils.normalizeForSearch("NESBO"); // uppercase
|
||||
String searchQuery4 = BookUtils.normalizeForSearch("Jo Nesbø"); // full name with ø
|
||||
|
||||
assertEquals(searchQuery1, searchQuery2, "Queries with and without diacritics should match");
|
||||
assertEquals(searchQuery1, searchQuery3, "Case should not matter");
|
||||
|
||||
// Simulate LIKE '%query%' - all searches should find the book
|
||||
assertTrue(storedSearchText.contains(searchQuery1),
|
||||
"Search 'nesbo' should match stored text: " + storedSearchText);
|
||||
assertTrue(storedSearchText.contains(searchQuery2),
|
||||
"Search 'Nesbø' should match stored text: " + storedSearchText);
|
||||
assertTrue(storedSearchText.contains(searchQuery3),
|
||||
"Search 'NESBO' should match stored text: " + storedSearchText);
|
||||
assertTrue(storedSearchText.contains(searchQuery4),
|
||||
"Search 'Jo Nesbø' should match stored text: " + storedSearchText);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,42 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BookUtilsTest {
|
||||
|
||||
@Test
|
||||
void testBuildSearchText() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Harry Potter");
|
||||
metadata.setSubtitle("Philosopher's Stone");
|
||||
metadata.setSeriesName("Harry Potter Series");
|
||||
metadata.setAuthors(Set.of(AuthorEntity.builder().name("J.K. Rowling").build()));
|
||||
|
||||
String searchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
assertNotNull(searchText);
|
||||
assertTrue(searchText.contains("harry potter"));
|
||||
// More permissive: keeps apostrophe
|
||||
assertTrue(searchText.contains("philosopher's stone"));
|
||||
// Keeps period
|
||||
assertTrue(searchText.contains("rowling"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanSearchTerm_doesNotTruncate() {
|
||||
String longText = "A".repeat(100);
|
||||
String result = BookUtils.cleanSearchTerm(longText);
|
||||
assertEquals(100, result.length());
|
||||
assertEquals(longText, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanFileName_nullInput() {
|
||||
String result = BookUtils.cleanFileName(null);
|
||||
@@ -76,13 +108,15 @@ class BookUtilsTest {
|
||||
@Test
|
||||
void testCleanAndTruncateSearchTerm_withSpecialChars() {
|
||||
String result = BookUtils.cleanAndTruncateSearchTerm("Hello, World! How are you?");
|
||||
assertEquals("Hello World How are you", result);
|
||||
// More permissive: keeps comma
|
||||
assertEquals("Hello, World How are you", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanAndTruncateSearchTerm_withBrackets() {
|
||||
String result = BookUtils.cleanAndTruncateSearchTerm("Test [Book] {Series}");
|
||||
assertEquals("Test Book Series", result);
|
||||
// More permissive: keeps brackets and braces
|
||||
assertEquals("Test [Book] {Series}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -98,7 +132,7 @@ class BookUtilsTest {
|
||||
String longText = "This-is,a@very#long$search%term^with&special*chars(that)should[be]truncated{because}it<exceeds>sixty?characters";
|
||||
String result = BookUtils.cleanAndTruncateSearchTerm(longText);
|
||||
assertTrue(result.length() <= 60);
|
||||
assertEquals("Thisisaverylongsearchtermwithspecialcharsthatshouldbetruncat", result);
|
||||
assertEquals("This-is,avery#longsearchtermwithspecialchars(that)should[be]", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,6 +152,179 @@ class BookUtilsTest {
|
||||
@Test
|
||||
void testCleanAndTruncateSearchTerm_onlySpecialChars() {
|
||||
String result = BookUtils.cleanAndTruncateSearchTerm(",.!@#$%^&*()[]{}");
|
||||
assertEquals("", result);
|
||||
assertEquals(",.#()[]{}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNormalizeForSearch() {
|
||||
assertEquals("nesbo", BookUtils.normalizeForSearch("Nesbø"));
|
||||
assertEquals("jo nesbo", BookUtils.normalizeForSearch("Jo Nesbø"));
|
||||
assertEquals("aeiou", BookUtils.normalizeForSearch("áéíóú"));
|
||||
assertEquals("aeiou", BookUtils.normalizeForSearch("ÀÈÌÒÙ"));
|
||||
assertEquals("l", BookUtils.normalizeForSearch("ł"));
|
||||
assertEquals("ss", BookUtils.normalizeForSearch("ß"));
|
||||
assertEquals("harry potter", BookUtils.normalizeForSearch("Harry Potter"));
|
||||
assertEquals("misere", BookUtils.normalizeForSearch("Misère"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNormalizeForSearch_variousDiacritics() {
|
||||
// French
|
||||
assertEquals("francois", BookUtils.normalizeForSearch("François"));
|
||||
assertEquals("renee", BookUtils.normalizeForSearch("Renée"));
|
||||
assertEquals("helene", BookUtils.normalizeForSearch("Hélène"));
|
||||
|
||||
// Spanish
|
||||
assertEquals("jose", BookUtils.normalizeForSearch("José"));
|
||||
assertEquals("nino", BookUtils.normalizeForSearch("Niño"));
|
||||
assertEquals("manana", BookUtils.normalizeForSearch("Mañana"));
|
||||
|
||||
// German
|
||||
assertEquals("muller", BookUtils.normalizeForSearch("Müller"));
|
||||
assertEquals("gross", BookUtils.normalizeForSearch("Groß"));
|
||||
assertEquals("schon", BookUtils.normalizeForSearch("Schön"));
|
||||
|
||||
// Polish
|
||||
assertEquals("lodz", BookUtils.normalizeForSearch("Łódź"));
|
||||
assertEquals("wroclaw", BookUtils.normalizeForSearch("Wrocław"));
|
||||
|
||||
// Scandinavian
|
||||
assertEquals("oslo", BookUtils.normalizeForSearch("Oslø"));
|
||||
assertEquals("malmo", BookUtils.normalizeForSearch("Malmö"));
|
||||
assertEquals("copenhagen", BookUtils.normalizeForSearch("Cøpenhagen"));
|
||||
|
||||
// Portuguese
|
||||
assertEquals("sao paulo", BookUtils.normalizeForSearch("São Paulo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNormalizeForSearch_programmingLanguages() {
|
||||
// Test that + and # are preserved for programming book titles
|
||||
assertEquals("c++", BookUtils.normalizeForSearch("C++"));
|
||||
assertEquals("c#", BookUtils.normalizeForSearch("C#"));
|
||||
assertEquals("f#", BookUtils.normalizeForSearch("F#"));
|
||||
assertEquals("effective c++ programming", BookUtils.normalizeForSearch("Effective C++ Programming"));
|
||||
assertEquals("c# in depth", BookUtils.normalizeForSearch("C# In Depth"));
|
||||
assertEquals("cacao", BookUtils.normalizeForSearch("Cação"));
|
||||
|
||||
// Turkish
|
||||
assertEquals("istanbul", BookUtils.normalizeForSearch("İstanbul"));
|
||||
|
||||
// Czech
|
||||
assertEquals("dvorak", BookUtils.normalizeForSearch("Dvořák"));
|
||||
assertEquals("capek", BookUtils.normalizeForSearch("Čapek"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildSearchText_withDiacritics() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("The Snowman");
|
||||
metadata.setSubtitle("A Harry Hole Novel");
|
||||
metadata.setSeriesName("Harry Hole");
|
||||
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build()));
|
||||
|
||||
String searchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
assertNotNull(searchText);
|
||||
assertTrue(searchText.contains("jo nesbo"), "Expected 'jo nesbo' in: " + searchText);
|
||||
assertTrue(searchText.contains("the snowman"), "Expected 'the snowman' in: " + searchText);
|
||||
assertTrue(searchText.contains("harry hole"), "Expected 'harry hole' in: " + searchText);
|
||||
|
||||
assertFalse(searchText.contains("ø"), "Should not contain 'ø' in: " + searchText);
|
||||
assertFalse(searchText.contains("Nesbø"), "Should not contain 'Nesbø' in: " + searchText);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchMatchingWithAndWithoutDiacritics() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Misère");
|
||||
metadata.setAuthors(Set.of(AuthorEntity.builder().name("François Müller").build()));
|
||||
|
||||
String storedSearchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
String searchWithoutDiacritics = BookUtils.normalizeForSearch("francois muller");
|
||||
String searchWithDiacritics = BookUtils.normalizeForSearch("François Müller");
|
||||
String searchMixedCase = BookUtils.normalizeForSearch("FRANCOIS muller");
|
||||
|
||||
assertEquals(searchWithoutDiacritics, searchWithDiacritics);
|
||||
assertEquals(searchWithoutDiacritics, searchMixedCase);
|
||||
|
||||
assertTrue(storedSearchText.contains("francois muller"),
|
||||
"Stored text should contain normalized author: " + storedSearchText);
|
||||
|
||||
assertTrue(storedSearchText.contains(searchWithoutDiacritics),
|
||||
"Search without diacritics should match");
|
||||
assertTrue(storedSearchText.contains(searchWithDiacritics),
|
||||
"Search with diacritics should match");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNormalizeForSearch_nullAndEmpty() {
|
||||
assertNull(BookUtils.normalizeForSearch(null));
|
||||
assertEquals("", BookUtils.normalizeForSearch(""));
|
||||
assertEquals("", BookUtils.normalizeForSearch(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNormalizeForSearch_preservesSpaces() {
|
||||
assertEquals("jo nesbo book", BookUtils.normalizeForSearch("Jo Nesbø Book"));
|
||||
assertEquals("multiple word title", BookUtils.normalizeForSearch("Multiple Word Title"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNormalizeForSearch_removesSpecialCharacters() {
|
||||
assertEquals("book: title", BookUtils.normalizeForSearch("Book: Title!"));
|
||||
assertEquals("author's name", BookUtils.normalizeForSearch("Author's Name"));
|
||||
assertEquals("test (123)", BookUtils.normalizeForSearch("Test (123)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildSearchText_withNullFields() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Title Only");
|
||||
|
||||
String searchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
assertNotNull(searchText);
|
||||
assertEquals("title only", searchText);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildSearchText_handlesExceptionGracefully() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Test Book");
|
||||
|
||||
String searchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
assertNotNull(searchText);
|
||||
assertTrue(searchText.contains("test book"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildSearchText_withAuthorHavingNullName() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Test Book");
|
||||
Set<AuthorEntity> authors = new HashSet<>();
|
||||
authors.add(AuthorEntity.builder().name("Valid Author").build());
|
||||
authors.add(AuthorEntity.builder().name(null).build()); // Author with null name
|
||||
metadata.setAuthors(authors);
|
||||
|
||||
String searchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
assertNotNull(searchText);
|
||||
assertTrue(searchText.contains("valid author"));
|
||||
assertTrue(searchText.contains("test book"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildSearchText_withEmptyAuthorsSet() {
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Test Book");
|
||||
metadata.setAuthors(new HashSet<>()); // Empty set
|
||||
|
||||
String searchText = BookUtils.buildSearchText(metadata);
|
||||
|
||||
assertNotNull(searchText);
|
||||
assertEquals("test book", searchText);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,19 @@ export class HeaderFilter implements BookFilter {
|
||||
}
|
||||
|
||||
filter(bookState: BookState): Observable<BookState> {
|
||||
const normalize = (str: string): string =>
|
||||
str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
|
||||
const normalize = (str: string): string => {
|
||||
if (!str) return '';
|
||||
// Normalize Unicode combining characters (e.g., é -> e)
|
||||
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||||
s = s.replace(/ø/gi, 'o')
|
||||
.replace(/ł/gi, 'l')
|
||||
.replace(/æ/gi, 'ae')
|
||||
.replace(/œ/gi, 'oe')
|
||||
.replace(/ß/g, 'ss');
|
||||
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
|
||||
s = s.replace(/\s+/g, ' ').trim();
|
||||
return s.toLowerCase();
|
||||
};
|
||||
|
||||
return this.searchTerm$.pipe(
|
||||
distinctUntilChanged(),
|
||||
|
||||
Reference in New Issue
Block a user