search
HomeJavajavaTutorialExample code for using the powerful Elastisearch search engine in Java

This article mainly introduces the use of powerful Elastisearch in Java Search engine example code, which has certain reference value. Those who are interested can learn about it

Elastisearch is a very powerful and easy-to-use engine. SearchIndexEngine

To run Elastisearch on the system, you only need the following steps

1. Download Elastisearch

The code is as follows:

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.4.0.zip

2. Unzip

unzip elasticsearch-5.4.0.zip

3. Run

elasticsearch-5.4.0/bin/elasticsearch

At this time, it may be killed directly. Because of memory overflow (OOM), elastisearch takes up a very large amount of memory. Therefore, when running on a server with relatively small memory, you must first modify the memory size of the jvm

vi elasticsearch-5.4.0/config/jvm.options

Change the stack size of lines 22 and 23 to 512M

-Xms512M
-Xmx512M

If it is still killed after restarting, try again Change it to a smaller size

4. Whether the test is successful

curl  'http://localhost:9200/?pretty'

You can see the following return information:

{
      "status":  200,
      "name":  "Shrunken  Bones",
      "version":  {
            "number":  "1.4.0",
            "lucene_version":  "4.10"
      },
      "tagline":  "You  Know,  for  Search"
}

It means the startup is successful

Connect Next, we use Java's API to operate Elasticsearch

First, import the elastisearch and log4j packages

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jk</groupId>
  <artifactId>ElasticsearchExample</artifactId>
  <version>1.0-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>transport</artifactId>
      <!--用哪个版本就填什么-->
      <version>5.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.7</version>
    </dependency>
  </dependencies>

</project>

The following are commonly used Several operations

1. Create client

Client client = null;
    try {
      client = new PreBuiltTransportClient(Settings.EMPTY)
          .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    } catch (Exception e) {
      e.printStackTrace();
    }

2. Create index

/**
   * 创建索引,有则先删除
   * @param client
   */
  private static void recreateIndex(Client client) {
    if (client.admin().indices().prepareExists(index).execute().actionGet()
        .isExists()) {
      DeleteIndexResponse deleteIndexResponse = client.admin().indices()
          .delete(new DeleteIndexRequest(index)).actionGet();
      System.out.println("delete index :");
      System.out.println(deleteIndexResponse);
    }

    CreateIndexResponse createIndexResponse = client.admin().indices()
        .prepareCreate(index).execute().actionGet();
    System.out.println("create index :");
    System.out.println(createIndexResponse);
  }

3.Insert data

/**
   * 插入数据
   * @param client
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  private static void doIndex(final Client client) {
    Map s11 = new LinkedHashMap();
    s11.put("title", "Think in java");
    s11.put("origin", "美国");
    s11.put("description", "初级java开发人员必读的书");
    s11.put("author", "Bruce Eckel");
    s11.put("price", 108);

    Map s12 = new LinkedHashMap();
    s12.put("title", "Head First Java");
    s12.put("origin", "英国");
    s12.put("description", "java入门教材");
    s12.put("author", "Kathy Sierra");
    s12.put("price", 54);

    Map s21 = new LinkedHashMap();
    s21.put("title", "Design Pattern");
    s21.put("origin", "法国");
    s21.put("description", "程序员不得不读的设计模式");
    s21.put("author", "Kathy Sierra");
    s21.put("price", 89);

    Map s22 = new LinkedHashMap();
    s22.put("title", "黑客与画家");
    s22.put("origin", "法国");
    s22.put("description", "读完之后脑洞大开");
    s22.put("author", "Paul Graham");
    s22.put("price", 35);

    BulkResponse bulkResponse = client
        .prepareBulk()
        .add(client.prepareIndex(index, type).setId("11").setSource(s11).setOpType(IndexRequest.OpType.INDEX).request())
        .add(client.prepareIndex(index, type).setId("12").setSource(s12).setOpType(IndexRequest.OpType.INDEX).request())
        .add(client.prepareIndex(index, type).setId("21").setSource(s21).setOpType(IndexRequest.OpType.INDEX).request())
        .add(client.prepareIndex(index, type).setId("22").setSource(s22).setOpType(IndexRequest.OpType.INDEX).request())
        .execute().actionGet();
    if (bulkResponse.hasFailures()) {
      System.err.println("index docs ERROR:" + bulkResponse.buildFailureMessage());
    } else {
      System.out.println("index docs SUCCESS:");
      System.out.println(bulkResponse);
    }
  }

4.QueryAll

  /**
   * 查询所有
   */
  private static void searchAll(Client client) {
    SearchResponse response = client.prepareSearch(index)
        .setQuery(QueryBuilders.matchAllQuery())
        .setExplain(true).execute().actionGet();
    System.out.println("searchAll : ");
    for (SearchHit searchHit : response.getHits()) {
      System.out.println("********");
      System.out.println(searchHit.getSource());
    }
  }

5.Keyword query

  /**
   * 关键词查询
   *
   * @param client
   */
  private static void searchKeyWord(Client client) {
    SearchResponse response = client.prepareSearch(index)
        //查询所有字段匹配关键字
        .setQuery(QueryBuilders.matchQuery("_all", "法国"))
        //设置最小匹配程度
//        .setQuery(QueryBuilders.matchQuery("_all", "法国").minimumShouldMatch("100%"))
        .execute().actionGet();
    System.out.println("searchKeyWord : ");
    System.out.println(response);
  }

6. Numeric range filtering

  /**
   * 数值范围过滤
   *
   * @param client
   */
  private static void searchRange(Client client) {
    SearchResponse response = client.prepareSearch(index).
        //大于80,小于100
        setQuery(QueryBuilders.rangeQuery("price").gt(80).lt(100))
        .execute()
        .actionGet();
    System.out.println("searchRange : ");
    System.out.println(response);
  }

7. Sorting

  /**
   * 排序
   *
   * @param client
   */
  private static void searchOrdered(Client client) {
    SearchResponse response = client.prepareSearch(index)
        .setQuery(QueryBuilders.matchAllQuery())
        //根据价格降序排序
        .addSort(SortBuilders.fieldSort("price")
            .order(SortOrder.DESC)).execute().actionGet();
    System.out.println("searchOrdered : ");
    System.out.println(response);
  }

8.Highlight keywords

/**
   * 高亮关键字
   * @param client
   */
  private static void searchHightlight(Client client) {
    //高亮多个字段
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.field("title");
    highlightBuilder.field("description");
    SearchResponse response = client.prepareSearch(index)
        //单条件匹配,高亮时只能高亮该字段
//        .setQuery(QueryBuilders.matchQuery("title", "java"))
        //多条件匹配,高亮时只能高亮多个字段
        .setQuery(QueryBuilders.multiMatchQuery("开发人员必读", "title", "description"))
        .highlighter(highlightBuilder)
        .execute()
        .actionGet();
    System.out.println("searchHightlight : ");
    System.out.println(response);
  }

9. Search

 /**
   * 根据id查找
   * @param client
   */
  private static void findById(final Client client) {
    String id="12";
    GetResponse response = client.prepareGet(index, type, id).get();
    System.out.println("findById");
    System.out.println(response);
  }

10. Delete

   /**
   * 删除
   * @param client
   */
  private static void deleteById(Client client) {
    String id="12";
    DeleteResponse response = client.prepareDelete(index, type, id).get();
  }

11.Update

  /**
   * 更新
   * @param client
   */
  private static void updateById(Client client) {
    try {
      String id="11";
      client.prepareUpdate(index, type, id)
          .setDoc(jsonBuilder()
              .startObject()
              .field("title", "白鹿原")
              .endObject())
          .get();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

The above is the detailed content of Example code for using the powerful Elastisearch search engine in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在 iPhone 和 iPad 上更改搜索引擎如何在 iPhone 和 iPad 上更改搜索引擎Apr 25, 2023 am 08:28 AM

在iPhone或iPad上的Safari、GoogleChrome或其他浏览器中更改搜索引擎非常简单。本教程将向您展示如何在iPhone和iPad上可用的四种不同网络浏览器上进行操作。如何更改iPhone或iPad上的Safari搜索引擎Safari是iOS和iPadOS上的默认网络浏览器,但您可能不喜欢这个搜索引擎。幸运的是,您可以使用以下步骤进行更改:在iPhone或iPad上,从主屏幕启动设置。向下滑动并从列表中点按Safari。在下一个菜单中,

Java开发:如何实现搜索引擎和全文检索功能Java开发:如何实现搜索引擎和全文检索功能Sep 21, 2023 pm 01:10 PM

Java开发:如何实现搜索引擎和全文检索功能,需要具体代码示例搜索引擎和全文检索是现代互联网时代的重要功能。它们不仅可以帮助用户快速找到想要的内容,还可以为网站和应用程序提供更好的用户体验。本文将介绍如何使用Java开发搜索引擎和全文检索功能,并提供一些具体的代码示例。使用Lucene库实现全文检索Lucene是一款开源的全文检索引擎库,由ApacheSo

PHP搜索引擎性能优化:Algolia的妙用之道PHP搜索引擎性能优化:Algolia的妙用之道Jul 23, 2023 pm 04:21 PM

PHP搜索引擎性能优化:Algolia的妙用之道随着互联网的发展和用户对搜索体验的要求不断提高,搜索引擎的性能优化变得至关重要。在PHP开发领域,Algolia是一个强大且易于集成的搜索引擎服务。本文将介绍Algolia的妙用之道以及如何通过Algolia来优化PHP搜索引擎的性能。Algolia介绍Algolia是一家基于SaaS模式的搜索引擎服务提供商,

人工智能搜索领域,谷歌微软展开对抗人工智能搜索领域,谷歌微软展开对抗Apr 08, 2023 am 11:31 AM

自去年年底推出以来,ChatGPT被看作对传统搜索信息方式的重大威胁。因为它是多样化的,可以回答人们的问题,编写论文或诗歌,甚至编写程序代码。对话式人工智能提供连贯答案的能力被认为是对谷歌搜索引擎的威胁,几十年来,谷歌一直是人们在互联网上搜索信息的标杆平台。OpenAI的ChatGPT可以定制用户提出的特定问题的答案,这可以节省浏览网站的时间。《纽约时报》12月发布的一份报告显示,ChatGPT一夜之间的成功迫使谷歌称其为“红色代码”,并开始应对人工智能聊天机器人对其搜索引擎业务造成的威胁。根据

PHP和Manticore Search开发:打造高效的搜索引擎PHP和Manticore Search开发:打造高效的搜索引擎Aug 07, 2023 am 09:45 AM

PHP和ManticoreSearch开发:打造高效的搜索引擎搜索引擎在现代互联网应用中起着非常重要的作用。为了实现高效和准确的搜索功能,我们需要选择合适的搜索引擎,并使用适当的开发工具进行开发。本文将介绍如何使用PHP和ManticoreSearch开发一个高效的搜索引擎。ManticoreSearch是一个强大的开源搜索引擎,它基于SphinxS

使用PHP和Elasticsearch构建高效的搜索引擎使用PHP和Elasticsearch构建高效的搜索引擎Jul 09, 2023 pm 04:57 PM

使用PHP和Elasticsearch构建高效的搜索引擎引言:在当今互联网时代,搜索引擎是人们获取信息的首选工具。为了提供快速准确的搜索结果,开发人员需要构建高效的搜索引擎。本文将介绍如何使用PHP和Elasticsearch构建高效的搜索引擎,并给出相应的代码示例。一、什么是Elasticsearch?Elasticsearch是一个分布式的开源搜索和分析

如何在PHP7.0中实现一个全文搜索引擎?如何在PHP7.0中实现一个全文搜索引擎?May 26, 2023 pm 04:51 PM

随着信息时代的不断发展,人们越来越依赖互联网来获取信息。而作为信息分享的平台之一,网页搜索引擎也在不断进化和完善。本文将介绍如何在PHP7.0中实现一个全文搜索引擎,帮助读者更好地利用PHP技术,快速构建高效率的搜索引擎。一、全文搜索引擎概述全文搜索即使用关键词或短语在整篇文档中进行搜索,以找到最匹配的结果。全文搜索引擎使用算法对文档进行索引,以加速搜索。在

构建强大的搜索引擎:PHP与Algolia的结合实践构建强大的搜索引擎:PHP与Algolia的结合实践Jul 22, 2023 pm 01:30 PM

构建强大的搜索引擎:PHP与Algolia的结合实践搜索引擎在当今互联网时代扮演着至关重要的角色,为用户提供快速、准确的搜索结果。而在实现强大的搜索功能时,PHP作为一种常用的编程语言,结合Algolia这个高性能的搜索服务,可以为网站或应用程序提供出色的搜索体验。本文将介绍如何使用PHP和Algolia构建强大的搜索引擎,并附上一些代码示例供读者参考。一、

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor