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

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>

使用代码,完成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<QueryBuilder> must = boolQueryBuilder.must();
        //表示搜索class为1的人
        must.add(QueryBuilders.termQuery("class", 1));
        //过滤
        List<QueryBuilder> 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();
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值