国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

springboot整合MeiliSearch輕量級搜索引擎

這篇具有很好參考價(jià)值的文章主要介紹了springboot整合MeiliSearch輕量級搜索引擎。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

一、Meilisearch與Easy Search點(diǎn)擊進(jìn)入官網(wǎng)了解,本文主要從小微型公司業(yè)務(wù)出發(fā),選擇meilisearch來作為項(xiàng)目的全文搜索引擎,還可以當(dāng)成來mongodb來使用。

二、starter封裝

1、項(xiàng)目結(jié)構(gòu)展示

springboot整合MeiliSearch輕量級搜索引擎,spring boot,搜索引擎,elasticsearch

2、引入依賴包(我是有包統(tǒng)一管理的fastjson用的1.2.83,gson用的2.8.6)

<dependencies>
        <dependency>
            <groupId>cn.iocoder.boot</groupId>
            <artifactId>yudao-common</artifactId>
        </dependency>
        <!-- meilisearch 輕量級搜索       -->
        <!-- https://mvnrepository.com/artifact/com.meilisearch.sdk/meilisearch-java -->
        <dependency>
            <groupId>com.meilisearch.sdk</groupId>
            <artifactId>meilisearch-java</artifactId>
            <version>0.11.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <!-- Web 相關(guān) -->
        <dependency>
            <groupId>cn.iocoder.boot</groupId>
            <artifactId>yudao-spring-boot-starter-web</artifactId>
            <scope>provided</scope> <!-- 設(shè)置為 provided,只有 OncePerRequestFilter 使用到 -->
        </dependency>
    </dependencies>

3、yml參數(shù)讀取代碼參考

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

/**
 * MeiliSearch 自動(dòng)裝配參數(shù)類
 * 2023年9月21日
 */
@ConfigurationProperties("yudao.meilisearch")
@Data
@Validated
public class MeiliSearchProperties {

    /**
     * 主機(jī)地址
     */
    private String hostUrl;
    /**
     * 接口訪問標(biāo)識(shí)
     */
    private String apiKey;

}

4、自動(dòng)配置類代碼參考

import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Config;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;


/**
 * MeiliSearch 自動(dòng)裝配類
 * 2023年9月21日
 */
@AutoConfiguration
@EnableConfigurationProperties({MeiliSearchProperties.class})
@EnableCaching
public class MeiliSearchAutoConfiguration {
    @Resource
    MeiliSearchProperties properties;

    @Bean
    @ConditionalOnMissingBean(Client.class)
    Client client() {
        return new Client(config());
    }

    @Bean
    @ConditionalOnMissingBean(Config.class)
    Config config() {
        return new Config(properties.getHostUrl(), properties.getApiKey());
    }

}

5、數(shù)據(jù)處理類參考

import java.util.List;

/**
 * MeiliSearch json解析類
 * 2023年9月21日
 */
public class JsonHandler {

    private com.meilisearch.sdk.json.JsonHandler jsonHandler = new MyGsonJsonHandler();

    public <T> SearchResult<T> resultDecode(String o, Class<T> clazz) {
        Object result = null;
        try {
            result = jsonHandler.decode(o, SearchResult.class, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result == null ? null : (SearchResult<T>) result;
    }

    public <T> List<T> listDecode(Object o, Class<T> clazz) {
        Object list = null;
        try {
            list = jsonHandler.decode(o, List.class, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list == null ? null : (List<T>) list;
    }

    public String encode(Object o) {
        try {
            return jsonHandler.encode(o);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public <T> T decode(Object o, Class<T> clazz) {
        T t = null;
        try {
            t = jsonHandler.decode(o, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
}

6、MyGsonJsonHandler類改寫基本沒啥用(meilisearch通過官方sdk到springboot的雪花id會(huì)丟失精度,我是加了冗余字段把雪花id存進(jìn)去當(dāng)主鍵用的。還有就是LocalDateTime不用大于小于范圍查詢,我是把要范圍查詢的時(shí)間字段冗余成long類型),有對LocalDateTime和雪花id Long存儲(chǔ)有更好的解決方案的歡迎留言。

import com.alibaba.fastjson.JSON;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.meilisearch.sdk.exceptions.JsonDecodingException;
import com.meilisearch.sdk.exceptions.JsonEncodingException;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.meilisearch.sdk.model.Key;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyGsonJsonHandler implements com.meilisearch.sdk.json.JsonHandler {
    private Gson gson;

    public MyGsonJsonHandler() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, typeOfT, context) ->
                LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ISO_DATE_TIME));
//        gsonBuilder.registerTypeAdapter(Long.class, (JsonDeserializer<Long>) (json, typeOfT, context) -> {
//            Long parse = Long.parseLong(json.getAsJsonPrimitive().getAsString());
//            雪花id科學(xué)計(jì)數(shù)后轉(zhuǎn)支付串會(huì)丟失進(jìn)度小1啥的
//            return parse;
//        });
        this.gson = gsonBuilder.create();
    }

    public String encode(Object o) throws MeilisearchException {
        if (o != null && o.getClass() == String.class) {
            return (String) o;
        } else {
            if (o != null && o.getClass() == Key.class) {
                Key key = (Key) o;
                if (key.getExpiresAt() == null) {
                    JsonElement jsonElement = this.gson.toJsonTree(o);
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    jsonObject.add("expiresAt", JsonNull.INSTANCE);
                    o = jsonObject;
                }
            }
            try {
                return JSON.toJSONString(o);
            } catch (Exception var6) {
                throw new JsonEncodingException(var6);
            }
        }
    }

    public <T> T decode(Object o, Class<?> targetClass, Class<?>... parameters) throws MeilisearchException {
        if (o == null) {
            throw new JsonDecodingException("Response to deserialize is null");
        } else if (targetClass == String.class) {
            return (T) o;
        } else {
            try {
                if (parameters != null && parameters.length != 0) {
                    TypeToken<?> parameterized = TypeToken.getParameterized(targetClass, parameters);
                    Type type = parameterized.getType();
                    String json = this.gson.toJson(o);
                    json = json.replace("\\", "");
                    //去除json首位字符串
                    json = json.substring(1, json.length() - 1);
                    String string = o.toString();
                    return this.gson.fromJson(string, type);
//                    return  JSON.parseObject(string, type);
                } else {
                    return (T) JSON.parseObject((String) o, targetClass);
                }
            } catch (JsonSyntaxException var5) {
                throw new JsonDecodingException(var5);
            }
        }
    }
}

7、自定義注解代碼參考

import java.lang.annotation.*;

/**
 * MeiliSearch
 * 2023年9月21日
 */
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MSFiled {

    /**
     * 是否開啟過濾
     */
    boolean openFilter() default false;

    /**
     * 是否不展示
     */
    boolean noDisplayed() default false;

    /**
     * 是否開啟排序
     */
    boolean openSort() default false;


    /**
     *  處理的字段名
     */
    String key() ;
}





import java.lang.annotation.*;

/**
 * MeiliSearch
 * 2023年9月21日
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MSIndex {

    /**
     * 索引
     */
    String uid() default "";

    /**
     * 主鍵
     */
    String primaryKey() default "";

    /**
     * 分類最大數(shù)量
     */
    int maxValuesPerFacet() default 100;

    /**
     *  單次查詢最大數(shù)量
     */
    int maxTotalHits() default 1000;
}

8、返回結(jié)果解析類參考

import java.util.List;

/**
 * MeiliSearch
 * 2023年9月21日
 */
public class SearchResult<T> {

    private String query;
    private long offset;
    private long limit;
    private long processingTimeMs;
    private long nbHits;


    private long hitsPerPage;
    private long page;
    private long totalPages;
    private long totalHits;

    private boolean exhaustiveNbHits;

    private List<T> hits;

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public long getOffset() {
        return offset;
    }

    public void setOffset(long offset) {
        this.offset = offset;
    }

    public long getLimit() {
        return limit;
    }

    public void setLimit(long limit) {
        this.limit = limit;
    }

    public long getProcessingTimeMs() {
        return processingTimeMs;
    }

    public void setProcessingTimeMs(long processingTimeMs) {
        this.processingTimeMs = processingTimeMs;
    }

    public long getNbHits() {
        return nbHits;
    }

    public void setNbHits(long nbHits) {
        this.nbHits = nbHits;
    }

    public boolean isExhaustiveNbHits() {
        return exhaustiveNbHits;
    }

    public void setExhaustiveNbHits(boolean exhaustiveNbHits) {
        this.exhaustiveNbHits = exhaustiveNbHits;
    }

    public List<T> getHits() {
        return hits;
    }

    public void setHits(List<T> hits) {
        this.hits = hits;
    }

    @Override
    public String toString() {
        return "SearchResult{" +
                "query='" + query + '\'' +
                ", offset=" + offset +
                ", limit=" + limit +
                ", processingTimeMs=" + processingTimeMs +
                ", nbHits=" + nbHits +
                ", exhaustiveNbHits=" + exhaustiveNbHits +
                ", hits=" + hits +
                '}';
    }

    public long getHitsPerPage() {
        return hitsPerPage;
    }

    public void setHitsPerPage(long hitsPerPage) {
        this.hitsPerPage = hitsPerPage;
    }

    public long getPage() {
        return page;
    }

    public void setPage(long page) {
        this.page = page;
    }

    public long getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(long totalPages) {
        this.totalPages = totalPages;
    }

    public long getTotalHits() {
        return totalHits;
    }

    public void setTotalHits(long totalHits) {
        this.totalHits = totalHits;
    }
}

9、基礎(chǔ)操作接口封裝

import cn.iocoder.yudao.framework.meilisearch.json.SearchResult;
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.Settings;
import com.meilisearch.sdk.model.Task;
import com.meilisearch.sdk.model.TaskInfo;

import java.util.List;

/**
 * MeiliSearch 基礎(chǔ)接口
 * 2023年9月21日
 */
interface DocumentOperations<T> {

    T get(String identifier);

    List<T> list();

    List<T> list(int limit);

    List<T> list(int offset, int limit);

    long add(T document);

    long update(T document);

    long add(List<T> documents);

    long update(List<T> documents);

    long delete(String identifier);

    long deleteBatch(String... documentsIdentifiers);

    long deleteAll();

    SearchResult<T> search(String q);

    SearchResult<T> search(String q, int offset, int limit);

    SearchResult<T> search(SearchRequest sr);

    String select(SearchRequest sr);

    Settings getSettings();

    TaskInfo updateSettings(Settings settings);

    TaskInfo resetSettings();

    Task getUpdate(int updateId);

//    UpdateStatus updateSettings(Settings settings);
//
//    UpdateStatus resetSettings();
//
//    UpdateStatus getUpdate(int updateId);
//
//    UpdateStatus[] getUpdates();
}

10、基本操作實(shí)現(xiàn)

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.meilisearch.json.JsonHandler;
import cn.iocoder.yudao.framework.meilisearch.json.MSFiled;
import cn.iocoder.yudao.framework.meilisearch.json.MSIndex;
import cn.iocoder.yudao.framework.meilisearch.json.SearchResult;
import com.alibaba.fastjson.JSON;
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * MeiliSearch 基本操作實(shí)現(xiàn)
 * 2023年9月21日
 */
public class MeilisearchRepository<T> implements InitializingBean, DocumentOperations<T> {

    private Index index;
    private Class<T> tClass;
    private JsonHandler jsonHandler = new JsonHandler();

    @Resource
    private Client client;

    @Override
    public T get(String identifier) {
        T document;
        try {
            document = getIndex().getDocument(identifier, tClass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return document;
    }

    @Override
    public List<T> list() {
        List<T> documents;
        try {
            documents = Optional.ofNullable(getIndex().getDocuments(tClass))
                    .map(indexDocument -> indexDocument.getResults())
                    .map(result -> Arrays.asList(result))
                    .orElse(new ArrayList<>());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return documents;
    }

    @Override
    public List<T> list(int limit) {
        List<T> documents;
        try {
            DocumentsQuery query = new DocumentsQuery();
            query.setLimit(limit);
            documents = Optional.ofNullable(index.getDocuments(query, tClass))
                    .map(indexDocument -> indexDocument.getResults())
                    .map(result -> Arrays.asList(result))
                    .orElse(new ArrayList<>());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return documents;
    }

    @Override
    public List<T> list(int offset, int limit) {
        List<T> documents;
        try {
            DocumentsQuery query = new DocumentsQuery();
            query.setLimit(limit);
            query.setOffset(offset);
            documents = Optional.ofNullable(getIndex().getDocuments(query, tClass))
                    .map(indexDocument -> indexDocument.getResults())
                    .map(result -> Arrays.asList(result))
                    .orElse(new ArrayList<>());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return documents;
    }

    @Override
    public long add(T document) {
        List<T> list = Collections.singletonList(document);
        return add(list);
    }

    @Override
    public long update(T document) {
        List<T> list = Collections.singletonList(document);
        return update(list);
    }

    @Override
    public long add(List documents) {
        try {
            if (ObjectUtil.isNotNull(documents)) {
                String jsonString = JSON.toJSONString(documents);
                if (ObjectUtil.isNotNull(jsonString)) {
                    TaskInfo taskInfo = getIndex().addDocuments(jsonString);
                    if (ObjectUtil.isNotNull(taskInfo)) {
                        return taskInfo.getTaskUid();
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(documents.toString(), e);
        }
        return 0;
    }


    @Override
    public long update(List documents) {
        int updates;
        try {
            updates = getIndex().updateDocuments(JSON.toJSONString(documents)).getTaskUid();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return updates;
    }


    @Override
    public long delete(String identifier) {
        int taskId;
        try {
            taskId = getIndex().deleteDocument(identifier).getTaskUid();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return taskId;
    }

    @Override
    public long deleteBatch(String... documentsIdentifiers) {
        int taskId;
        try {
            taskId = getIndex().deleteDocuments(Arrays.asList(documentsIdentifiers)).getTaskUid();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return taskId;
    }

    @Override
    public long deleteAll() {
        int taskId;
        try {
            taskId = getIndex().deleteAllDocuments().getTaskUid();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return taskId;
    }


    @Override
    public cn.iocoder.yudao.framework.meilisearch.json.SearchResult<T> search(String q) {
        String result;
        try {
            result = JSON.toJSONString(getIndex().search(q));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonHandler.resultDecode(result, tClass);
    }

    @Override
    public cn.iocoder.yudao.framework.meilisearch.json.SearchResult<T> search(String q, int offset, int limit) {
        SearchRequest searchRequest = SearchRequest.builder()
                .q(q)
                .offset(offset)
                .limit(limit)
                .build();
        return search(searchRequest);
    }

    //    @Override
    public cn.iocoder.yudao.framework.meilisearch.json.SearchResult<T> searchPage(String q) {
        SearchRequest searchRequest = SearchRequest.builder()
                .q(q)
                .build();
        return search(searchRequest);
    }

    @Override
    public SearchResult<T> search(SearchRequest sr) {
        String result;
        try {
            result = "";
            if (ObjectUtil.isNotNull(sr)) {
                if (ObjectUtil.isNull(getIndex())) {
                    initIndex();
                }
                Searchable search = getIndex().search(sr);
                String jsonString = JSON.toJSONString(search);
                result = jsonString;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonHandler.resultDecode(result, tClass);
    }


    @Override
    public String select(SearchRequest sr) {
        try {
            if (ObjectUtil.isNotNull(sr)) {
                if (ObjectUtil.isNull(getIndex())) {
                    initIndex();
                }
                Searchable search = getIndex().search(sr);
                String jsonString = JSON.toJSONString(search);
                return jsonString;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public Settings getSettings() {
        try {
            return getIndex().getSettings();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TaskInfo updateSettings(Settings settings) {
        try {
            return getIndex().updateSettings(settings);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TaskInfo resetSettings() {
        try {
            return getIndex().resetSettings();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Task getUpdate(int updateId) {
        try {
            return getIndex().getTask(updateId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initIndex();
    }

    public Index getIndex() {
        if (ObjectUtil.isNull(index)) {
            try {
                initIndex();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return index;
    }

    /**
     * 初始化索引信息
     *
     * @throws Exception
     */
    private void initIndex() throws Exception {
        Class<? extends MeilisearchRepository> clazz = getClass();
        tClass = (Class<T>) ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];
        MSIndex annoIndex = tClass.getAnnotation(MSIndex.class);
        String uid = annoIndex.uid();
        String primaryKey = annoIndex.primaryKey();
        if (StringUtils.isEmpty(uid)) {
            uid = tClass.getSimpleName().toLowerCase();
        }
        if (StringUtils.isEmpty(primaryKey)) {
            primaryKey = "id";
        }
        int maxTotalHit = 1000;
        int maxValuesPerFacet = 100;
        if (Objects.nonNull(annoIndex.maxTotalHits())) {
            maxTotalHit = annoIndex.maxTotalHits();
        }
        if (Objects.nonNull(annoIndex.maxValuesPerFacet())) {
            maxValuesPerFacet = 100;
        }

        List<String> filterKey = new ArrayList<>();
        List<String> sortKey = new ArrayList<>();
        List<String> noDisPlay = new ArrayList<>();
        //獲取類所有屬性
        for (Field field : tClass.getDeclaredFields()) {
            //判斷是否存在這個(gè)注解
            if (field.isAnnotationPresent(MSFiled.class)) {
                MSFiled annotation = field.getAnnotation(MSFiled.class);
                if (annotation.openFilter()) {
                    filterKey.add(annotation.key());
                }

                if (annotation.openSort()) {
                    sortKey.add(annotation.key());
                }
                if (annotation.noDisplayed()) {
                    noDisPlay.add(annotation.key());
                }
            }
        }
        Results<Index> indexes = client.getIndexes();
        Index[] results = indexes.getResults();
        Boolean isHaveIndex = false;
        for (Index result : results) {
            if (uid.equals(result.getUid())) {
                isHaveIndex = true;
                break;
            }
        }

        if (isHaveIndex) {
            client.updateIndex(uid, primaryKey);
        } else {
            client.createIndex(uid, primaryKey);
        }
        this.index = client.getIndex(uid);
        Settings settings = new Settings();
        settings.setDisplayedAttributes(noDisPlay.size() > 0 ? noDisPlay.toArray(new String[noDisPlay.size()]) : new String[]{"*"});
        settings.setFilterableAttributes(filterKey.toArray(new String[filterKey.size()]));
        settings.setSortableAttributes(sortKey.toArray(new String[sortKey.size()]));
        index.updateSettings(settings);
    }

}


11、指定自動(dòng)配置類所在

springboot整合MeiliSearch輕量級搜索引擎,spring boot,搜索引擎,elasticsearch

12、項(xiàng)目有統(tǒng)一版本管理的設(shè)置下版本管理

springboot整合MeiliSearch輕量級搜索引擎,spring boot,搜索引擎,elasticsearch

二、項(xiàng)目引用

1、引入starter依賴(沒有版本統(tǒng)一管理的要把version加上)

springboot整合MeiliSearch輕量級搜索引擎,spring boot,搜索引擎,elasticsearch

2、基本使用

2.1、建立索引(寬表)

import cn.iocoder.yudao.framework.meilisearch.json.MSFiled;
import cn.iocoder.yudao.framework.meilisearch.json.MSIndex;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@MSIndex(uid = "com_baidu_main", primaryKey = "idToString")
public class MainDO {
    private Long id;
    @MSFiled(openFilter = true, key = "idToString", openSort = true)
    private idToString;
    private String seedsName;
    @MSFiled(openFilter = true, key = "isDelete")
    private Integer isDelete;
    @MSFiled(openFilter = true, key = "status")
    private Integer status;

    @MSFiled(openFilter = true, key = "classFiledId")
    private Integer classFiledId;
    private String classFiledName;
    @MSFiled(openFilter = true, key = "tags")
    private List<TageInfo> tags;

    @MSFiled(openFilter = true,key = "createTime",openSort = true)
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
    private LocalDateTime createTime;
    @MSFiled(openFilter = true,key = "createTimeToLong",openSort = true)
    private LocalDateTime createTimeToLong;
}

2.2、集成starter里邊的mapper對milisearch進(jìn)行基本操作

import cn.iocoder.yudao.framework.meilisearch.core.MeilisearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public class MeiliSearchMapper extends MeilisearchRepository<MainDO> {
}

2.3、當(dāng)mongodb實(shí)現(xiàn)精準(zhǔn)分頁查詢

        // 條件組裝,實(shí)體類根據(jù)業(yè)務(wù)需要提前加好業(yè)務(wù)字段索引注解@MSFiled,顯示隱藏 索引等
        StringBuffer sb = new StringBuffer();
        if (ObjectUtil.isNotEmpty(pageParam.getStartTime())) {
            sb.append("createTimeToLong>=").append(pageParam.getStartTime()).append(" AND ");
        }
        if (ObjectUtil.isNotEmpty(pageParam.getEndTime())) {
            sb.append("createTimeToLong<=").append(pageParam.getEndTime()).append(" AND ");
        }
        sb.append("userId=" + SecurityFrameworkUtils.getLoginUserId());

        // 分頁查詢及排序
        SearchRequest searchRequest4 = SearchRequest.builder()
                .sort(new String[]{"createTime:desc"})
                .page(pageParam.getPageNo())
                .hitsPerPage(pageParam.getPageSize())
                .filter(new String[]{sb.toString()}).build();
        SearchResult<SeedsDO> search = meiliSearchMapper.search(searchRequest4);
        return SeedCultivateConvert.INSTANCE.convert(search);






        // SeedCultivateConvert.INSTANCE.convert是個(gè)類轉(zhuǎn)化器可手動(dòng)轉(zhuǎn)換成分頁的統(tǒng)一數(shù)據(jù)格式
        pageResult.setList(search.getHits());
        pageResult.setTotal(search.getTotalPages());
        .......


2.4、其他基本使用文章來源地址http://www.zghlxwxcb.cn/news/detail-714466.html

@Resource
private MeiliSearchMapper meiliSearchMapper;

//根據(jù)標(biāo)簽分頁查詢
SearchRequest searchRequest4 = SearchRequest.builder()
                .limit(pageParam.getPageSize().intValue())
                .sort(new String[]{"createTime:desc"})
                .offset(pageParam.getPageNo().intValue() == 0 ? pageParam.getPageNo().intValue() : (pageParam.getPageNo().intValue() - 1) * pageParam.getPageSize().intValue())
                .filter(new String[]{"tags.id=" + "10010" + " AND status=1 AND isDelete=0"}).build();
SearchResult<MainDO> search4 = meiliSearchMapper.search(searchRequest4);

//保存Or編輯
List<SeedsDO> articleCardDTOS = new ArrayList<>();
Boolean aBoolean = meiliSearchMapper.add(articleCardDTOS) > 0 ? Boolean.TRUE : Boolean.FALSE;
//按id刪除
meiliSearchMapper.delete(String.valueOf(10085));

//根據(jù)類目分頁查詢
SearchRequest searchRequest3 = SearchRequest.builder()
                .limit(pageParam.getPageSize().intValue())
                .offset(pageParam.getPageNo().intValue() == 0 ? pageParam.getPageNo().intValue() : (pageParam.getPageNo().intValue() - 1) * pageParam.getPageSize().intValue())
                .build();
StringBuffer sb1 = new StringBuffer();
sb.append("status =1 AND isDelete=0").append(" AND ").append("categoryId =").append(10086L);
searchRequest.setFilter(new String[]{sb.toString()});
searchRequest.setSort(new String[]{"createTime:desc"});
SearchResult<SeedsDO> search3 = meiliSearchMapper.search(searchRequest3);

到了這里,關(guān)于springboot整合MeiliSearch輕量級搜索引擎的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring Boot整合Postgres實(shí)現(xiàn)輕量級全文搜索

    Spring Boot整合Postgres實(shí)現(xiàn)輕量級全文搜索

    有這樣一個(gè)帶有搜索功能的用戶界面需求: 搜索流程如下所示: 這個(gè)需求涉及兩個(gè)實(shí)體: “評分(Rating)、用戶名(Username)”數(shù)據(jù)與 User 實(shí)體相關(guān) “創(chuàng)建日期(create date)、觀看次數(shù)(number of views)、標(biāo)題(title)、正文(body)”與 Story 實(shí)體相關(guān) 需要支持的功能對 User

    2024年02月19日
    瀏覽(91)
  • Springboot集成輕量級內(nèi)存數(shù)據(jù)庫H2

    最近做一個(gè)小項(xiàng)目,需要存儲(chǔ)的數(shù)據(jù)不多,用mysql太重了,用其他的Redis之類的也不太方便,然后就想到了H2,他就是一個(gè)jar包,可以和項(xiàng)目一起打包發(fā)布,非常適合數(shù)據(jù)量不多的微小系統(tǒng),下面大概介紹下H2的基本知識(shí)和Springboot的集成 H2是一個(gè)用Java開發(fā)的嵌入式數(shù)據(jù)庫,它本

    2024年02月07日
    瀏覽(17)
  • SimSearch:一個(gè)輕量級的springboot項(xiàng)目索引構(gòu)建工具,實(shí)現(xiàn)快速模糊搜索

    大部分項(xiàng)目都會(huì)涉及模糊搜索功能,而實(shí)現(xiàn)模糊搜索一般分為兩個(gè)派系: like簡約派系 搜索引擎派系 對于較為大型的項(xiàng)目來說,使用Solr、ES或者M(jìn)ilvus之類的引擎是比較流行的選擇了(效果只能說優(yōu)秀),而對于中小型項(xiàng)目,如果考慮這些較為重型的引擎,就意味著開發(fā)成本和

    2024年02月02日
    瀏覽(30)
  • 告別if else!試試這款輕量級流程引擎吧,跟SpringBoot絕配!

    告別if else!試試這款輕量級流程引擎吧,跟SpringBoot絕配!

    之前同事用了一款輕量級的規(guī)則引擎腳本 AviatorScript ,我也跟著用了起來,真的挺香,能少寫很多代碼。這期就給大家介紹一下這款規(guī)則引擎。 AviatorScript 是一門高性能、輕量級寄宿于 JVM (包括 Android 平臺(tái))之上的腳本語言。 它起源于2010年,作者對當(dāng)時(shí)已有的一些產(chǎn)品不是

    2024年02月13日
    瀏覽(34)
  • git輕量級服務(wù)器gogs、gitea,非輕量級gitbucket

    git輕量級服務(wù)器gogs、gitea,非輕量級gitbucket

    本文來源:git輕量級服務(wù)器gogs、gitea,非輕量級gitbucket, 或 gitcode/gogs,gitea.md 結(jié)論: gogs、gitea很相似 確實(shí)輕, gitbucket基于java 不輕, 這三者都不支持組織樹(嵌套組織 nested group) 只能一層組織。 個(gè)人用,基于gogs、gitea,兩層結(jié)構(gòu)樹 簡易辦法: 把用戶當(dāng)成第一層節(jié)點(diǎn)、該用戶的

    2024年02月07日
    瀏覽(140)
  • 輕量靈動(dòng): 革新輕量級服務(wù)開發(fā)

    輕量靈動(dòng): 革新輕量級服務(wù)開發(fā)

    從 JDK 8 升級到 JDK 17 可以讓你的應(yīng)用程序受益于新的功能、性能改進(jìn)和安全增強(qiáng)。下面是一些 JDK 8 升級到 JDK 17 的最佳實(shí)戰(zhàn): 1.1、確定升級的必要性:首先,你需要評估你的應(yīng)用程序是否需要升級到 JDK 17。查看 JDK 17 的新特性、改進(jìn)和修復(fù)的 bug,以確定它們對你的應(yīng)用程序

    2024年02月07日
    瀏覽(99)
  • 輕量級 HTTP 請求組件

    Apache HttpClient 是著名的 HTTP 客戶端請求工具——現(xiàn)在我們模擬它打造一套簡單小巧的請求工具庫, 封裝 Java 類庫里面的 HttpURLConnection 對象來完成日常的 HTTP 請求,諸如 GET、HEAD、POST 等等,并嘗試應(yīng)用 Java 8 函數(shù)式風(fēng)格來制定 API。 組件源碼在:https://gitee.com/sp42_admin/ajaxjs/tr

    2024年02月01日
    瀏覽(101)
  • Kotlin 輕量級Android開發(fā)

    Kotlin 輕量級Android開發(fā)

    Kotlin 是一門運(yùn)行在 JVM 之上的語言。 它由 Jetbrains 創(chuàng)建,而 Jetbrains 則是諸多強(qiáng)大的工具(如知名的 Java IDE IntelliJ IDEA )背后的公司。 Kotlin 是一門非常簡單的語言,其主要目標(biāo)之一就是提供強(qiáng)大語言的同時(shí)又保持簡單且精簡的語法。 其主要特性如下所示: 輕量級:這一點(diǎn)對

    2024年02月07日
    瀏覽(904)
  • Tomcat輕量級服務(wù)器

    Tomcat輕量級服務(wù)器

    目錄 1.常見系統(tǒng)架構(gòu)? C-S架構(gòu) B-S架構(gòu) 2.B-S架構(gòu)系統(tǒng)的通信步驟 3.常見WEB服服務(wù)器軟件 4.Tomcat服務(wù)器的配置 下載安裝 環(huán)境變量配置 測試環(huán)境變量是否配置成功 測試Tomcat服務(wù)器是否配置成功? Tomcat窗口一閃而過的解決步驟 Tomcat解決亂碼 介紹: C-S架構(gòu)即Client/Server(客戶端/服務(wù)

    2023年04月14日
    瀏覽(103)
  • 一種輕量級定時(shí)任務(wù)實(shí)現(xiàn)

    現(xiàn)在市面上有各式各樣的分布式定時(shí)任務(wù),每個(gè)都有其獨(dú)特的特點(diǎn),我們這邊的項(xiàng)目因?yàn)橐婚_始使用的是分布式開源調(diào)度框架TBSchedule,但是這個(gè)框架依賴ZK, 由于ZK的不穩(wěn)定性和項(xiàng)目老舊無人維護(hù) ,導(dǎo)致我們的定時(shí)任務(wù)會(huì)偶發(fā)出現(xiàn)異常,比如:任務(wù)停止、任務(wù)項(xiàng)丟失、任務(wù)不

    2024年02月14日
    瀏覽(96)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包