SpringBoot +Solr

在学习本文章前请先确定solr启动成功!

SpringBoot +Solr_第1张图片

SpringBoot +Solr_第2张图片

如还没安装solr的朋友请学习此文章http://blog.csdn.net/YyCarry/article/details/78695823

pom.xml导入插件solrj


<dependency>
    <groupId>org.apache.solrgroupId>
    <artifactId>solr-solrjartifactId>
    <version>5.3.0version>
dependency>

application.properties引入solr仓库地址

#solr
spring.data.solr.host=http://localhost:8983/solr/new_core

solr新建索引查询索引操作

/** * Created by pudding on 2017-10-11.(YYR) */

@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private SolrClient client;

     @Override
    public boolean SetSolr() {

        try {
            //创建索引
            SolrInputDocument solrInputFields=new SolrInputDocument();
            solrInputFields.addField("id", "1");
            solrInputFields.addField("username", "admin");
            solrInputFields.addField("password", "11111");
            client.add(solrInputFields);
            client.commit();


            //基于实体类创建索引
            List users=new ArrayList();
            users.add(new User(7,"admin7","111111","你好"));
            users.add(new User(8,"admin8","222222","你不好"));
            client.addBeans(users);
            client.commit();

            //查询第一种方式
            ModifiableSolrParams params =new ModifiableSolrParams();
            params.add("q","username:admin");
            params.add("ws","json");
            params.add("start","0");
            params.add("rows","10");
            QueryResponse queryResponse=client.query(params);
            System.out.println(queryResponse);


            //查询第二种方式
            int page = 1;
            int rows = 10;

            SolrQuery solrQuery = new SolrQuery(); // 构造搜索条件
            solrQuery.setQuery("username:7");// 搜索关键词
            // 设置分页
            solrQuery.setStart((Math.max(page, 1) - 1) * rows);
            solrQuery.setRows(rows);
            QueryResponse  docs = client.query(solrQuery);
            SolrDocumentList solrDocuments=docs.getResults();
            for(SolrDocument sd : solrDocuments){
                System.out.println(sd.get("id")+"#"+sd.get("username")+"#"+sd.get("password")+"#"+sd.get("vsername"));
            }


            //List userList=docs.getBeans(User.class);//直接转实体(!这个B有问题,只有用上面的循环赋值比较靠谱)


            //删除索引
            client.deleteByQuery("id:2");
            client.commit();

            //通过版本号删除索引
            client.deleteById("123123");
            client.commit();

        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

}

你可能感兴趣的:(spring-boot,solr)