首頁 > Java > java教程 > 強大的Elastisearch搜尋引擎在Java中使用的實例程式碼

強大的Elastisearch搜尋引擎在Java中使用的實例程式碼

黄舟
發布: 2017-05-21 10:17:47
原創
1823 人瀏覽過

本篇文章主要介紹了Java使用強大的Elastisearch搜尋引擎實例程式碼,具有一定的參考價值,有興趣的可以了解一下

Elastisearch是一個很強大,易於使用的搜尋索引

在系統上執行Elastisearch只需以下幾個步驟

1.下載Elastisearch

 程式碼如下:

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.4.0.zip
登入後複製

2.解壓縮

unzip elasticsearch-5.4.0.zip
登入後複製

3.運行

elasticsearch-5.4.0/bin/elasticsearch
登入後複製

這時有可能會直接被Killed掉,因為記憶體溢出(OOM),elastisearch佔用的記憶體非常大,所以在記憶體比較小的伺服器上運行要先修改jvm的記憶體大小

vi elasticsearch-5.4.0/config/jvm.options
登入後複製

將22和23行的堆疊大小改為512M

-Xms512M
-Xmx512M
登入後複製

如果重新啟動後還是killed就再改小一點

4.測試是否成功

curl  'http://localhost:9200/?pretty'
登入後複製

你能看到以下回傳訊息:

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

則表示啟動成功

##接下來我們用Java的API來操作Elasticsearch

首先是導入elastisearch和log4j的套件

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>
登入後複製

以下是常用的幾個操作

1.建立client

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

#2.建立索引

/**
   * 创建索引,有则先删除
   * @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.插入資料

/**
   * 插入数据
   * @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.查詢所有

  /**
   * 查询所有
   */
  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.關鍵字查詢

  /**
   * 关键词查询
   *
   * @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.數值範圍過濾

  /**
   * 数值范围过滤
   *
   * @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.排序

  /**
   * 排序
   *
   * @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.高亮關鍵字

/**
   * 高亮关键字
   * @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.根據id查找

 /**
   * 根据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.刪除

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

11.更新

  /**
   * 更新
   * @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();
    }
  }
登入後複製

以上是強大的Elastisearch搜尋引擎在Java中使用的實例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板