Elasticsearch Java API使用详解(基本操作增删改、条件查询QueryBuilders、映射mapping)

本文详细介绍了如何使用Elasticsearch的Java API进行基本操作,包括创建和删除索引、添加和更新文档、查询文档数据。同时,文章还探讨了使用QueryBuilders进行条件查询,如matchAllQuery、queryStringQuery、wildcardQuery、TermQuery和fuzzy查询。此外,还展示了如何管理映射(mapping)。
摘要由CSDN通过智能技术生成

前言

在前面的两篇文章中分别介绍了Elasticsearch和head插件的安装部署:

Elasticsearch5.2.2 安装部署与常见启动报错解决
Elasticsearch head插件安装过程详解

在本篇文章,将结合具体的例子重点介绍Elasticsearch Java API的操作。

Elasticsearch的Java客户端非常强大;它可以建立一个嵌入式实例并在必要时运行管理任务。运行一个Java应用程序和Elasticsearch时,有两种操作模式可供使用。该应用程序可在Elasticsearch集群中扮演更加主动或更加被动的角色。在更加主动的情况下(称为Node Client),应用程序实例将从集群接收请求,确定哪个节点应处理该请求,就像正常节点所做的一样。(应用程序甚至可以托管索引和处理请求。)另一种模式称为Transport Client,它将所有请求都转发到另一个Elasticsearch节点,由后者来确定最终目标。

一、API基本操作

1、操作环境准备

  • Elasticsearch和head插件已经安装部署好,并已经启动成功
  • 创建Maven工程,导入以下依赖:
	<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • 等待依赖的jar包下载完成
  • 在Maven工程的resources目录下新建一个文件log4j2.xml ,然后在该文件中下入以下配置信息:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
        </Console>
        <RollingFile name="RollingFile" fileName="logs/strutslog1.log"
                     filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{
   MM-dd-yyyy} %p %c{
   1.} [%t] -%M-%L- %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="1 KB"/>
            </Policies>
            <DefaultRolloverStrategy fileIndex="max" max="2"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.opensymphony.xwork2" level="WAN"/>
        <Logger name="org.apache.struts2" level="WAN"/>
        <Root level="warn">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

2、获取Transport Client

(1)ElasticSearch服务默认端口9300。
(2)Web管理平台端口9200。

private TransportClient client;

    @SuppressWarnings("unchecked")
    @Before
    public void getClient() throws Exception {
   

        // 1 设置连接的集群名称
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        // 2 连接集群
        client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("weekend110"), 9300));

        // 3 打印集群名称
        System.out.println(client.toString());
    }

3、创建索引
1)源代码:

	/**
     * 创建索引
     */
    @Test
    public void createIndex_blog(){
   
        // 1 创建索引
        client.admin().indices().prepareCreate("blog1").get();

        // 2 关闭连接
        client.close();
    }

2)查看结果: http://192.168.2.100:9200/blog1

{“blog1”:{“aliases”:{},“mappings”:{},“settings”:{“index”:{“creation_date”:“1594951875136”,“number_of_shards”:“5”,“number_of_replicas”:“1”,“uuid”:“MIoleYUIRf2pBhgycwdUcQ”,“version”:{“created”:“5020299”},“provided_name”:“blog1”}}}}

4、删除索引
1)源代码:

	/**
     * 删除索引
     */
    @Test
    public void deleteIndex(){
   
        // 1 删除索引
        client.admin().indices().prepareDelete("blog1").get();

        // 2 关闭连接
        client.close();
    }

2)查看结果: http://192.168.2.100:9200/blog1

没有blog1索引了。
{“error”:{“root_cause”:[{“type”:“index_not_found_exception”,“reason”:“no such index”,“resource.type”:“index_or_alias”,“resource.id”:“blog1”,“index_uuid”:“na”,“index”:“blog1”}],“type”:“index_not_found_exception”,“reason”:“no such index”,“resource.type”:“index_or_alias”,“resource.id”:“blog1”,“index_uuid”:“na”,“index”:“blog1”},“status”:404}

5、新建文档(源数据json串)
当直接在ElasticSearch建立文档对象时,如果索引不存在的,默认会自动创建,映射采用默认方式。
ElasticSearch服务默认端口9300
Web管理平台端口9200

1)源代码:

	/**
     * 源数据为 json串
     * @throws UnknownHostException
     */
    @Test
    public void createIndexByJson() throws UnknownHostException {
   

        // 1 文档数据准备
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
                + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";

        // 2 创建文档
        IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();

        // 3 打印返回的结果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("version:" + indexResponse.getVersion());
        System.out.println("result:" + indexResponse.getResult());

        // 4 关闭连接
        client.close();
    }

2)查看结果:
在这里插入图片描述
在这里插入图片描述
6、新建文档(源数据map方式添加json)
1)源代码:

 	/**
     * 源数据 Map方式添加json
     */
    @Test
    public void createIndexByMap() {
   

        // 1 文档数据准备
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "2");
        map.put("title", "基于Lucene的搜索服务器");
        map.put("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");

        // 2 创建文档
        IndexResponse indexResponse = client.prepareIndex("blog", "article", "2").setSource(map).execute().actionGet();

        // 3 打印返回的结果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("version:" + indexResponse.getVersion());
        System.out.println("result:" + indexResponse.getResult());

        // 4 关闭连接
        client.close();
    }

2)查看结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值