ElastaticSearch的入门使用

1.es的概念
–es是一个基于luence的全文检索框架
–特点是操作简单、不需要繁琐的配置,支持分布式、集群,可以以JSON格式来操作,可以以restful风格来操作。
–和es类似的框架还有solr,solr是一个重量级框架,功能比es丰富一些,但是实时搜索上面比es弱一些。
2.es的安装
–es的安装,在官网下载解压即可:https://www.elastic.co/downloads/elasticsearch ,运行bin目录中的elastaticsearch.bat文件,访问路径:http://localhost:9200/ 如果有结果说明启动成功。
–es的操作软件kibana的安装,官网下载:https://www.elastic.co/downloads/kibana ,运行bin目录中的kibana.bat文件,访问路径:http://localhost:5601 。
3.es的使用
–完成基本的CRUD
通过restfull的风格,面向资源的 结合http动词操作(GET PUT POST DELETE)
新增方法:

	POST _index/_type/_id
	{
		field:value
	}
	PUT _index/_type/_id
	{
		field:value
	}

局部修改方法:

POST _index/_type/_id/_update
{
  "doc":{
      field:value
  }
}

删除操作:

DELETE  _index/_type/_id

查询操作:

GET _search
GET _index/_type/_id
#只查询source下面的数据 指定的列
GET  _index/_type/_id?_source=name,age,size
GET _index/_type/_id/_source

–批量操作
批量插入:

POST _bulk
{ "delete":{ "_index": "box", "_type": "smile", "_id": "1" }}
{ "create":{ "_index": "box", "_type": "smile", "_id": "1" }}
{ "title": "微笑" }
{ "index": { "_index": "box", "_type": "smile","_id": "2" }}
{ "title": "嘲笑" }

批量获取:

方式一:
GET _mget
{
  "docs":[{
      "_index":"box",
      "_type":"smile",
      "_id":"1"
    },{
       "_index":"box",
      "_type":"smile",
      "_id":"2",
      "_source":"title"
    }]
}
方式二:
GET box/smile/_mget
{
  "ids":["1","2"]
}

–分页查询

GET _search?size=3&from=2;

–字符串查询

GET box/smile/_search?q=name:微笑;

GET  box/smile/_search?q=age[10 TO 30]

–DSL查询,注意DSL不支持缓存

GET box/smile/_search
{
"query" : {
    "match" : {
		  "name" : "微笑"
   }
  }
}

–DSL的过滤写法
查询关键字为iphone,国家为cn的,价格范围6000到8000 价格降序,并且取前面2条:

GET shop/goods/_search
{
  "query":{
    "bool": {
      "must": [
        {"match": {
          "name": "iphone"
        }}
      ],
      "filter": [{
        "term":{
          "local":"us"
        }
      },{
        "range":{
          "price":{
            "gte":"5000",
            "lte":"7000"
          }
        }
      }]
    }
  },
  "from": 1, 
  "size": 5,      
  "_source": ["id", "name", "type","price"],
  "sort": [{"price": "desc"}]
}

–ES分词器
分词器下载地址:https://github.com/medcl/elasticsearch-analysis-ik ,下载之后,解压target/releases/elasticsearch-analysis-ik-5.2.2.zip文件,并将其内容放置于ES根目录/plugins/ik
重启ES服务器
简单使用:

POST _analyze
{
"analyzer":"ik_max_word",
"text":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"
} 

分词器动态模板

PUT _template/global_template  
{
    "template":"*",
    "settings":{
        "number_of_shards":1
    },
    "mappings":{
        "_default_":{
            "_all":{
                "enabled":false
            },
            "dynamic_templates":[ 
                {
                    "string_as_text":{
                        "match_mapping_type":"string",
                        "match":"*_text",
                        "mapping":{
                            "type":"text",
                            "analyzer":"ik_max_word",
                            "search_analyzer":"ik_max_word",
                            "fields":{
                                "raw":{
                                    "type":"keyword",
                                    "ignore_above":256
                                }
                            }
                        }
                    }
                },
                {
                    "string_as_keyword":{
                        "match_mapping_type":"string",
                        "mapping":{
                            "type":"keyword"
                        }
                    }
                }
            ]
        }
    }
}

4.JAVA中使用ES
–导包,配置pom.xml


org.elasticsearch.client
transport
5.2.2


org.apache.logging.log4j
log4j-api
2.7


org.apache.logging.log4j
log4j-core
2.7

使用代码,完成CRUD,分页和高级查询

public class EsTest {

    public static TransportClient  getClient() throws Exception {

        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).
                addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));

        return client;
    }

    //新建文档
    @Test
    public void testCreate() throws Exception{
        TransportClient client = getClient();
        IndexRequestBuilder  requestBuilder = client.prepareIndex("crm", "users", "1");
        Map map =new HashMap();
        map.put("id", "2");
        map.put("age", 18);
        map.put("name", "xiaoming");
        IndexResponse indexResponse = requestBuilder.setSource(map).get();
        System.out.println(indexResponse);
    }

    //修改文档
    @Test
    public void testUpdate() throws Exception{
        TransportClient client = getClient();
        Map map =new HashMap();
        map.put("id", "2");
        map.put("age", 28);
        map.put("name", "xiaosong");
        UpdateResponse updateResponse = client.prepareUpdate("crm", "users", "1").setDoc(map).get();
        System.out.println(updateResponse);
    }

    //删除文档
    @Test
    public void testDelete() throws Exception{
        TransportClient client = getClient();
        DeleteResponse deleteResponse = client.prepareDelete("crm", "users", "1").get();
        System.out.println(deleteResponse);
    }
    //批量操作
    @Test
    public void testBulk() throws Exception{
        //获取客户端es对象
        TransportClient client = getClient();
        //获取批量请求对象
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        //批量赋值
        for(int i=0;i<10;i++){
            Map map =new HashMap();
            map.put("id", i);
            map.put("age", 20+i);
            map.put("name", "SB"+i);
            map.put("class",1);
            bulkRequestBuilder.add(client.prepareIndex("take", "classes", i+"").setSource(map));
        }
        //提交数据
        BulkResponse bulkItemResponses = bulkRequestBuilder.get();

        if(bulkItemResponses.hasFailures()){
            System.out.println("error");
        }
        client.close();
    }

    @Test
    public void testSearch() throws Exception{
        //获取客户端es对象
        TransportClient client = getClient();
        //获得查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        List must = boolQueryBuilder.must();
        //表示搜索class为1的人
        must.add(QueryBuilders.termQuery("class", 1));
        //过滤
        List filter = boolQueryBuilder.filter();
        //条件是年龄在20到25之间
        filter.add(QueryBuilders.rangeQuery("age").gte(20).lte(25));
        //设置分页
        SearchResponse searchResponse = client.prepareSearch("take").setFrom(0)
                .setSize(3).setQuery(boolQueryBuilder).addSort("id", SortOrder.ASC).get();
        System.out.println("总条数"+searchResponse.getHits().getTotalHits());
        //循环数据结构
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSource());
        }
        client.close();
    }
}

你可能感兴趣的:(java)