ElasticSearch 记录

version: 5.4.1

step 1  下载 elasticsearch

step 2   启动  {es_dir}/bin/.elasticsearch


创建索引、put一条数据

curl -XPUT 'http://localhost:9200/twitter/tweet/1' -d '{
  "user":"lili",
  "post_date":"2017-06-09",
  "message":"Hello, ElasticSearch!"
}'

Rest API 查询

curl -XGET 'http://localhost:9200/twitter/tweet/_search?pretty'
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "twitter",
        "_type" : "tweet",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "user" : "lili",
          "post_date" : "2017-06-09",
          "message" : "Hello, ElasticSearch!"
        }
      }
    ]
  }
}

Java API 查询

1、POM.xml

<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>


2、src/main/resources 下新建 log4j2.properties文件

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout

rootLogger.level = info
rootLogger.appenderRef.console.ref = console

3、测试(jdk版本>=1.8)

public class ESDemo {
    public static void main(String[] args) throws Exception {
        Settings settings = Settings.builder()
                .put("cluster.name", "myes")//集群名称可以在{es_dir}/conf/elasticsearch.yml中配置
                .put("client.transport.sniff", "true").build();

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

        QueryBuilder qb = termQuery("user", "lili");

        SearchResponse response = client.prepareSearch("twitter")
                .setTypes("tweet").setQuery(qb).get();

        if (response.getHits().getTotalHits() != 0) {
            SearchHits shs = response.getHits();
            for (SearchHit sh : shs.getHits()) {
                System.out.println((sh.getSource().get("message")));
            }
        }
    }
}


4、结果




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值