ElasticSearch 초기 탐색 의 모든 초기 사용 기록(7)부분 자바 api+사용 정지 단어+동의어
curl -s -XPOST http://172.22.112.1:9200/_bulk --data-binary @elasticsearch.txt -S:오류 표시,-s 침묵 모드[데 이 터 를 업로드 할 때 중간 kill,일부 업로드 에 성공 하지 않 고 모두 실패 합 니 다]
3.단어 구분 기 를 설정 하기 전에 ES 는 한 자 를 한 개 로 나 눕 니 다(Elasticsearch 를 설치 한 후에 기본적으로'standard'라 는 단어 가 포함 되 어 있 습 니 다.중국어 에 대한 지원 이 약 합 니 다).예 를 들 어 검색:
http://172.22.112.1:9200/listing_new/listing/_search?q=category_이름:바닷물,GET/listingnew/listing/_search?q=category_name:%E6%B5%B7%E6%B0%B4
'해산물 수산'이 나 올 것 이 고 우 리 는'바닷물'이라는 두 글자 가 분리 되 지 않 기 를 바 랄 것 이다.분사 기 설치:
.\elasticsearch-plugin.bat install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.8/ela sticsearch-analysis-ik-5.6.8.zip ES 다시 시작 하기;자동 으로 생 성 되 는 색인 을 삭제 합 니 다:
DELETE /listing_new index 를 만 들 기 전에 새 mapping-기본all 이 열 렸 습 니 다(즉,필드 를 지정 하지 않 았 을 때 사용 하지 않 은 모든 것 을 검색 합 니 다all 매개 변수의 필드),통과"all":{"enabled":false}을 사용 하지 않 습 니 다.
4.567917.자동 으로 색인 을 만 드 는 것 을 금지 하려 면 config/elasticsearch.yml 의 모든 노드 에 아래 설정 을 추가 할 수 있 습 니 다.4.567914.4.567918.
lucen 에서:
4.567917.analyzer-분석 기,여기 ik 분사 기 는 ik-smart 모드 와 ik-max 가 있 습 니 다.워드 두 가지 모델 은 전 자 는 굵 은 입자 의 구분 이 고 후 자 는 가 는 입자 이다.굵 은 입도 도 정확도 가 높다 는 뜻 이지 만 굵 은 입도 구분 으로 검색 결과 가 적어 리 콜 율 이 낮다.필드 에 분석 기(Lucen 의 Index.ANALYZED 에 대응 하 는)를 지정 하면'분할'되 고 역 색인 에 저 장 됩 니 다.지정 하지 않 으 면 Lucen 의 Index.NOTANALYZED,어떤 단어 조작 도 하지 않 고 후진 색인 을 직접 저장 하기 때문에 핸드폰 번호,URL 등 유형의 데이터(지 정 된 필드 를 키워드 로 할 수도 있 음)]
## mapping,ik
PUT /listing_new
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 0,
"analysis": {
"analyzer": {
"ik": {
"tokenizer": "ik_smart"
}
}
}
},
"mappings": {
"listing": {
"dynamic": true,
"properties": {
"listing_title": {
"type": "text",
"analyzer": "ik"
},
"category_name": {
"type": "text",
"analyzer": "ik"
},
"listing_id": {
"type": "long"
},
"category_id": {
"type": "long"
}
}
}
}
} 오류 보고:
action.auto_create_index: false분사 기 를 설치 한 후 클 러 스 터 를 다시 시작 해 야 합 니 다.index.analysis.analysis.analyser.ik.type:"ik"을 설정 할 필요 가 없습니다.재 실행 조회:
"Custom Analyzer [ik] failed to find tokenizer under name [ik_smart]"명중 없 음 을 볼 수 있 습 니 다.4.567917.자연 언어 처리 에서 보통'정용 어'와'동의어'를 설정 해 야 한다.
http://172.22.112.1:9200/listing_new/listing/_search?q=category_name: 텍스트 필드(text)에 대해 서 는 기본적으로 fielddata 기능 이 닫 혀 있 습 니 다.[categoryname]에 fielddata=true 를 설정 하여 메모리 에 있 는 fielddata 를 다시 반전 시 킬 수 있 습 니 다.이것 은 대량의 메모 리 를 소모 할 수 있 으 니 주의 하 세 요.또는 키워드 필드 로 대체 합 니 다.【text 필드 는 기본적으로 fielddata 를 열지 않 습 니 다.ES 는 키워드 필드 를 단어 로 나 누고 색인 으로 거꾸로 배열 하기 때문에 text 를 취 합 할 때 먼저 mapping 에서 fielddata 를 ture 로 설정 한 다음 에 거꾸로 배열 색인 을 문서 id 와 단어의 관 계 를 반전 시 켜 야 합 니 다.]Solr synonyms 의 형식 1.기호=>지정 을 사용 합 니 다.예 를 들 어 잘못 쓰기 쉬 운 단어:느슨 함=>느슨 함 ture=>true 2.쉼표 로 구 분 된 목록 입 니 다.
4.567914.예 를 들 어 우리 의 문서 에'중국'이라는 두 글자 가 있 는데 우 리 는 할 수 있다.
중국,중화,중국,중화 인민공화국
이렇게 되면'중국,중화,중국,중화 인명 공화국'은 모두'중국'과 일치 할 것 이다.
MORE:https://examples.javacodegeeks.com/enterprise-java/apache-solr/apache-solr-synonyms-example/
새로운 mapping
PUT /listing_new
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 0,
"analysis": {
"analyzer": {
"ik_synonym": {
"tokenizer": "ik_smart",
"filter": ["synonym"]
}
},
"filter": {
"synonym": {
"type": "synonym",
"synonyms_path": "analysis/synonym_listing.txt"
}
}
}
},
"mappings": {
"listing": {
"dynamic": true,
"properties": {
"listing_title": {
"type": "text",
"analyzer": "ik_synonym"
},
"category_name": {
"type": "text",
"analyzer": "ik_synonym",
"fielddata": true
},
"listing_id": {
"type": "long"
},
"category_id": {
"type": "long"
}
}
}
}
} "caused_by": { "type": "malformed_input_exception", "reason": "Input length = 1" 4.567917.Junit 4 테스트 를 사용 하면 4.567918 도 참고 할 수 있 습 니 다.
ES 의 자바 Api 들
클 라 이언 트 닫 기 만 들 기
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
/**
* Descirption: Elastic
*
* @author
* @version V1.0
* @package PACKAGE_NAME
* @date 2018/5/18 14:55
* @since api1.0
*/
public class OpenClose {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenClose.class);
TransportClient client = null;
/**
* Map
*
* @param mapParms Map
*/
public TransportClient getClientWithMap(Map mapParms) {
// client ip , ,
//
String clusterName = mapParms.get("cluster.name").toString();
// ip
//String addressMaster = mapParms.get("server").toString();
byte[] addressMaster = (byte[]) mapParms.get("server");
// (ES 9300)
int transport = (int) mapParms.get("port");
// , elasticsearch
// Builder Settings
Settings settings = Settings.builder().put("cluster.name", clusterName).build();
try {
//client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(addressMaster), transport));
client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByAddress(addressMaster), transport));
} catch (UnknownHostException e) {
e.printStackTrace();
LOGGER.error(" client ===== " + e.getMessage());
}
LOGGER.info(" client ===== " + System.currentTimeMillis());
return client;
}
public void closeClient(TransportClient client) {
if (client != null) {
client.close();
client = null;
LOGGER.info(" client ===== " + System.currentTimeMillis());
}
}
}
단순 검색,MultiMatchQuery/bool
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import java.util.Map;
/**
* Descirption: bool
*
* @author
* @version V1.0
* @since 2018/5/18 22:23
*/
public class BaseAndBool {
public static String query(Map queryParams, TransportClient esClient) {
//검색 어
String queryWords = queryParams.get("query").toString();
//검색 모드
String queryMode = queryParams.get("mode").toString();
//검색 필드
String[] queryFields = (String[]) queryParams.get("fields");
// index
String index = queryParams.get("index").toString();
// type
String type = queryParams.get("type").toString();
int from = (int) queryParams.get("from");
int size = (int) queryParams.get("size");
// org.elasticsearch.index.query.QueryBuilder
QueryBuilder queryBuilder = null;
if ("MultiMatchQuery".equalsIgnoreCase(queryMode)) {
//기본 검색,기본 사용 OR
queryBuilder = QueryBuilders.multiMatchQuery(queryWords, queryFields);
} else {
//bool 조회 사용,must\should\must Not 등 사용 가능
String[] terms = queryWords.split("\\s+");
for (String term : terms) {
if (queryBuilder == null) {
queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.multiMatchQuery(term, queryFields));
} else {
queryBuilder = QueryBuilders.boolQuery().must(queryBuilder).must(QueryBuilders.multiMatchQuery(term, queryFields));
}
}
}
//Query Builders 구축 이 완료 되 었 습 니 다.아래 가 진정한 조 회 를 수행 하 는 곳 입 니 다.
SearchResponse searchResponse = null;
//get()을 실행 하기 전에 돌아 오 는 것 은 모두 SearchRequestBuilder 대상 이 고,SearchType.DEPAULT 는 QUERY 입 니 다.THEN_FETCH
//setTypes 를 설정 하지 않 으 면 기본 index 의 모든 type
searchResponse = esClient.prepareSearch(index).setTypes(type).setSearchType(SearchType.DEFAULT).setQuery(queryBuilder).setFrom(from).setSize(size).get();
return searchResponse.toString();
}
}
테스트import org.elasticsearch.client.transport.TransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* BaseAndBool Tester.
*
* @author
* @version 1.0
* @since 05/18/2018
*/
public class BaseAndBoolTest {
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
/**
* Method: query(Map queryParams, TransportClient esClient)
*테스트 조회 방법
*/
@Test
public void testQuery() throws Exception {
//클 라 이언 트 만 들 기
OpenClose openClose = new OpenClose();
Map hashMap = new HashMap<>();
hashMap.put("cluster.name", "elasticsearch-win");
hashMap.put("server", new byte[]{(byte) 172, (byte) 22, (byte) 112, 1});
hashMap.put("port", 9300);
TransportClient client = openClose.getClientWithMap(hashMap);
//조회 체 만 들 기
Map queryParams = new HashMap<>();
queryParams.put("index", "listing_new");
queryParams.put("type", "listing");
queryParams.put("query","데 프 라면");
queryParams.put("fields", new String[]{"listing_title","category_name"});
queryParams.put("from", 1);
queryParams.put("size", 10);
//
queryParams.put("mode", "MultiMatchQuery");
String result_multi = BaseAndBool.query(queryParams, client);
System.out.println(result_multi);
// bool
queryParams.put("mode", "bool");
String result_bool = BaseAndBool.query(queryParams, client);
System.out.println(result_bool);
//연결 닫 기
openClose.closeClient(client);
}
}
부분 반환 결과:
{“took”:5,”timed_out”:false,”_shards”:{“total”:3,”successful”:3,”skipped”:0,”failed”:0},”hits”:{“total”:1528,”max_score”:7.5759635,”hits”:[{“_index”:”listing_new”,”_type”:”listing”,”_id”:”AWNxycq8SnQysQYb0_Zd”,”_score”:7.564964,”_source”:{ “listing_id” : “7132”, “listing_title":"데 프 진 한 다 크 초콜릿 66 80 g 간식 데 프 초콜릿","categoryid” : “6”, “category_name":"초콜릿"},{"index”:”listing_new”,”_type”:”listing”,”_id”:”AWNxycq8SnQysQYb0_Zb”,”_score”:7.4578214,”_source”:{ “listing_id” : “7130”, “listing_title":"데 프 초콜릿 간식 290.5g 그릇","categoryid” : “6”, “category_name":"초콜릿"}}}}bool{"took":4,"timed 사용 하기out”:false,”_shards”:{“total”:3,”successful”:3,”skipped”:0,”failed”:0},”hits”:{“total”:0,”max_score”:null,”hits”:[]}}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ELK 스택 구축ElasticSearch, LogStash, Kibana 조합으로 로그 수집 - 로그 저장 및 검색 - 시각화로 쓰이게 된다. Logstash는 실시간 파이프라인 기능을 갖는 데이터 수집 엔지이며, Input을 받아...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.