Article directory
1. Install Elasticsearch related plug-ins
1. Select version
In order to avoid problems caused by inconsistencies between the Elasticsearch version used and the version used by SpringBoot, try to use a consistent version. The following table is the corresponding relationship:
My SpringBoot version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.15</version>
<relativePath />
</parent>
Therefore, the corresponding Elasticsearch version is selected as 7.12.0.
2. Install Elasticsearch
Download various versions of Elasticsearch
Download Elasticsearch7.12.0 official website
- Download the installation package linked above
- Unzip to any directory
- Start es /bin/elasticsearch.bat
- To check the installation results, enter localhost:9200 on the web page. If the following picture appears, it means success.
There may be a problem at this time. It can be accessed using localhost but cannot be accessed using IP
You need to modify /config/elasticsearch.yml in the Elasticsearch installation directory, which is on line 58 Add the following settings
network.bind_host: 0.0.0.0
After the addition is completed, restart the es service, a crash problem may occur
If the problem is: bootstrap check failure [1] of [1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured
You need to put about 77 in /config/elasticsearch.yml in the Elasticsearch installation directory row position
#cluster.initial_master_nodes: ["node-1", "node-2"]
Release the annotation and change it to
cluster.initial_master_nodes: ["node-1"]
3.Install node
es5 and above require the installation of node and grunt, so the prerequisite for installing the head plug-in is that these two items need to be configured.
node download addressDownload the node version corresponding to the environment and install it.
After the installation process is completed, check whether the installation is successful in the DOS window. Use the command: node -v. If the following screenshot appears, the installation is successful.
4.Install grunt
In the node installation path, use the command to install: npm install -g grunt-cli to install grunt. After the installation is completed, use the command grunt
-version to check whether the installation is successful. The following screenshot appears, indicating that the installation is successful.
5. Install the es-head plug-in
Conveniently view indexes and data in ES
Unzip elasticsearch-head-master
Enter the cmd command in this directory and executenpm install
Run the command after completiongrunt server,
grunt server is the startup command< a i=4> If an error occurs
Use cmd to continue executionnpm install grunt --save-dev. This will add the latest version to package.json.
If no error is reported, the command window displays
Browser input 127.0.0.1:9100
In fact, it is not possible to connect to elasticsearch here, and cross-domain problems need to be solved
Since the front-end and back-end are developed separately, there will be cross-domain problems, and CORS needs to be configured on the server side.
Modify /config/elasticsearch.yml in the Elasticsearch installation directory and add the following settings
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-credentials: true
http.cors.allow-headers: Content-Type,Accept,Authorization,x-requested-with
#http.cors.allow-headers: "*"
Restart the ES service
6.Install kibana
Purpose: To facilitate debugging ES through rest api.
kibana official 7.12.0 download address
kibana Chinese community download address
- Unzip
- Modified kibana-7.12.0-windows-x86_64/config/kibana.yml 32 lines
- Change to elasticsearch.hosts: ["http://127.0.0.1:9200"]
- After saving, run bin/kibana.bat
- Visit kibana homepage in browserHomepage link
Direct access to development tools:Development Tools
If you want to use IP to access kibana, you need to modify itkibana-7.12.0-windows-x86_64/config/kibana.yml 7 lines< /span> i18n.locale: “zh-CN” Last linekibana-7.12.0- windows-x86_64/config/kibana.yml If you want to use kibana Chinese version, you need to modify it
Change to server.host: “0.0.0.0”
7. Install ik word segmenter
Note: The downloaded ik word segmenter version number must be consistent with the installed elasticsearch version
Unzip the downloaded ik word segmenter to the Elasticsearch installation directory/plugins/ik.
- Test ik word segmenter
- Restart elasticsearch
- Restart kibana
- Enter kibana’s development tool to execute command testing Development tool
- Execute command: GET _analyze{ “analyzer”: “ik_max_word”, “text”: “Discount up or down”}
- The execution results are as follows
2. Integrate SpringBoot and Elasticearch
1.pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.15</version>
<relativePath />
</parent>
<!--springBoot2.5.15对应Elasticsearch7.12.0版本-->
<!--elasticsearch-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.12.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.application.yml
spring:
elasticsearch:
rest:
uris: 192.168.1.36:9200
connection-timeout: 1s
read-timeout: 30s
3.ElasticSearch (entity class)
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
//@Document 文档对象 (索引信息、文档类型 )
@Document(indexName="blog3")
@Data
public class ElasticSearch {
//@Id 文档主键 唯一标识
@Id
//@Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 )
@Field(store=true, index = false,type = FieldType.Integer)
private Integer id;
@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
private String title;
@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
private String content;
@Field(index=true,store=true,type = FieldType.Double)
private Double price;
}
4.ElasticSearchRepository
import com.economics.project.es.domain.ElasticSearch;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.HighlightParameters;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ElasticSearchRepository extends ElasticsearchRepository<ElasticSearch, Integer> {
/**
* 查询内容标题查询
* @param title 标题
* @param content 内容
* @return 返回关键字高亮的结果集
*/
@Highlight(
fields = {
@HighlightField(name = "title"), @HighlightField(name = "content")},
parameters = @HighlightParameters(preTags = {
"<span style='color:red'>"}, postTags = {
"</span>"}, numberOfFragments = 0)
)
List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content);
}
5.ElasticSearchService
import com.economics.project.es.domain.ElasticSearch;
import org.springframework.data.elasticsearch.core.SearchHit;
import java.util.List;
public interface ElasticSearchService {
//保存和修改
void save(ElasticSearch article);
//查询id
ElasticSearch findById(Integer id);
//删除指定ID数据
void deleteById(Integer id);
long count();
boolean existsById(Integer id);
List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content);
}
6.ElasticSearchServiceImpl
import com.economics.project.es.domain.ElasticSearch;
import com.economics.project.es.service.ElasticSearchService;
import com.economics.project.es.service.ElasticSearchRepository;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
@Resource
private ElasticSearchRepository ElasticSearchRepository;
@Override
public void save(ElasticSearch ElasticSearch) {
ElasticSearchRepository.save(ElasticSearch);
}
@Override
public ElasticSearch findById(Integer id) {
return ElasticSearchRepository.findById(id).orElse(new ElasticSearch());
}
@Override
public void deleteById(Integer id) {
ElasticSearchRepository.deleteById(id);
}
@Override
public long count() {
return ElasticSearchRepository.count();
}
@Override
public boolean existsById(Integer id) {
return ElasticSearchRepository.existsById(id);
}
@Override
public List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content) {
return ElasticSearchRepository.findByTitleOrContent(title,content);
}
}
7.EsTest
import com.economics.EconomicsApplication;
import com.economics.project.es.domain.ElasticSearch;
import com.economics.project.es.service.ElasticSearchService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EconomicsApplication.class)
public class EsTest {
@Resource
private ElasticSearchService elasticSearchService;
@Resource
private ElasticsearchRestTemplate elasticsearchRestTemplate;
/**创建索引和映射*/
@Test
public void createIndex(){
// elasticsearchTemplate.createIndex(ElasticSearch.class);
// elasticsearchTemplate.putMapping(ElasticSearch.class);
}
/**添加文档或者修改文档(以id为准)*/
@Test
public void saveElasticSearch(){
ElasticSearch elasticSearch = new ElasticSearch();
elasticSearch.setId(1);
elasticSearch.setTitle("SpringData ElasticSearch");
elasticSearch.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
" Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
elasticSearchService.save(elasticSearch);
}
@Test
public void findById(){
ElasticSearch byId = elasticSearchService.findById(1);
System.out.println(byId);
}
@Test
public void deleteById(){
elasticSearchService.deleteById(100);
}
@Test
public void count(){
long count = elasticSearchService.count();
System.out.println(count);
}
@Test
public void existsById(){
boolean b = elasticSearchService.existsById(102);
System.out.println(b);
}
@Test
public void findByTitleOrContent(){
List<SearchHit<ElasticSearch>> byTitleOrContent = elasticSearchService.findByTitleOrContent("xxxxxxSpringData","elasticSearch");
for (SearchHit<ElasticSearch> elasticSearchService : byTitleOrContent) {
List<String> title = elasticSearchService.getHighlightField("title");
System.out.println(title);
List<String> content = elasticSearchService.getHighlightField("content");
System.out.println(content);
}
}
}
8. Customized query method
Keywords | explain | method |
---|---|---|
and | Get data based on Field1 and Field2 | findByTitleAndContent(String title,String content); |
or | Get data based on Field1 or Field2 | findByTitleOrContent(String title,String content); |
is | Get data based on Field | findByTitle(String title); |
not | Get opposite data based on Field | findByTitleNot(String title) |
between | Get data in a specified range | findByPriceBetween(double price1, double price2); |
lessThanEqual | Get data less than or equal to the specified value | findByPriceLessThan(double price); |
GreaterThanEqual | Get data greater than or equal to the specified value | findByPriceGreaterThan(double price); |
Before | findByPriceBefore | |
After | findByPriceAfter | |
Like | Relatively familiar data | findByNameLike |
StartingWith | Data starting with xx | findByNameStartingWith(String Name); |
EndingWith | Data ending with xx | findByNameEndingWith(String Name); |
Contains/Containing | Data included | findByNameContaining(String Name); |
In | Multiple value matching | findByNameIn(Collectionnames) |
swimming | Multiple values do not match | findByNameNotIn(Collectionnames) |
OrderBy | Sorted data | findByxxxxxOrderByNameDesc(String xxx ); |