欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java使用强大的Elastisearch搜索引擎实例代码

程序员文章站 2024-02-22 15:47:00
elastisearch是一个很强大,易用的搜索引擎 在系统上运行elastisearch只需以下几步 1.下载elastisearch 复制代码 代码如下:...

elastisearch是一个很强大,易用的搜索引擎

在系统上运行elastisearch只需以下几步

1.下载elastisearch

复制代码 代码如下:

wget

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();
    }
  }

常用的操作就这些,代码上传到https://github.com/jkgeekjack/elasticsearchexample

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。