실험 환경
우선, Elasticsearch 환경을 설치해야합니다. 데이터를 직관적으로 볼 수 있도록 Visual Plug-In Elasticsearch-Head를 설치하는 것이 가장 좋습니다.
물론이 부분에서 내 게시물을 참조 할 수 있습니다.
내 ES는 http://113.209.119.170:9200/에 설치되어 있습니다 (이 주소는 Springboot 프로젝트에 할당되어야합니다)
봄 프로젝트 제작
이 부분에 대한 특별한 설명은 없지만 조심해야 할 몇 가지가 있습니다.
새 프로젝트를 만들 때 웹 및 NOSQL에서 Elasticsearch 종속성을 확인하고 그림을 찍어 다음을 설명해주십시오.
프로젝트를 만들 때 NOSQL에서 ES 종속성 옵션을 확인하십시오.
프로젝트가 자동으로 생성되면 Spring-Boot-Starter-Data-Elasticsearch의 종속성이 Pom.xml에 자동으로 추가됩니다.
<pectionency> <groupid> org.springframework.boot </groupid> <artifactid> 스프링 부트 스타터-데이터-엘라 스타 틱 검색 </artifactid> </dependency>
이 프로젝트에서는 오픈 소스 RESTFUL ES Java Client Jest를 사용하므로 POM.xml에 Jest 의존성을 추가해야합니다.
<pectionency> <groupid> io.searchbox </groupid> <artifactid> jest </artifactid> </fectionency>
또한 JNA 종속성을 추가해야합니다.
<pectionency> <groupid> net.java.dev.jna </groupid> <artifactid> jna </artifactid> </fectionency>
그렇지 않으면, 스프링 프로젝트를 시작할 때 JNA의 오류는 찾을 수 없습니다. 기본 방법은 비활성화됩니다. :
JNA를 찾을 수 없습니다. 기본 방법은 비활성화됩니다.
ES 서버 주소는 프로젝트 구성 파일 application.yml에서 구성해야합니다.
서버 : 포트 : 6325Spring : Elasticsearch : Jest : Uris : -http://113.209.119.170:9200 # ES 서버 주소! 읽기 시간 : 5000
코드 조직
내 프로젝트 코드는 다음과 같이 구성됩니다.
프로젝트 코드 조직
코드의 각 부분은 다음과 같이 설명되며 주석은 다음과 같습니다.
Entity.java
패키지 com.hansonwang99.springboot_es_demo.entity; import java.io.serializable; import org.springframework.data.elasticsearch.annotations.document; public class emplements serializable {private static long serialversionuid = -76338353551774166L; 공개 정적 최종 문자열 index_name = "index_entity"; 공개 정적 최종 문자열 유형 = "tstype"; 개인 긴 ID; 개인 문자열 이름; 공공 기관 () {super (); } 공공 기관 (long id, 문자열 이름) {this.id = id; this.name = 이름; } public long getId () {return id; } public void setId (long id) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; }} testservice.java
패키지 com.hansonwang99.springboot_es_demo.service; import com.hansonwang99.springboot_es_demo.entity; import java.util.list; public interface readservice {void saventity (entity entity); void saveentity (list <entity> entityList); List <entity> searchentity (String SearchContent);}testserviceimpl.java
패키지 com.hansonwang99.springboot_es_demo.service.mpl; import java.io.ioexception; import java.util.list; import com.hansonwang99.springboot_es_demo.entity.entity; import com.hansonwang99.springboot_es_demo.servere.tervere.tervere.tervice.tervice.tervice.tervice org.elasticsearch.dex.query.querybuilders; import org.elasticsearch.search.search.builder.searchsourcebuilder; import org.slf4j.logger; import org.slf4j.logger Afficory; import org.springframework.beans.antofation.antowier; org.springframework.stereotype.Service;import io.searchbox.client.JestClient;import io.searchbox.client.JestResult;import io.searchbox.core.Bulk;import io.searchbox.core.Index;import io.searchbox.core.Search;@Servicepublic class TestServiceImpl implements TestService { private static 최종 로거 로거 = loggerfactory.getLogger (testserviceimpl.class); @autowired 개인 Jestclient Jestclient; @override public void saventity (entity entity) {index index = new index.builder (entity) .index (entity.index_name) .type (entity.type) .build (); try {jestclient.execute (index); logger.info ( "es insert complete"); } catch (ioexception e) {e.printstacktrace (); logger.error (e.getMessage ()); }} / ** * 배치로 컨텐츠 저장 es * / @override public void saveentity (list <entity> entityList) {bulk.builder bulk = new Bulk.Builder (); for (entity entity : entityList) {index index = new index.Builder (entity) .index (entity.index_name) .type (entity.type) .build (); BULK.ADDACTION (색인); } try {jestclient.execute (bulk.build ()); logger.info ( "es insert complete"); } catch (ioexception e) {e.printstacktrace (); logger.error (e.getMessage ()); }} / *** es* / @override public list <entity> searchEntity (String SearchContent) {SearchSourceBuilder SearchSourceBuilder = new SearchSourceBuilder (); //searchSourceBuilder.query(QueryBuilders.queryStringQuery(searchContent)); //searchSourceBuilder.field("name "); SearchSourceBuilder.query (QueryBuilders.matchQuery ( "name", searchContent)); Search = new Search.Builder (SearchSourceBuilder.toString ()) .addindex (entity.index_name) .addtype (entity.type) .build (); try {jestresult result = jestclient.execute (검색); return result.getSourceAsObjectList (entity.class); } catch (ioException e) {logger.error (e.getMessage ()); e.printstacktrace (); } return null; }} EntityController.java
패키지 com.hansonwang99.springboot_es_demo.controller; import java.util.arraylist; import java.util.list; import com.hansonwang99.springboot_es_demo.entity; import com.hansonwang99.springboot_es_demo.service org.apache.commons.lang.stringutils; import org.springframework.beans.beans.annotation.autowired; import org.springframework.web.bind.annotation.requestmapping; import org.spramework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.restcontroller;@restcontroller@restontroller@restontmapping ( "/entitycontroller") 공개 클래스 엔티티 콘트롤러 {@autowired tredservice cityesservice; @requestmapping (value = "/save", method = requestmethod.get) public string (long id, string name) {System.out.println ( "Save Interface"); if (id> 0 && stringutils.isnotempty (name)) {Entity newentity = 새 엔티티 (id, name); List <entity> addList = new ArrayList <Entity> (); addlist.add (newentity); cityesservice.saveentity (addlist); "OK"를 반환합니다. } else {return "나쁜 입력 값"; }} @requestmapping (value = "/search", method = requestmethod.get) 공개 목록 <Entity> 저장 (문자열 이름) {list <entity> entityList = null; if (stringUtils.isnotempty (name)) {entityList = CityEsService.searchentity (name); } return entityList; }}실제 실험
여러 데이터를 추가하려면 Postman 도구를 사용하거나 다음 5 가지 데이터 추가와 같은 브라우저에서 직접 입력 할 수 있습니다.
http : // localhost : 6325/entitycontroller/save? id = 1 & name = nanjing sun yat-sen mausoleum http : // localhost : 6325/entitycontroller/save? id = 2 & nanjing normal University http : // localhost : 6325/enditytroller/save/save/save/save/save/save/save. 공자 사원 http : // localhost : 6325/entityController/Save? id = 4 & name = hangzhou는 또한 매우 좋은 http : // localhost : 6325/entitycontroller/save? id = 5 & name = 중국 남부에 Jing이라는 도시가없는 것 같습니다.
데이터 삽입 효과는 다음과 같습니다 (시각적 플러그인 Elasticsearch-Head 사용) :
데이터 삽입 효과
검색 테스트를하자 : 예를 들어, "Nanjing"키워드를 검색하고 싶습니다.
브라우저를 입력합니다.
http : // localhost : 6325/entitycontroller/search? name = nanjing
검색 결과는 다음과 같습니다.
키워드 "난징"에 대한 검색 결과
방금 삽입 된 키워드 "Nanjing"이 포함 된 4 개의 레코드가 모두 검색되었습니다!
물론 표준 단어 세분화 방법은 여기에서 사용되며 각 중국어는 용어로 사용됩니다. 키워드 "South"및 "Beijing"이 포함 된 모든 레코드가 검색되었지만 점수는 다릅니다. 물론 다른 단어 세분화 방법이 있습니다. 현재 다른 단어 세분화 플러그인의 지원이 필요합니다. 이것은 여기에서 다루지 않았으며 나중에 탐구하겠습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.