java使用jest连接操作Elasticsearch2.2.0中的索引

Wesley13
• 阅读 656

前言

在了解jest框架前,楼主一直尝试用官方的Elasticsearch java api连接es服务的,可是,不知何故,一直报如下的异常信息,谷歌了很久,都说是jvm版本不一致导致的问题,可我是本地测试的,jvm肯定是一致的,这个问题现在都木有解决,but,这怎么能阻止我探索es的脚步呢,so,让我发现了jest 这个框架   

org.elasticsearch.transport.RemoteTransportException: Failed to deserialize exception response from stream
Caused by: org.elasticsearch.transport.TransportSerializationException: Failed to deserialize exception response from stream

我的测试代码是参考官方api实例的,官方api地址: Elasticsearch java api,代码如下:

Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("127.0.0.1", 9300));
        QueryBuilder queryBuilder =  QueryBuilders.termQuery("content", "搜");
        SearchResponse searchResponse = client.prepareSearch("indexdata").setTypes("fulltext")
                .setQuery(queryBuilder)
                .execute()
                .actionGet();
        SearchHits hits = searchResponse.getHits();
        System.out.println("查询到记录数:" + hits.getTotalHits());
        SearchHit[] searchHists = hits.getHits();
        for(SearchHit sh : searchHists){
            System.out.println("content:"+sh.getSource().get("content"));
        }
        client.close();

如果有人知道怎么回事,告诉一下楼主吧,让楼主坑的明白,感激不尽了,我的es版本是2.2.0

进入正题

了解jest

jest是一个基于 HTTP Rest 的连接es服务的api工具集,功能强大,能够使用es java api的查询语句,项目是开源的,github地址:https://github.com/searchbox-io/Jest

我的测试用例

分词器:ik,分词器地址:https://github.com/medcl/elasticsearch-analysis-ik ,es的很多功能都是基于插件提供的,es版本升级都2.2.0后,安装插件的方式不一样了,如果你安装ik分词插件有问题,请点击右上角的qq联系博主

新建索引

curl -XPUT http://localhost:9200/indexdata

创建索引的mapping,指定分词器

curl -XPOST http://localhost:9200/indexdata/fulltext/\_mapping

{
  "fulltext": {
    "_all": {
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_max_word",
      "term_vector": "no",
      "store": "false"
    },
    "properties": {
      "content": {
        "type": "string",
        "store": "no",
        "term_vector": "with_positions_offsets",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word",
        "include_in_all": "true",
        "boost": 8
      },
      "description": {
        "type": "string",
        "store": "no",
        "term_vector": "with_positions_offsets",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word",
        "include_in_all": "true",
        "boost": 8
      },
      "title": {
        "type": "string",
        "store": "no",
        "term_vector": "with_positions_offsets",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word",
        "include_in_all": "true",
        "boost": 8
      },
      "keyword": {
        "type": "string",
        "store": "no",
        "term_vector": "with_positions_offsets",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word",
        "include_in_all": "true",
        "boost": 8
      }
    }
  }
}

mapping信息可以用head插件查看,如下

java使用jest连接操作Elasticsearch2.2.0中的索引
导入数据和查询,看代码吧

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ElasticSearchTestApplication.class)
public class JestTestApplicationTests {
    @Autowired
    private KlarticleDao klarticleDao;
    //得到JestClient实例
    public JestClient getClient()throws Exception{
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://127.0.0.1:9200")
                .multiThreaded(true)
                .build());

        return  factory.getObject();
    }
    /**
     * 导入数据库数据到es
     * @throws Exception
     */
    @Test
    public void contextLoads() throws  Exception{
        JestClient client=getClient();
        Listlists=klarticleDao.findAll();
        for(Klarticle k:lists){
            Index index = new Index.Builder(k).index("indexdata").type("fulltext").id(k.getArcid()+"").build();
            System.out.println("添加索引----》"+k.getTitle());
            client.execute(index);
        }
        //批量新增的方式,效率更高
        Bulk.Builder bulkBuilder = new Bulk.Builder();
        for(Klarticle k:lists){
            Index index = new Index.Builder(k).index("indexdata").type("fulltext").id(k.getArcid()+"").build();
            bulkBuilder.addAction(index);
        }
        client.execute(bulkBuilder.build());
        client.shutdownClient();
    }
    //搜索测试
    @Test
    public void JestSearchTest()throws Exception{
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("content", "搜索"));
        Search search = new Search.Builder(searchSourceBuilder.toString())
                // multiple index or types can be added.
                .addIndex("indexdata")
                .build();
        JestClient client =getClient();
        SearchResult result=  client.execute(search);
//          List

  
  
  
   
   
   
 > hits = result.getHits(Klarticle.class);
        Listarticles = result.getSourceAsObjectList(Klarticle.class);
        for(Klarticle k:articles){
            System.out.println("------->:"+k.getTitle());
        }
    }
}


  
  
  

下面是依赖的jar,maven项目

<!--jest依赖-->
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--jest 日志依赖-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.2.0</version>
        </dependency>
    </dependencies>

本文同步分享在 博客“kailing”(other)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
待兔 待兔
6个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Easter79 Easter79
3年前
taro小程序展示富文本
在微信小程序下会用到wxParse这个东西来达到html转换wxml的效果,taro小程序官方也给出了示例,地址(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2FNervJS%2Ftarocomponentstest%2Fblob%2Fmaster%2F
Easter79 Easter79
3年前
tcc分布式事务源码解析系列(四)之项目实战
通过之前的几篇文章我相信您已经搭建好了运行环境,本次的项目实战是依照happylifeplattccdemo(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Fyu199195%2Fhappylifeplattcc%2Ftree%2Fmaster%
Wesley13 Wesley13
3年前
Java微服务新生代之Nacos
前言从2017年底Java开发领域使用最广的RPC框架Dubbo开启重新更新维护之路开始,阿里巴巴为打造Dubbo微服务生态持续开源了Sentinel(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Falibaba%2FSenti
Stella981 Stella981
3年前
MXNet 源码解读系列之一 C++端如何解析NDArray参数文件
本文相关代码:parsingNDArray(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2FLdpe2G%2FDeepLearningForFun%2Ftree%2Fmaster%2FMXNetCpp%2FparsingNDArray)   要想弄
Wesley13 Wesley13
3年前
Ubuntu安装网易云音乐
安装网易云音乐更多的Ubuntu下软件安装问题,请关注这儿(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Fpyexile%2FNotes%2Ftree%2Fmaster%2FLinux%2F%25E8%25BD%25AF%25E4%25
Stella981 Stella981
3年前
ARouter使用随记
官方文档地址(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Falibaba%2FARouter%2Fblob%2Fmaster%2FREADME_CN.md)其他配置1.创建一个config.gradleext{isDeb
Stella981 Stella981
3年前
Node学习笔记
Node.js教程目录1.Node.js基础(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Fwscats%2Fnodetutorial%2Ftree%2Fmaster%2Ftutorial%2Fbase)
Stella981 Stella981
3年前
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法参考文章:(1)Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.codeprj.com%2Fblo
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究