elasticsearch 색인 생 성 및 데이터 검색
3787 단어 elasticsearch
우 리 는 elasticsearch 를 데이터베이스 로 이해 할 수 있다.
json 문서 만 들 기
elasticsearch 는 json document 을 만 드 는 여러 가지 방식 이 있 습 니 다.
1. 손 글씨, 예 를 들 면
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
2. map 사용
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");
3. 직렬 화 bean
For example,use jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.3</version>
</dependency>
그리고 우 리 는 jackson 을 사용 하여 우리 의 bean 을 서열 화 할 수 있다.
import com.fasterxml.jackson.databind.*;
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
String json = mapper.writeValueAsString(yourbeaninstance);
4. elasticsearch 도움말 클래스 사용 하기
Elasticsearch 는 JSON 을 만 들 기 위해 도움말 클래스 를 제공 합 니 다.
import static org.elasticsearch.common.xcontent.XContentFactory.*;
XContentBuilder builder = jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
색인 생 성
예 를 들 어 색인 이름 은 blog 이 고 type 은 post 이 며 id 는 1 입 니 다.
IndexResponse response = client.prepareIndex("blog", "post", "1")
.setSource(XContentFactory.jsonBuilder().startObject()
.field("title", "test")
.field("content", "here is content")
.field("tag", "test")
.endObject()
).execute().actionGet();
만약 에 우리 가 id 를 지정 하지 않 으 면 ES 는 우리 에 게 id 를 생 성 해 줄 것 입 니 다. setSource 방법 은 몇 가지 형식 이 있 습 니 다. json 문자열, map 등 을 전송 할 수 있 습 니 다. 차이 가 많 지 않 은 것 은 위 에서 지적 한 몇 가지 형식 IndexResponse 가 정 보 를 되 돌려 주 는 것 입 니 다.
// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
//
boolean isCreated = response.isCreated()
기록 하 나 를 검색 하 다
색인 을 만 들 때 저 희 는 IndexResponse 에 따라 index, type, id 를 얻 었 습 니 다. 기록 을 검색 하 는 방법 은 매우 간단 합 니 다. index, type, id 의 색인 이 존재 하 는 지 판단 할 수 있 습 니 다.
GetResponse getResponse = client.prepareGet("blog", "post","1")
.execute()
.actionGet();
GetResponse 에서 자주 사용 하 는 방법 은 isExists (), getSourceAsString () 등 이 있 습 니 다. 전 자 는 지정 한 색인 이 존재 하 는 지 여 부 를 판단 하고 나중에 되 돌아 오 는 json 을 판단 합 니 다.우 리 는 제 이 슨 의 반 직렬 화 에 따라 우리 가 원 하 는 대상 을 얻 을 수 있다.
Post post = mapper.readValue(getResponse.getSourceAsString(),Post.class);
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
App Search의 본문 파싱(저를 포함하여) 일부 사람들이 Swifttype 사이트 검색에서 놓친 기능은 CSS 선택기를 사용하여 콘텐츠를 구문 분석할 수 있다는 것입니다. App Search 크롤러는 지정한 웹사이트에서 모든 콘텐츠를 추출하...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.