本文详细介绍了如何在SpringBoot项目中集成Elasticsearch(ES),并进行基本的操作。首先,通过学习Linux基础命令,用户可以进入编辑模式进行文件编辑,编辑完成后退出并保存文件。接着,文章讲解了如何使用Elasticsearch进行索引的创建和文档的增删改查等操作。为了方便操作,本文推荐使用es-head作为图形化工具。需要注意的是,高亮显示功能在ES7.9.x版本中才被引入,而在ES7.7版本中可能会出现报错。此外,由于前后端分离的架构,直接输入ES地址无法连接,需要进行跨域配置。
SpringBoot, Elasticsearch, es-head, 跨域配置, 索引操作
在现代的软件开发中,SpringBoot因其简洁和高效的特点而广受欢迎。而Elasticsearch(ES)则以其强大的搜索和分析能力,在大数据处理领域占据一席之地。将这两者结合,可以为应用程序提供高效的搜索和数据处理能力。以下是详细的环境搭建步骤:
pom.xml
文件中添加Elasticsearch的依赖。这可以通过Maven或Gradle来实现。例如,使用Maven时,可以在pom.xml
中添加以下依赖:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
application.properties
或application.yml
文件中配置Elasticsearch的连接信息。例如:spring:
elasticsearch:
rest:
uris: http://localhost:9200
bin/elasticsearch
@SpringBootTest
public class ElasticsearchTest {
@Autowired
private RestHighLevelClient client;
@Test
public void testConnection() throws IOException {
Request request = new Request("GET", "/");
Response response = client.performRequest(request);
System.out.println(response.getStatusLine().getStatusCode());
}
}
在Linux环境中,掌握一些基础命令对于文件编辑和系统管理至关重要。以下是一些常用的Linux命令及其用途:
vi
或nano
编辑器打开文件。例如,使用vi
编辑器打开一个文件:vi filename.txt
vi
编辑器中,按i
键进入插入模式,可以开始编辑文件。编辑完成后,按Esc
键退出插入模式,然后输入:wq
保存并退出。cat
命令查看文件内容:cat filename.txt
find
命令查找文件。例如,查找当前目录及其子目录下的所有.txt
文件:find . -name "*.txt"
cp
、mv
和rm
命令进行文件操作。例如,复制文件:cp source.txt destination.txt
Elasticsearch的安装和配置相对简单,但需要一些基本的系统管理知识。以下是详细的安装和配置步骤:
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.0-linux-x86_64.tar.gz
tar
命令解压下载的文件:tar -xzf elasticsearch-7.9.0-linux-x86_64.tar.gz
config/elasticsearch.yml
文件,配置Elasticsearch的基本参数。例如,设置集群名称和节点名称:cluster.name: my-cluster
node.name: node-1
bin/elasticsearch
http://localhost:9200
,如果看到类似以下的JSON响应,说明Elasticsearch已成功启动:{
"name" : "node-1",
"cluster_name" : "my-cluster",
"cluster_uuid" : "uXjYzWQdRkGhIJKLmNOpQw",
"version" : {
"number" : "7.9.0",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "a479a2a",
"build_date" : "2020-08-11T21:36:46.119083Z",
"build_snapshot" : false,
"lucene_version" : "8.6.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
通过以上步骤,您可以在SpringBoot项目中成功集成Elasticsearch,并进行基本的操作。接下来,我们将进一步探讨如何使用Elasticsearch进行索引的创建和文档的增删改查等操作。
在Elasticsearch中,索引是存储相关数据的逻辑空间。创建和管理索引是使用Elasticsearch进行数据操作的基础。以下是如何在SpringBoot项目中创建和管理Elasticsearch索引的详细步骤:
RestHighLevelClient
对象创建索引。首先,定义索引的映射(mapping),然后发送请求创建索引。例如:@Service
public class ElasticsearchService {
@Autowired
private RestHighLevelClient client;
public void createIndex(String indexName) throws IOException {
CreateIndexRequest request = new CreateIndexRequest(indexName);
request.mapping("{\n" +
" \"properties\": {\n" +
" \"title\": {\n" +
" \"type\": \"text\"\n" +
" },\n" +
" \"content\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}", XContentType.JSON);
client.indices().create(request, RequestOptions.DEFAULT);
}
}
GetIndexRequest
对象来实现:public boolean indexExists(String indexName) throws IOException {
GetIndexRequest request = new GetIndexRequest(indexName);
return client.indices().exists(request, RequestOptions.DEFAULT);
}
DeleteIndexRequest
对象:public void deleteIndex(String indexName) throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
client.indices().delete(request, RequestOptions.DEFAULT);
}
PutMappingRequest
对象来实现:public void updateMapping(String indexName) throws IOException {
PutMappingRequest request = new PutMappingRequest(indexName);
request.source("{\n" +
" \"properties\": {\n" +
" \"newField\": {\n" +
" \"type\": \"keyword\"\n" +
" }\n" +
" }\n" +
"}", XContentType.JSON);
client.indices().putMapping(request, RequestOptions.DEFAULT);
}
在Elasticsearch中,文档是存储在索引中的基本单位。以下是如何在SpringBoot项目中进行文档的增删改查操作:
IndexRequest
对象可以向索引中添加文档。例如:public void addDocument(String indexName, String id, Map<String, Object> document) throws IOException {
IndexRequest request = new IndexRequest(indexName).id(id).source(document);
client.index(request, RequestOptions.DEFAULT);
}
SearchRequest
对象可以查询索引中的文档。例如,查询所有文档:public List<Map<String, Object>> searchDocuments(String indexName) throws IOException {
SearchRequest request = new SearchRequest(indexName);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
List<Map<String, Object>> documents = new ArrayList<>();
for (SearchHit hit : response.getHits()) {
documents.add(hit.getSourceAsMap());
}
return documents;
}
UpdateRequest
对象可以更新索引中的文档。例如:public void updateDocument(String indexName, String id, Map<String, Object> updates) throws IOException {
UpdateRequest request = new UpdateRequest(indexName, id).doc(updates);
client.update(request, RequestOptions.DEFAULT);
}
DeleteRequest
对象可以删除索引中的文档。例如:public void deleteDocument(String indexName, String id) throws IOException {
DeleteRequest request = new DeleteRequest(indexName, id);
client.delete(request, RequestOptions.DEFAULT);
}
高亮显示功能可以帮助用户在搜索结果中快速找到匹配的关键字。在Elasticsearch 7.9.x版本中,高亮显示功能得到了增强,但在7.7版本中可能会出现报错。以下是如何在SpringBoot项目中使用高亮显示功能:
public List<Map<String, Object>> searchWithHighlight(String indexName, String query) throws IOException {
SearchRequest request = new SearchRequest(indexName);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery("content", query));
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("content");
highlightBuilder.preTags("<span style='background-color: yellow;'>");
highlightBuilder.postTags("</span>");
sourceBuilder.highlighter(highlightBuilder);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
List<Map<String, Object>> documents = new ArrayList<>();
for (SearchHit hit : response.getHits()) {
Map<String, Object> source = hit.getSourceAsMap();
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField contentField = highlightFields.get("content");
if (contentField != null) {
Text[] fragments = contentField.fragments();
String highlightedContent = "";
for (Text fragment : fragments) {
highlightedContent += fragment.string();
}
source.put("content", highlightedContent);
}
documents.add(source);
}
return documents;
}
通过以上步骤,您可以在SpringBoot项目中有效地使用Elasticsearch进行索引的创建和管理,以及文档的增删改查操作。同时,高亮显示功能的使用可以提升用户体验,但需要注意版本兼容性和性能影响。希望这些内容对您的项目有所帮助。
在Elasticsearch的日常管理和操作中,使用图形化工具可以大大提升效率和便捷性。es-head是一个非常流行的Elasticsearch图形化操作工具,它提供了直观的界面,使得索引管理和文档操作变得更加简单。以下是es-head的安装和使用步骤:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
git clone https://github.com/mobz/elasticsearch-head.git
cd elasticsearch-head
npm install
npm run start
http://localhost:9100
上运行。打开浏览器,访问该地址即可看到es-head的界面。http://localhost:9200
),点击“Connect”按钮即可连接到Elasticsearch。通过es-head,用户可以轻松地进行索引的创建、删除、查看文档等操作,极大地简化了Elasticsearch的管理过程。
Kibana是Elasticsearch官方提供的图形化操作工具,它不仅提供了丰富的可视化功能,还支持索引管理和文档操作。Kibana的界面友好且功能强大,是Elasticsearch用户的首选工具。以下是Kibana的基本使用方法:
wget https://artifacts.elastic.co/downloads/kibana/kibana-7.9.0-linux-x86_64.tar.gz
tar
命令解压下载的文件:tar -xzf kibana-7.9.0-linux-x86_64.tar.gz
config/kibana.yml
文件,配置Kibana连接Elasticsearch的地址。例如:server.host: "0.0.0.0"
elasticsearch.hosts: ["http://localhost:9200"]
bin/kibana
http://localhost:5601
,即可看到Kibana的界面。在Kibana中,用户可以进行索引的管理、文档的查询和修改,还可以创建各种图表和仪表板,实现数据的可视化展示。Kibana的强大功能使得Elasticsearch的数据分析和管理变得更加直观和高效。
在现代Web应用中,前后端分离的架构越来越普遍。在这种架构下,前端应用通常运行在不同的域名或端口上,而Elasticsearch服务则运行在另一个域名或端口上。为了使前端应用能够顺利连接到Elasticsearch,需要进行跨域配置。以下是详细的跨域配置步骤:
config/elasticsearch.yml
文件,添加以下配置项:http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-methods: "GET, POST, PUT, DELETE, OPTIONS"
http.cors.allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
http.cors.enabled
用于启用跨域支持,http.cors.allow-origin
用于指定允许跨域访问的源,http.cors.allow-methods
用于指定允许的HTTP方法,http.cors.allow-headers
用于指定允许的HTTP头。bin/elasticsearch
import axios from 'axios';
const elasticsearchUrl = 'http://localhost:9200';
const searchDocuments = async (indexName, query) => {
try {
const response = await axios.get(`${elasticsearchUrl}/${indexName}/_search`, {
params: {
q: query
}
});
return response.data.hits.hits;
} catch (error) {
console.error('Error searching documents:', error);
return [];
}
};
// 示例调用
searchDocuments('my-index', 'example').then(documents => {
console.log('Documents:', documents);
});
通过以上配置,前端应用可以顺利连接到Elasticsearch,实现数据的查询和操作。跨域配置是前后端分离架构中不可或缺的一部分,正确配置跨域可以确保应用的正常运行和数据的安全传输。
本文详细介绍了如何在SpringBoot项目中集成Elasticsearch(ES),并进行了基本的操作。首先,我们通过添加依赖和配置文件,成功搭建了SpringBoot与Elasticsearch的环境。接着,我们学习了Linux基础命令,掌握了文件编辑和系统管理的基本技能。随后,我们详细讲解了如何使用Elasticsearch进行索引的创建、删除、更新和文档的增删改查等操作。特别值得一提的是,高亮显示功能在ES7.9.x版本中得到了增强,但在7.7版本中可能会出现报错,因此建议使用7.9.x或更高版本。
为了提高操作的便捷性和效率,我们推荐使用es-head和Kibana这两个图形化工具。es-head提供了直观的界面,使得索引管理和文档操作更加简单;而Kibana不仅支持索引管理和文档操作,还提供了丰富的可视化功能,使得数据分析和管理更加直观和高效。
最后,我们讨论了在前后端分离的架构中,如何进行跨域配置,确保前端应用能够顺利连接到Elasticsearch。通过修改Elasticsearch的配置文件并重启服务,可以实现跨域访问,确保数据的正常传输和应用的稳定运行。
希望本文的内容对您的项目有所帮助,使您能够在SpringBoot项目中更高效地使用Elasticsearch。