Elasticsearch:使用Java添加手动映射 [英] Elasticsearch: Adding manual mapping using Java

查看:142
本文介绍了Elasticsearch:使用Java添加手动映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能改变映射。有人可以帮我找到代码中的错误吗?

我已经找到这种标准的方法来根据几个教程来更改映射。但是,当我尝试调用映射结构时,在制作映射后,只出现一个空白的映射结构。

但是插入一些数据后会出现映射规范,因为ES使用的是默认映射结构。更具体地看下面的代码。

  public class ElasticTest {
private String dbname =ElasticSearch;
private String index =indextest;
private String type =table;
private Client client = null;
private Node node = null;

public ElasticTest(){
this.node = nodeBuilder()。local(true).node();
this.client = node.client();

if(isIndexExist(index)){
deleteIndex(this.client,index);
createIndex(index);
}
else {
createIndex(index);
}

System.out.println(数据插入之前的映射结构);
getMappings();
System.out.println(--------------------------------------- - );
createData();
System.out.println(数据插入后的映射结构);
getMappings();





public void getMappings(){
ClusterState clusterState = client.admin()。cluster()。prepareState )
.setFilterIndices(index).execute()。actionGet()。getState();
IndexMetaData inMetaData = clusterState.getMetaData()。index(index);
MappingMetaData metad = inMetaData.mapping(type);

if(metad!= null){
try {
String structure = metad.getSourceAsMap()。toString();
System.out.println(structure);

} catch(IOException e){
e.printStackTrace();
}
}

}

private void createIndex(String index){
XContentBuilder typemapping = buildJsonMappings();
String mappingstring = null;
try {
mappingstring = buildJsonMappings()。string();
} catch(IOException e1){
e1.printStackTrace();
}

client.admin()。indexes()。create(new CreateIndexRequest(index)
.mapping(type,typemapping))actionGet();

//创建索引后尝试放置映射
/ *
* PutMappingResponse response = null;尝试{response =
* client.admin()。indexes().preparePutMapping(index).setType(type)
* .setSource(typemapping.string()).execute()。actionGet() ; } catch
*(ElasticSearchException e){e.printStackTrace(); } catch
*(IOException e){e.printStackTrace(); }
* /

}

private void deleteIndex(客户端客户端,String索引){
try {
DeleteIndexResponse delete = client。 admin()。indexes()
.delete(new DeleteIndexRequest(index))。actionGet();
if(!delete.isAcknowledged()){
} else {
}
} catch(异常e){
}
}

private XContentBuilder buildJsonMappings(){
XContentBuilder builder = null;
try {
builder = XContentFactory.jsonBuilder();
builder.startObject()
.startObject(properties)
.startObject(ATTR1)
.field(type,string)
$($)
.field(index,resolved)
.endObject()
.endObject()
.endObject() ;
} catch(IOException e){
e.printStackTrace();
}
return builder;
}

private boolean isIndexExist(String index){
ActionFuture< IndicesExistsResponse> exists = client.admin()。indexes()
.exists(new IndicesExistsRequest(index));
IndicesExistsResponse actionGet = exists.actionGet();

return actionGet.isExists();
}

private void createData(){
System.out.println(Data creation);
IndexResponse response = null; (int i = 0; i <10; i ++)
{
Map< String,Object> json = new HashMap< String,Object>();
json.put(ATTR1,new value+ i);
response = this.client.prepareIndex(index,type)
.setSource(json)
.setOperationThreaded(false)
.execute()
.actionGet() ;
}
String _index = response.getIndex();
String _type = response.getType();
long _version = response.getVersion();
System.out.println(Index:+ _index +Type:+ _type +Version:+ _version);
System.out.println(----------------------------------);
}

public static void main(String [] args)
{
new ElasticTest();
}
}

我只想改变ATTR1字段的属性进行分析以确保快速查询。
什么im做错了?我还试图在创建索引后创建映射,但它会产生相同的影响。

解决方案

我找到了我自己的答案。在类型级别,我必须用类型名称包装属性。例如:



type1:{
properties:{
.....
}
}



请参阅以下代码:

  private XContentBuilder getMappingsByJson() 
XContentBuilder builder = null;
try {
builder = XContentFactory.jsonBuilder()。startObject()。startObject(type).startObject(properties);
(int i = 1; i <5; i ++){
builder.startObject(ATTR+ i)
.field(type,integer)
.field(store,yes)
.field(index,resolved)
.endObject();
}
builder.endObject()。endObject()。endObject();
}
catch(IOException e){
e.printStackTrace();
}
return builder;
}

它为属性ATTR1 - ATTR4创建映射。现在可以动态地为示例定义不同属性的列表的映射。希望它帮助别人。


I cant change the mapping. Can anybody help me to find the bug in my code?
I have found this standard way to change the mapping according to several tutorials. But when i'm try to call the mapping structure there just appear a blank mapping structure after manuall mapping creation.
But after inserting some data there appear the mapping specification because ES is using of course the default one. To be more specific see the code below.

public class ElasticTest {
private String dbname = "ElasticSearch";
private String index = "indextest";
private String type = "table";
private Client client = null;
private Node node = null;

public ElasticTest(){
    this.node = nodeBuilder().local(true).node();
    this.client = node.client();

    if(isIndexExist(index)){
        deleteIndex(this.client, index);
        createIndex(index);
    }
    else{
        createIndex(index);
    }

    System.out.println("mapping structure before data insertion");
    getMappings();
    System.out.println("----------------------------------------");
    createData();
    System.out.println("mapping structure after data insertion");
    getMappings();



}

public void getMappings() {
    ClusterState clusterState = client.admin().cluster().prepareState()
            .setFilterIndices(index).execute().actionGet().getState();
    IndexMetaData inMetaData = clusterState.getMetaData().index(index);
    MappingMetaData metad = inMetaData.mapping(type);

    if (metad != null) {
        try {
            String structure = metad.getSourceAsMap().toString();
            System.out.println(structure);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

private void createIndex(String index) {
    XContentBuilder typemapping = buildJsonMappings();
    String mappingstring = null;
    try {
        mappingstring = buildJsonMappings().string();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    client.admin().indices().create(new CreateIndexRequest(index)
                  .mapping(type, typemapping)).actionGet();

    //try put mapping after index creation
    /*
     * PutMappingResponse response = null; try { response =
     * client.admin().indices() .preparePutMapping(index) .setType(type)
     * .setSource(typemapping.string()) .execute().actionGet(); } catch
     * (ElasticSearchException e) { e.printStackTrace(); } catch
     * (IOException e) { e.printStackTrace(); }
     */

}

private void deleteIndex(Client client, String index) {
    try {
        DeleteIndexResponse delete = client.admin().indices()
                .delete(new DeleteIndexRequest(index)).actionGet();
        if (!delete.isAcknowledged()) {
        } else {
        }
    } catch (Exception e) {
    }
}

private XContentBuilder buildJsonMappings(){
    XContentBuilder builder = null; 
    try {
        builder = XContentFactory.jsonBuilder();
        builder.startObject()
        .startObject("properties")
            .startObject("ATTR1")
                .field("type", "string")
                .field("store", "yes")
                .field("index", "analyzed")
             .endObject()
           .endObject()
        .endObject();           
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder;
}

private boolean isIndexExist(String index) {
    ActionFuture<IndicesExistsResponse> exists = client.admin().indices()
            .exists(new IndicesExistsRequest(index));
    IndicesExistsResponse actionGet = exists.actionGet();

    return actionGet.isExists();
}

private void createData(){
    System.out.println("Data creation");
    IndexResponse response=null;
    for (int i=0;i<10;i++){
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("ATTR1", "new value" + i);
        response = this.client.prepareIndex(index, type)
                .setSource(json)
                .setOperationThreaded(false)
                .execute()
                .actionGet();
    }
    String _index = response.getIndex();
    String _type = response.getType();
    long _version = response.getVersion();
    System.out.println("Index : "+_index+"   Type : "+_type+"   Version : "+_version);
    System.out.println("----------------------------------");
}

public static void main(String[] args)
{
    new ElasticTest();
}
}

I just wanna change the property of ATTR1 field to analyzed to ensure fast queries. What im doing wrong? I also tried to create the mapping after index creation but it leads to the same affect.

解决方案

Ok i found the answer by my own. On the type level i had to wrap the "properties" with the type name. E.g:

"type1" : { "properties" : { ..... } }

See the following code:

private XContentBuilder getMappingsByJson(){
    XContentBuilder builder = null;
    try {
        builder = XContentFactory.jsonBuilder().startObject().startObject(type).startObject("properties");
        for(int i = 1; i<5; i++){
            builder.startObject("ATTR" + i)
                    .field("type", "integer")
                    .field("store", "yes")
                    .field("index", "analyzed")
                    .endObject();
            }
            builder.endObject().endObject().endObject();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    return builder;
}

It creates mappings for the attributes ATTR1 - ATTR4. Now it is possible to define mapping for Example a list of different attributes dynamically. Hope it helps someone else.

这篇关于Elasticsearch:使用Java添加手动映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆