liang-spring-ai/src/main/java/com/example/springaidemo/service/VectorService.java

33 lines
1.2 KiB
Java
Raw Normal View History

2025-07-18 16:52:25 +00:00
package com.example.springaidemo.service;
2025-07-19 08:33:11 +00:00
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
2025-07-18 16:52:25 +00:00
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
2025-07-19 08:33:11 +00:00
import org.springframework.stereotype.Service;
2025-07-18 16:52:25 +00:00
2025-07-19 08:33:11 +00:00
import java.util.List;
@Service
2025-07-18 16:52:25 +00:00
public class VectorService {
2025-07-19 08:33:11 +00:00
@Autowired VectorStore vectorStore;
public void storeVector(){
List<Document> documents = List.of(
new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!"),
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("You walk forward facing the past and you turn back toward the future."));
2025-07-18 16:52:25 +00:00
// Add the documents to Elasticsearch 需要注意的是elasticSearch的版本需要大于8.10.0
2025-07-19 08:33:11 +00:00
vectorStore.add(documents);
2025-07-18 16:52:25 +00:00
2025-07-19 08:33:11 +00:00
// Retrieve documents similar to a query
SearchRequest searchRequest = SearchRequest.builder().query("Spring")
.topK(5)
.build();
List<Document> results = this.vectorStore.similaritySearch(searchRequest);
System.out.println(results);
2025-07-19 08:33:11 +00:00
}
2025-07-18 16:52:25 +00:00
}