elasticsearch简单使用

谭玄天
2023-12-01

elasticsearch简单使用

新手自学,好多注解还不懂怎么使用,记录一下,再接再厉

安装

官方查询:elasticsearch 
下载:docker pull elasticsearch:6.8.1 
es启动默认占用2G堆内存空间,最好做下限制 
运行:docker run  -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d  -p 9200:9200 -p 9300:9300 --name myES  elasticsearch:6.8.1 
注释:-e ES_JAVA_OPTS="-Xms256m -Xmx256m"  设置运行占用最大最小内存为256m 
官方运行:docker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:tag   
查看:浏览器输入 ip+9200,记下cluster_name的值,我的是docker-cluster,springboot配置需要
springboot配置:
spring:
  data:
    elasticsearch:
      cluster-nodes: ip:9300
      cluster-name: docker-cluster
      repositories:
        enabled: true

es安装出错就不做记录了,因为百度好多,很全,想看出什么错:docker logs myES

跨域

命令:
docker exec -it myES  /bin/bash
cd config
vi elasticsearch.yml
# 加入跨域配置,复制下面即可
http.cors.enabled: true
http.cors.allow-origin: "*"
重启:docker restart myES

springboot中的简单使用

我的springboot版本是2.2.x
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

测试代码

实体类

/**
 * Created with IntelliJ IDEA.
 *
 * @author : zjs
 * @Date: 2020/6/18
 * Description:
 * 注解:@Document 第一个参数索引,第二个参数是类型
 * 如在浏览器查询id为1的数据:ip:9200/goodsname/searchHistory/1
 *
 */
@Data
@ToString
@Document(indexName = "goodsname",type = "searchHistory")
public class YxSearchHistory {

    /**
     * 主键ID
     */
    @Field(type = FieldType.Keyword)
    private String id;

    /**
     * 搜索字段(商品名称)
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String goodsname;

    /**
     * 搜索次数
     */
    @Field(type = FieldType.Integer, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private int num;

    /**
     * 创建时间
     */
    @Field(type = FieldType.Date, pattern = "yyyy-MM-dd HH:mm:ss", format = DateFormat.custom)
    private String createTime;
}

Repository类

/**
 * Created with IntelliJ IDEA.
 *
 * @author : zjs
 * @Date: 2020/6/18
 * Description:
 */
@Repository
public interface SearchHistoryRepository extends ElasticsearchRepository<YxSearchHistory,String> {
}

测试类

    @Autowired
    private SearchHistoryRepository searchHistoryRepository;
   
   private static YxSearchHistory createSearchHistory(String goodsname,int num) {
        //UUID模拟ID
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString();
        YxSearchHistory searchHistory = new YxSearchHistory();
        searchHistory.setId(id);
        searchHistory.setNum(num);
        searchHistory.setGoodsname(goodsname);
        searchHistory.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return searchHistory;
    }
    
        @Test
    public void contextLoads() {
        YxSearchHistory searchHistory;

        TermQueryBuilder matchQueryBuilder = QueryBuilders.termQuery("goodsname.keyword","黑人牙膏");
        Iterable<YxSearchHistory> search = searchHistoryRepository.search(matchQueryBuilder);
        if(search.iterator().hasNext()){
            System.out.println("已存在");
        }else{
            searchHistory = createSearchHistory("黑人牙膏",8);
            searchHistoryRepository.save(searchHistory);
        }


        searchHistory = createSearchHistory("白人牙膏",3);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("蓝猫",1);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("淘气",9);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("三千问",8);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("非洲刚果战斗机",2);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("中国真知味战斗机",3);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("韩国珍宝珠战斗机",6);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("中国阿尔卑斯战斗机",4);
        searchHistoryRepository.save(searchHistory);

        searchHistory = createSearchHistory("中国阿尔卑斯臭豆腐",3);
        searchHistoryRepository.save(searchHistory);
    }
    
    @Test
    public void dele() {
//        删除所有
//        searchHistoryRepository.deleteAll();

        //完成匹配  要查询的字段需要加.keyword,暂时没搞懂为啥要加,没加的时候返回有问题
        TermQueryBuilder matchQueryBuilder = QueryBuilders.termQuery("goodsname.keyword","中国真知味战斗机");
        //分词匹配  意思是会把值进行拆分,如中国 ---中 和 国  都会去查询,还有个分词器,要关注一下
//        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("goodsname", "中国");
        //模糊匹配
//        MatchPhraseQueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery("goodsname", "中国");
        Iterable<YxSearchHistory> search = searchHistoryRepository.search(matchQueryBuilder);
        Iterator<YxSearchHistory> iterator = search.iterator();
        //错误记录: 直接使用search.iterator().hasNext()判断,会一直输出
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
    
    @Test
    public void sort() {
        Sort sort = Sort.by("num").descending();
//        Sort sort = Sort.by("num","createTime").descending();
//        Pageable pageable = PageRequest.of(0, 10, sort);
//        MatchPhraseQueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery("goodsname", "中国棒棒糖");
//        Iterable<SearchHistory> search = searchHistoryRepository.search(matchQueryBuilder,pageable);
        Iterable<YxSearchHistory> search = searchHistoryRepository.findAll(sort);

        Iterator<YxSearchHistory> iterator = search.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

简单的前端使用

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>测试es查询接口</title>
</head>
<body>
    <div id="vue" >
        <p v-for="goods in info.hits.hits">{{goods._source.goodsname}}</p>
    </div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    var vm =new Vue({
        el: '#vue',
        data(){
            return{
                info: {
                    hits: {
                        hits: [
                            {
                                _source: {
                                    goodsname: null,
                                }
                            }
                        ]
                    }
                }
            }
        },
        mounted(){
            // axios.get('http://192.168.0.28:9200/goodsname/searchHistory/_search').then(response => (this.info=response.data));
            // http://192.168.0.28:9200/goodsname/searchHistory/_search?_source=num,goodsname
            axios({
                method: 'get',
                //查询所有
                // url: 'http://192.168.0.28:9200/goodsname/searchHistory/_search' ,
                //查询中国相关
                // url: 'http://192.168.0.28:9200/goodsname/searchHistory/_search?pretty&q=goodsname:"中国"' ,
                //显示频率最高的十条,热门词汇
                // url: 'http://192.168.0.28:9200/goodsname/searchHistory/_search?pretty&sort=num:desc' ,
                //查询随机的5条
                // url: 'http://192.168.0.28:9200/goodsname/searchHistory/_search?pretty&size=5' ,
                //输入时提示 类似词汇并且词汇是搜索最高的5条
                url: 'http://192.168.0.28:9200/goodsname/searchHistory/_search?pretty&q=goodsname:"中国"'
                    +"&size=5&sort=num:desc",
            }).then(response => (this.info=response.data));
        }
    });
</script>
</body>

</html>
 类似资料: