Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support setting attributes for index #119

Merged
merged 5 commits into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,9 @@
* @return Index UID
*/
String indexUid();

/**
* Apply the settings to the index on repository bootstrapping.
*/
boolean applySettings() default true;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.vanslog.spring.data.meilisearch.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.data.annotation.Persistent;

/**
* Meilisearch Setting
*
* @author Junghoon Ban
*/
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface Setting {

/**
* attributes to define an index sorting
*/
String[] sortAttributes() default {};

String[] filterableAttributes() default {};

String distinctAttribute() default "";

String[] searchableAttributes() default { "*" };

String[] displayedAttributes() default { "*" };

String[] rankingRules() default { "words", "typo", "proximity", "attribute", "sort", "exactness" };

String[] stopWords() default {};
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,13 @@ public interface MeilisearchOperations {
<T> List<T> search(SearchRequest searchRequest, Class<?> clazz);

/**
* Make the given attributes sortable.
*
* Apply the default settings for the given entity class.
*
* @param clazz the entity class, must be annotated with
* {@link io.vanslog.spring.data.meilisearch.annotations.Document}
* @param attributes the attributes to make sortable
* @param <T> the type of the entity
*/
<T> void makeSortable(Class<T> clazz, String[] attributes);
<T> void applySettings(Class<T> clazz);

/**
* Return the {@link io.vanslog.spring.data.meilisearch.core.convert.MeilisearchConverter}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package io.vanslog.spring.data.meilisearch.core;

import com.meilisearch.sdk.model.DocumentsQuery;
import com.meilisearch.sdk.model.Settings;
import io.vanslog.spring.data.meilisearch.DocumentAccessException;
import io.vanslog.spring.data.meilisearch.TaskStatusException;
import io.vanslog.spring.data.meilisearch.UncategorizedMeilisearchException;
Expand Down Expand Up @@ -191,12 +192,15 @@ public <T> List<T> search(SearchRequest searchRequest, Class<?> clazz) {
.toList();
}

public <T> void makeSortable(Class<T> clazz, String[] attributes) {
public <T> void applySettings(Class<T> clazz) {
String indexUid = getIndexUidFor(clazz);
TaskInfo taskInfo = execute(client -> client.index(indexUid).updateSortableAttributesSettings(attributes));
MeilisearchPersistentEntity<?> persistentEntity = getPersistentEntityFor(clazz);
Settings settings = persistentEntity.getDefaultSettings();

TaskInfo taskInfo = execute(client -> client.index(indexUid).updateSettings(settings));

if (!isTaskSucceeded(indexUid, taskInfo)) {
throw new TaskStatusException(taskInfo.getStatus(), "Failed to make sortable.");
throw new TaskStatusException(taskInfo.getStatus(), "Failed to create index.");
}
}

Expand All @@ -214,12 +218,20 @@ public <T> T execute(MeilisearchCallback<T> callback) {
try {
return callback.doWithClient(meilisearchClient);
} catch (MeilisearchException e) {
MeilisearchApiException ex = (MeilisearchApiException) e;

if (ex.getCode().equals("document_not_found")) {
throw new DocumentAccessException(ex.getMessage(), ex.getCause());
if (e instanceof MeilisearchApiException ex) {
handleApiException(ex);
}
throw new UncategorizedMeilisearchException(ex.getMessage(), ex.getCause());
throw new UncategorizedMeilisearchException(e.getMessage(), e.getCause());
}
}

/**
* Handle the given {@link MeilisearchApiException}.
* @param e the {@link MeilisearchApiException} to handle
*/
private void handleApiException(MeilisearchApiException e) {
if (e.getCode().equals("document_not_found")) {
throw new DocumentAccessException(e.getMessage(), e.getCause());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.vanslog.spring.data.meilisearch.core.mapping;

import com.meilisearch.sdk.model.Settings;
import org.springframework.data.mapping.PersistentEntity;

/**
Expand All @@ -32,4 +33,17 @@ public interface MeilisearchPersistentEntity<T> extends PersistentEntity<T, Meil
* @return Index UID
*/
String getIndexUid();

/**
* Returns whether to apply the settings to the index on repository bootstrapping.
* @return applySettings
*/
boolean isApplySettings();

/**
* Returns the default settings for an index.
*
* @return settings
*/
Settings getDefaultSettings();
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@

package io.vanslog.spring.data.meilisearch.core.mapping;

import com.meilisearch.sdk.model.Settings;
import io.vanslog.spring.data.meilisearch.annotations.Document;

import io.vanslog.spring.data.meilisearch.annotations.Setting;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.BeanFactoryAccessor;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.data.mapping.model.BasicPersistentEntity;
import org.springframework.data.util.Lazy;
import org.springframework.data.util.TypeInformation;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.lang.Nullable;
Expand All @@ -39,7 +43,10 @@ public class SimpleMeilisearchPersistentEntity<T> extends BasicPersistentEntity<
implements MeilisearchPersistentEntity<T>, ApplicationContextAware {

private final StandardEvaluationContext context;
@Nullable private final Document document;
@Nullable private String indexUid;
private final Lazy<SettingsParameter> settingParameter;
private boolean applySettings;

/**
* Creates a new {@link SimpleMeilisearchPersistentEntity} with the given {@link TypeInformation}.
Expand All @@ -51,11 +58,17 @@ public SimpleMeilisearchPersistentEntity(TypeInformation<T> information) {
this.context = new StandardEvaluationContext();

Class<T> rawType = information.getType();
if (rawType.isAnnotationPresent(Document.class)) {
Document document = rawType.getAnnotation(Document.class);
document = AnnotatedElementUtils.findMergedAnnotation(rawType, Document.class);

this.settingParameter = Lazy.of(() -> buildSettingParameter(rawType));

if (document != null) {
Assert.hasText(document.indexUid(),
"Unknown indexUid. Make sure the indexUid is defined." + "e.g @Document(indexUid=\"foo\")");
this.indexUid = document.indexUid();
this.applySettings = document.applySettings();
} else {
this.applySettings = false;
}
}

Expand All @@ -70,4 +83,93 @@ public void setApplicationContext(ApplicationContext applicationContext) throws
public String getIndexUid() {
return indexUid;
}

@Override
public boolean isApplySettings() {
return applySettings;
}

@Override
public Settings getDefaultSettings() {
return settingParameter.get().toSettings();
}

private SettingsParameter buildSettingParameter(Class<?> clazz) {

SettingsParameter settingsParameter = new SettingsParameter();
Setting settingAnnotation = AnnotatedElementUtils.findMergedAnnotation(clazz, Setting.class);

// default values
settingsParameter.searchableAttributes = new String[] { "*" };
settingsParameter.displayedAttributes = new String[] { "*" };
settingsParameter.rankingRules = new String[] { "words", "typo", "proximity", "attribute", "sort", "exactness" };

if (settingAnnotation != null) {
processSettingAnnotation(settingAnnotation, settingsParameter);
}

return settingsParameter;
}

private void processSettingAnnotation(Setting settingAnnotation, SettingsParameter settingsParameter) {
settingsParameter.searchableAttributes = settingAnnotation.searchableAttributes();
settingsParameter.displayedAttributes = settingAnnotation.displayedAttributes();
settingsParameter.rankingRules = settingAnnotation.rankingRules();

String[] sortAttributes = settingAnnotation.sortAttributes();
String[] filterableAttributes = settingAnnotation.filterableAttributes();
String distinctAttribute = settingAnnotation.distinctAttribute();
String[] stopWords = settingAnnotation.stopWords();

if (sortAttributes.length > 0) {
settingsParameter.sortAttributes = settingAnnotation.sortAttributes();
}

if (filterableAttributes.length > 0) {
settingsParameter.filterableAttributes = settingAnnotation.filterableAttributes();
}

if (!distinctAttribute.isEmpty()) {
settingsParameter.distinctAttribute = settingAnnotation.distinctAttribute();
}

if (stopWords.length > 0) {
settingsParameter.stopWords = settingAnnotation.stopWords();
}
}

private static class SettingsParameter {
@Nullable private String[] sortAttributes;
@Nullable private String[] filterableAttributes;
@Nullable private String distinctAttribute;
private String[] searchableAttributes;
private String[] displayedAttributes;
private String[] rankingRules;
@Nullable private String[] stopWords;

Settings toSettings() {
Settings settings = new Settings();
settings.setSearchableAttributes(searchableAttributes);
settings.setDisplayedAttributes(displayedAttributes);
settings.setRankingRules(rankingRules);

if (sortAttributes != null) {
settings.setSortableAttributes(sortAttributes);
}

if (filterableAttributes != null) {
settings.setFilterableAttributes(filterableAttributes);
}

if (distinctAttribute != null) {
settings.setDistinctAttribute(distinctAttribute);
}

if (stopWords != null) {
settings.setStopWords(stopWords);
}

return settings;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ public SimpleMeilisearchRepository(EntityInformation<T, ID> entityInformation,

Assert.notNull(entityInformation, "EntityInformation must not be null!");
this.entityType = entityInformation.getJavaType();

if (isRequiredApplySettings()) {
meilisearchOperations.applySettings(entityType);
}
}

private boolean isRequiredApplySettings() {
return meilisearchOperations.getMeilisearchConverter()
.getMappingContext().getRequiredPersistentEntity(entityType).isApplySettings();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,18 @@

import static org.assertj.core.api.Assertions.*;

import io.vanslog.spring.data.meilisearch.annotations.Document;
import io.vanslog.spring.data.meilisearch.client.ClientConfiguration;
import io.vanslog.spring.data.meilisearch.client.MeilisearchClient;
import io.vanslog.spring.data.meilisearch.core.MeilisearchOperations;
import io.vanslog.spring.data.meilisearch.entities.Movie;
import io.vanslog.spring.data.meilisearch.repository.MeilisearchRepository;
import io.vanslog.spring.data.meilisearch.repository.config.EnableMeilisearchRepositories;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

Expand All @@ -46,7 +47,7 @@ class MeilisearchConfigurationUnitTests {

@Autowired private MeilisearchClient meilisearchClient;
@Autowired private MeilisearchOperations meilisearchTemplate;
@Autowired private MovieRepository movieRepository;
@Autowired private ApplySettingsFalseRepository applySettingsFalseRepository;

@Test
void shouldCreateMeilisearchClient() {
Expand All @@ -67,10 +68,13 @@ void shouldCreateMeilisearchTemplate() {

@Test
void shouldCreateMeilisearchRepository() {
assertThat(movieRepository).isNotNull();
assertThat(applySettingsFalseRepository).isNotNull();
}

interface MovieRepository extends MeilisearchRepository<Movie, String> {}
@Document(indexUid = "test-index-config-namespace", applySettings = false)
record ApplySettingsFalseEntity(@Id String id) {}

interface ApplySettingsFalseRepository extends MeilisearchRepository<ApplySettingsFalseEntity, String> {}

@Configuration
@EnableMeilisearchRepositories(basePackages = { "io.vanslog.spring.data.meilisearch.config" },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@

import static org.assertj.core.api.Assertions.*;

import io.vanslog.spring.data.meilisearch.annotations.Document;
import io.vanslog.spring.data.meilisearch.client.MeilisearchClient;
import io.vanslog.spring.data.meilisearch.client.MeilisearchClientFactoryBean;
import io.vanslog.spring.data.meilisearch.core.MeilisearchTemplate;
import io.vanslog.spring.data.meilisearch.entities.Movie;
import io.vanslog.spring.data.meilisearch.repository.MeilisearchRepository;

import java.lang.reflect.Field;
Expand All @@ -30,6 +30,7 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.annotation.Id;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

Expand Down Expand Up @@ -65,8 +66,11 @@ void shouldUseGsonJsonHandler() throws NoSuchFieldException, IllegalAccessExcept

@Test
void shouldCreateMeilisearchRepository() {
assertThat(context.getBean(MovieRepository.class)).isInstanceOf(MovieRepository.class);
assertThat(context.getBean(ApplySettingsFalseRepository.class)).isInstanceOf(ApplySettingsFalseRepository.class);
}

interface MovieRepository extends MeilisearchRepository<Movie, String> {}
@Document(indexUid = "test-index-config-namespace", applySettings = false)
record ApplySettingsFalseEntity(@Id String id) {}

interface ApplySettingsFalseRepository extends MeilisearchRepository<ApplySettingsFalseEntity, String> {}
}
Loading
Loading