- 引言
- Java 項目集成 Manticoresearch
- 新增文檔操作
- 查詢文檔操作
- SQL 查詢
- API 查詢
- 總結
引言
Manticore Search 是一個使用 C++ 開發的高性能搜索引擎,創建于 2017 年,其前身是 Sphinx Search。它顯著改進了 Sphinx 的功能,修復了數百個錯誤,幾乎完全重寫了代碼并保持開源。在性能方面,相比 MySQL、Elasticsearch 等都有顯著優勢。
Java 項目集成 Manticoresearch
若要在 Java 項目中集成 Manticoresearch,需在 pom.xml
文件添加 Maven 依賴:
<dependencies><!-- Maven --><dependency><groupId>com.manticoresearch</groupId><artifactId>manticoresearch</artifactId><version>8.0.0</version></dependency>
</dependencies>
項目中的 pom.xml
文件也有相關依賴配置,如 <artifactId>manticoresearch</artifactId>
,表明項目已集成該客戶端。
新增文檔操作
在項目的中,展示了如何使用 Java API 向 Manticoresearch 新增文檔。以下是關鍵代碼片段:
public class InsertExample {public static void main(String[] args) {ApiClient defaultClient = Configuration.getDefaultApiClient();defaultClient.setBasePath("http://127.0.0.1:9308");IndexApi indexApi = new IndexApi(defaultClient);try {String tableName = "acc_20250625";InsertDocumentRequest indexRequest = new InsertDocumentRequest();Acc acc = new Acc();acc.setCaller("20250625");//...其他屬性indexRequest.table(tableName).id(System.currentTimeMillis()).setDoc(doc);indexApi.insert(indexRequest);}} catch (ApiException | InterruptedException e) {System.err.println("Exception when calling Api function");e.printStackTrace();}}
}
上述代碼先創建 ApiClient
并設置服務地址,接著實例化 IndexApi
,然后構建 InsertDocumentRequest
對象并設置文檔內容,最后調用 insert
方法將文檔插入指定表中。
查詢文檔操作
SQL 查詢
在項目的中,展示了如何使用 SQL 進行文檔查詢。示例代碼如下:
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://127.0.0.1:9308");
UtilsApi utilsApi = new UtilsApi(defaultClient);try {SqlResponse selectResultList = utilsApi.sql("select * from testrt where gid =66", true);System.out.println(selectResultList);// 解析結果到對象JSON.parseArray(JSON.toJSONString(selectResultList.get())).forEach(str -> {ManticoreResult<TestRT> result = JSON.parseObject(JSON.toJSONString(str),new TypeReference<ManticoreResult<TestRT>>() {});System.out.println(result);});
} catch (ApiException e) {System.err.println("Exception when calling Api function");e.printStackTrace();
}
代碼中創建 UtilsApi
實例,調用 sql
方法執行 SQL 查詢語句,最后將查詢結果解析為 ManticoreResult
對象。
API 查詢
同樣在項目中,展示了使用 Java API 進行文檔查詢的方法:
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://127.0.0.1:9308");
SearchApi searchApi = new SearchApi(defaultClient);try {String tableName = "testrt";SearchQuery query = new SearchQuery();query.setQueryString("@title test");SearchRequest searchRequest = new SearchRequest();searchRequest.table(tableName).query(query);SearchResponse searchResponse = searchApi.search(searchRequest);System.out.println(searchResponse);
} catch (ApiException e) {System.err.println("Exception when calling Api function");e.printStackTrace();
}
此代碼創建 SearchApi
實例,構建 SearchQuery
和 SearchRequest
對象,設置查詢條件后調用 search
方法執行查詢并輸出結果。
總結
通過上述介紹和項目代碼示例,我們了解了如何在 Java 項目中集成 Manticoresearch,以及如何使用其 Java API 進行新增文檔和查詢文檔操作。SQL 查詢和 API 查詢各有優勢,開發者可根據實際需求選擇合適的查詢方式。Manticoresearch 憑借其高性能和易用性,在全文搜索領域具有廣闊的應用前景。