Java之ES各种查询

90人浏览 / 0人评论

一、查询API用法

1.创建es的连接

public TransportClient transportClient(){
    Settings settings = Settings.builder()
            .put("cluster.name", "elasticsearch")
            .build();
    TransportClient client  = new PreBuiltTransportClient(settings);
    TransportAddress transportAddress = null;
    try {
        transportAddress = new TransportAddress(InetAddress.getByName(host), Integer.valueOf(port));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    client.addTransportAddress(transportAddress);
    return client;
}

2.java es api的添加操作

transportClient.prepareIndex("search_index", "doc").setSource(json, XContentType.JSON).get();

3.java es api的修改操作

transportClient.prepareUpdate("search_index", "doc","gug4u3EBSHOgAqyn-5aI").setSource(json, XContentType.JSON).get();

4.java es api的删除操作

transportClient.prepareDelete("search_index", "doc", "gug4u3EBSHOgAqyn-5aI").get();

5.查询QueryBuilders

BoolQueryBuilder queryBuilder= QueryBuilders.boolQuery();

matchAllQuery匹配所有

queryBuilder.matchAllQuery();

termQuery精准匹配,大小写敏感且不支持

queryBuilder.termQuery("key", value) 一次匹配一个值,完全匹配
queryBuilder.termsQuery("key", obj1, obj2..)   一次匹配多个值

matchPhraseQuery对中文精确匹配

queryBuilder.matchPhraseQuery("key", value)

matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性

queryBuilder.matchQuery(key, value);

multiMatchQuery("text", "field1", "field2"..); 匹配多个字段, field有通配符忒行

queryBuilder.multiMatchQuery(value, key1, key2, key3);

6.组合查询

   * must:   AND
   * mustNot: NOT
   * should:: OR
 queryBuilder.must(QueryBuilders.termQuery("user", "kimchy"))
            .mustNot(QueryBuilders.termQuery("message", "nihao"))
            .should(QueryBuilders.termQuery("gender", "male"));

 

二、脚本刷写数据

修改aliases文档数据中id为123456的ststus改为开启

curl -XPOST "http://localhost:9200/aliases/_update_by_query" -H 'Content-Type: application/json' -d'
{
    "script": {
        "lang": "painless",
        "source": "ctx._source[\"status\"]=[\"开启\"]"
    },
    "query": {
        "bool": {
            "must": {
                "terms": {
                    "id": [
                        "123456"
                    ]
                }
            }
        }
    }
}


三、常用命令查询

1.根据条件删除数据:

POST   ip:19200/doc/_delete_by_query

 {
        "query" : {
        "match" : { "name" : "12456" }
        }
    }

 

全部评论