SolrDemo

来源:互联网 发布:淘宝2017虚假交易处罚 编辑:程序博客网 时间:2024/06/07 05:56

单机版查询:

    <!-- 商品名称 -->    <field name="product_name" type="text_ik" indexed="true" stored="true"/>    <!-- 商品分类ID -->    <field name="product_catalog" type="string" indexed="true" stored="true"/>     <!-- 商品分类名称 -->    <field name="product_catalog_name" type="string" indexed="true" stored="false"/>    <!-- 商品价格 -->    <field name="product_price" type="float" indexed="true" stored="true"/>    <!-- 商品描述 -->    <field name="product_description" type="text_ik" indexed="true" stored="false"/>    <!-- 商品图片地址 -->    <field name="product_picture" type="string" indexed="false" stored="true"/>     <!-- 目标域 -->    <field name="product_keywords" type="text_ik" indexed="true" stored="true" multiValued="true"/>     <!-- 复制域 -->    <copyField source="product_name" dest="product_keywords"/>    <copyField source="product_description" dest="product_keywords"/>
package com.da.test;import java.util.List;import java.util.Map;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrQuery.ORDER;import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.junit.Test;public class IndexSearcher {    @Test    public void search01() throws Exception {        // 创建HttpSolrServer        HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr");        // 创建SolrQuery对象        SolrQuery query = new SolrQuery();        // 输入查询条件        query.setQuery("product_name:小黄人");        // 执行查询并返回结果        QueryResponse response = server.query(query);        // 获取匹配的所有结果        SolrDocumentList list = response.getResults();        // 匹配结果总数        long count = list.getNumFound();        System.out.println("匹配结果总数:" + count);        for (SolrDocument doc : list) {            System.out.println(doc.get("id"));            System.out.println(doc.get("product_name"));            System.out.println(doc.get("product_catalog"));            System.out.println(doc.get("product_price"));            System.out.println(doc.get("product_picture"));            System.out.println("=====================");        }    }    @Test    public void search02() throws Exception {        // 创建HttpSolrServer        HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr");        // 创建SolrQuery对象        SolrQuery query = new SolrQuery();        // 输入查询条件        query.setQuery("product_name:小黄人");        // query.set("q", "product_name:小黄人");        // 设置过滤条件        // 如果设置多个过滤条件的话,需要使用query.addFilterQuery(fq)        query.setFilterQueries("product_price:[1 TO 10]");        // 设置排序        query.setSort("product_price", ORDER.asc);        // 设置分页信息(使用默认的)        query.setStart(0);        query.setRows(10);        // 设置显示的Field的域集合        query.setFields("id,product_name,product_catalog,product_price,product_picture");        // 设置默认域        query.set("df", "product_keywords");        // 设置高亮信息        query.setHighlight(true);        query.addHighlightField("product_name");        query.setHighlightSimplePre("<em>");        query.setHighlightSimplePost("</em>");        // 执行查询并返回结果        QueryResponse response = server.query(query);        // 获取匹配的所有结果        SolrDocumentList list = response.getResults();        // 匹配结果总数        long count = list.getNumFound();        System.out.println("匹配结果总数:" + count);        // 获取高亮显示信息        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();        for (SolrDocument doc : list) {            System.out.println(doc.get("id"));            List<String> list2 = highlighting.get(doc.get("id")).get("product_name");            if (list2 != null)                System.out.println("高亮显示的商品名称:" + list2.get(0));            else {                System.out.println(doc.get("product_name"));            }            System.out.println(doc.get("product_catalog"));            System.out.println(doc.get("product_price"));            System.out.println(doc.get("product_picture"));            System.out.println("=====================");        }    }}

增删改:

package com.da.test;import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.common.SolrInputDocument;import org.junit.Test;public class IndexManager {    @Test    public void insertAndUpdateIndex() throws Exception {        // 创建HttpSolrServer        HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr");        // 创建Document对象        SolrInputDocument document = new SolrInputDocument();        document.addField("id", "test001");        document.addField("name", "solr test 111");        // 将Document对象添加到索引库        server.add(document);        // 提交        server.commit();    }    @Test    public void deleteIndex() throws Exception {        // 创建HttpSolrServer        HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr");        // 根据指定的ID删除索引        server.deleteById("test001");        // 根据条件删除        // server.deleteByQuery("id:test001");        // 删除全部(慎用)        // server.deleteByQuery("*:*");        // 提交        server.commit();    }}

整合spring:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">    <!-- 配置SolrServer对象 -->    <!-- 单机版 -->    <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">        <constructor-arg name="baseURL" value="${SOLR.SERVER.URL}"></constructor-arg>    </bean>    <!-- 集群版 -->    <!-- <bean id="cloudSolrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer">        <constructor-arg name="zkHost" value="192.168.25.154:2181,192.168.25.154:2182,192.168.25.154:2183"></constructor-arg>        <property name="defaultCollection" value="collection2"></property>    </bean> --></beans>

DAO:

package com.taotao.search.dao.impl;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.taotao.search.dao.SearchDao;import com.taotao.search.pojo.Item;import com.taotao.search.pojo.SearchResult;/** * 商品搜索Dao * @version 1.0 */@Repositorypublic class SearchDaoImpl implements SearchDao {    @Autowired    private SolrServer solrServer;    @Override    public SearchResult search(SolrQuery query) throws Exception {        //返回值对象        SearchResult result = new SearchResult();        //根据查询条件查询索引库        QueryResponse queryResponse = solrServer.query(query);        //取查询结果        SolrDocumentList solrDocumentList = queryResponse.getResults();        //取查询结果总数量        result.setRecordCount(solrDocumentList.getNumFound());        //商品列表        List<Item> itemList = new ArrayList<>();        //取高亮显示        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();        //取商品列表        for (SolrDocument solrDocument : solrDocumentList) {            //创建一商品对象            Item item = new Item();            item.setId((String) solrDocument.get("id"));            //取高亮显示的结果            List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");            String title = "";            if (list != null && list.size()>0) {                title = list.get(0);            } else {                title = (String) solrDocument.get("item_title");            }            item.setTitle(title);            item.setImage((String) solrDocument.get("item_image"));            item.setPrice((long) solrDocument.get("item_price"));            item.setSell_point((String) solrDocument.get("item_sell_point"));            item.setCategory_name((String) solrDocument.get("item_category_name"));            //添加的商品列表            itemList.add(item);        }        result.setItemList(itemList);        return result;    }}

SERVICE

package com.taotao.search.service.impl;import org.apache.solr.client.solrj.SolrQuery;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.taotao.search.dao.SearchDao;import com.taotao.search.pojo.SearchResult;import com.taotao.search.service.SearchService;/** * 搜索Service */@Servicepublic class SearchServiceImpl implements SearchService {    @Autowired    private SearchDao searchDao;    @Override    public SearchResult search(String queryString, int page, int rows) throws Exception {        //创建查询对象        SolrQuery query = new SolrQuery();        //设置查询条件        query.setQuery(queryString);        //设置分页        query.setStart((page - 1) * rows);        query.setRows(rows);        //设置默认搜素域        query.set("df", "item_keywords");        //设置高亮显示        query.setHighlight(true);        query.addHighlightField("item_title");        query.setHighlightSimplePre("<em style=\"color:red\">");        query.setHighlightSimplePost("</em>");        //执行查询        SearchResult searchResult = searchDao.search(query);        //计算查询结果总页数        long recordCount = searchResult.getRecordCount();        long pageCount = recordCount / rows;        if (recordCount % rows > 0) {            pageCount++;        }        searchResult.setPageCount(pageCount);        searchResult.setCurPage(page);        return searchResult;    }}

RESULT类:

package com.taotao.search.pojo;import java.util.List;public class SearchResult {    //商品列表    private List<Item> itemList;    //总记录数    private long recordCount;    //总页数    private long pageCount;    //当前页    private long curPage;    public List<Item> getItemList() {        return itemList;    }    public void setItemList(List<Item> itemList) {        this.itemList = itemList;    }    public long getRecordCount() {        return recordCount;    }    public void setRecordCount(long recordCount) {        this.recordCount = recordCount;    }    public long getPageCount() {        return pageCount;    }    public void setPageCount(long pageCount) {        this.pageCount = pageCount;    }    public long getCurPage() {        return curPage;    }    public void setCurPage(long curPage) {        this.curPage = curPage;    }}
原创粉丝点击