이 글은 Java의 강력한 Elastisearch검색 엔진의 예제 코드를 주로 소개합니다. 관심 있는 사람은 이에 대해 알아볼 수 있습니다.
Elastisearch는 매우 강력하고 쉽습니다. -엔진을 사용합니다. 검색index엔진
을 사용하여 시스템에서 Elastisearch를 실행하려면 다음 단계만 필요합니다
1. Elastisearch 다운로드.
코드는 다음과 같습니다.wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.4.0.zip2.
unzip elasticsearch-5.4.0.zip를 압축 해제합니다. 이때
elasticsearch-5.4.0/bin/elasticsearch를 실행합니다. 오버플로(OOM)로 인해 elastisearch는 매우 많은 양의 메모리를 차지하므로 상대적으로 메모리가 적은 서버에서 실행하는 경우 먼저 jvm의 메모리 크기를 수정해야 합니다
vi elasticsearch-5.4.0/config/jvm.options라인의 스택 크기를 변경합니다. 22와 23을 512M
-Xms512M -Xmx512M다시 시작해도 계속 종료되면 다시 시도하세요.4. 테스트 성공 여부
curl 'http://localhost:9200/?pretty'할 수 있습니다. 다음 반환 정보를 참조하세요.
{ "status": 200, "name": "Shrunken Bones", "version": { "number": "1.4.0", "lucene_version": "4.10" }, "tagline": "You Know, for Search" }시작이 성공했음을 의미합니다
Connect 다음으로 Java의 API를 사용하여 Elasticsearch를 작동합니다
먼저 elastisearch 및 log4j 패키지를 가져옵니다. POM<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jk</groupId> <artifactId>ElasticsearchExample</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <!--用哪个版本就填什么--> <version>5.4.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.7</version> </dependency> </dependencies> </project>다음은 일반적으로 사용되는 여러 작업
1 클라이언트 생성
Client client = null; try { client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); } catch (Exception e) { e.printStackTrace(); }
2. 인덱스 생성
/** * 创建索引,有则先删除 * @param client */ private static void recreateIndex(Client client) { if (client.admin().indices().prepareExists(index).execute().actionGet() .isExists()) { DeleteIndexResponse deleteIndexResponse = client.admin().indices() .delete(new DeleteIndexRequest(index)).actionGet(); System.out.println("delete index :"); System.out.println(deleteIndexResponse); } CreateIndexResponse createIndexResponse = client.admin().indices() .prepareCreate(index).execute().actionGet(); System.out.println("create index :"); System.out.println(createIndexResponse); }
/** * 插入数据 * @param client */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void doIndex(final Client client) { Map s11 = new LinkedHashMap(); s11.put("title", "Think in java"); s11.put("origin", "美国"); s11.put("description", "初级java开发人员必读的书"); s11.put("author", "Bruce Eckel"); s11.put("price", 108); Map s12 = new LinkedHashMap(); s12.put("title", "Head First Java"); s12.put("origin", "英国"); s12.put("description", "java入门教材"); s12.put("author", "Kathy Sierra"); s12.put("price", 54); Map s21 = new LinkedHashMap(); s21.put("title", "Design Pattern"); s21.put("origin", "法国"); s21.put("description", "程序员不得不读的设计模式"); s21.put("author", "Kathy Sierra"); s21.put("price", 89); Map s22 = new LinkedHashMap(); s22.put("title", "黑客与画家"); s22.put("origin", "法国"); s22.put("description", "读完之后脑洞大开"); s22.put("author", "Paul Graham"); s22.put("price", 35); BulkResponse bulkResponse = client .prepareBulk() .add(client.prepareIndex(index, type).setId("11").setSource(s11).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("12").setSource(s12).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("21").setSource(s21).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("22").setSource(s22).setOpType(IndexRequest.OpType.INDEX).request()) .execute().actionGet(); if (bulkResponse.hasFailures()) { System.err.println("index docs ERROR:" + bulkResponse.buildFailureMessage()); } else { System.out.println("index docs SUCCESS:"); System.out.println(bulkResponse); } }
4. 쿼리전체
/** * 查询所有 */ private static void searchAll(Client client) { SearchResponse response = client.prepareSearch(index) .setQuery(QueryBuilders.matchAllQuery()) .setExplain(true).execute().actionGet(); System.out.println("searchAll : "); for (SearchHit searchHit : response.getHits()) { System.out.println("********"); System.out.println(searchHit.getSource()); } }
5. 키워드 쿼리
/** * 关键词查询 * * @param client */ private static void searchKeyWord(Client client) { SearchResponse response = client.prepareSearch(index) //查询所有字段匹配关键字 .setQuery(QueryBuilders.matchQuery("_all", "法国")) //设置最小匹配程度 // .setQuery(QueryBuilders.matchQuery("_all", "法国").minimumShouldMatch("100%")) .execute().actionGet(); System.out.println("searchKeyWord : "); System.out.println(response); }
6. 숫자 범위 필터링
/** * 数值范围过滤 * * @param client */ private static void searchRange(Client client) { SearchResponse response = client.prepareSearch(index). //大于80,小于100 setQuery(QueryBuilders.rangeQuery("price").gt(80).lt(100)) .execute() .actionGet(); System.out.println("searchRange : "); System.out.println(response); }
7. 정렬
/** * 排序 * * @param client */ private static void searchOrdered(Client client) { SearchResponse response = client.prepareSearch(index) .setQuery(QueryBuilders.matchAllQuery()) //根据价格降序排序 .addSort(SortBuilders.fieldSort("price") .order(SortOrder.DESC)).execute().actionGet(); System.out.println("searchOrdered : "); System.out.println(response); }
8. 키워드 강조
/** * 高亮关键字 * @param client */ private static void searchHightlight(Client client) { //高亮多个字段 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("title"); highlightBuilder.field("description"); SearchResponse response = client.prepareSearch(index) //单条件匹配,高亮时只能高亮该字段 // .setQuery(QueryBuilders.matchQuery("title", "java")) //多条件匹配,高亮时只能高亮多个字段 .setQuery(QueryBuilders.multiMatchQuery("开发人员必读", "title", "description")) .highlighter(highlightBuilder) .execute() .actionGet(); System.out.println("searchHightlight : "); System.out.println(response); }
검색 🎜>
10. 삭제 /**
* 根据id查找
* @param client
*/
private static void findById(final Client client) {
String id="12";
GetResponse response = client.prepareGet(index, type, id).get();
System.out.println("findById");
System.out.println(response);
}
업데이트 /**
* 删除
* @param client
*/
private static void deleteById(Client client) {
String id="12";
DeleteResponse response = client.prepareDelete(index, type, id).get();
}
위 내용은 Java에서 강력한 Elastisearch 검색 엔진을 사용하기 위한 예제 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사에서는 분산 응용 프로그램을 구축하기위한 Java의 원격 메소드 호출 (RMI)에 대해 설명합니다. 인터페이스 정의, 구현, 레지스트리 설정 및 클라이언트 측 호출을 자세히 설명하여 네트워크 문제 및 보안과 같은 문제를 해결합니다.

이 기사는 네트워크 통신을위한 Java의 소켓 API, 클라이언트 서버 설정, 데이터 처리 및 리소스 관리, 오류 처리 및 보안과 같은 중요한 고려 사항에 대해 자세히 설명합니다. 또한 성능 최적화 기술, i

이 기사에서는 맞춤형 Java 네트워킹 프로토콜을 작성합니다. 프로토콜 정의 (데이터 구조, 프레임, 오류 처리, 버전화), 구현 (소켓 사용), 데이터 직렬화 및 모범 사례 (효율성, 보안, Mainta를 포함합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
