-
进官网,什么操作都有,点下面
这个是es的官网可以选择各种版本去查询对应的API的操作,很全 -
因为分词查询针对的是某一个字段,所以需要指定字段的analysis 这里我使用的是es5.5.2版本
package com.ali.es.ik;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
/**
* @author zdsg
*/
//IK有两种analyzer--- ik_max_word ik_master
//需要在创建索引的时候指定
//如下api创建索引指定ik的analyzer
public class IK_Analysis {
private TransportClient client;
@Before
public void init() throws Exception{
Settings settings = Settings.builder().put("cluster.name", "bigdata").put("client.transport.sniff",true).build();
client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop111"),9300));
}
@Test
public void testCreate() throws IOException {
XContentBuilder mapping = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties")
.startObject("content").field("type", "text").field("analyzer", "ik_max_word").endObject()
.startObject("title").field("type", "text").field("analyzer", "ik_max_word").endObject()
.endObject() //第一个endObject是停止properties
.endObject(); //第二个endObject是停止XCotentBuilder
//china为索引库的名称 news为索引库的其中一个类型
PutMappingRequest putmap = Requests.putMappingRequest("china").type("news").source(mapping);
//创建索引
CreateIndexResponse response = client.admin().indices().prepareCreate("china")
.setSettings(Settings.builder()
.put("index.number_of_shards", 5) //指定分片数
.put("index.number_of_replicas", 0) //指定副本数
).get();
//为索引添加映射----将type与field添加进去
client.admin().indices().putMapping(putmap).actionGet();
}
@After
public void close() {
if(client!=null){
client.close();
}
}
}