200115-SpringBoot series Solr query using posture summary

Next, we will move on to the fourth part of Solr Curd, an introduction to how to use queries. This article will mainly cover the following knowledge points

  • Basic query operations
  • Fq query
  • Fl Specifies field queries
  • Comparison/Range
  • The sorting
  • paging
  • grouping

<! — more –>

I. the configuration

Before introducing the demo, we need to install the Solr environment first and build the SpringBoot project project. The specific environment construction process will not be detailed, but the documentation is recommended

  • 190510-SpringBoot Advanced Part Solr Environment Building and Simple Testing

In the application.yml configuration file, red, specifies the domain name of Solr

Spring: data: solr: host: http://127.0.0.1:8983/solr

Then in Solr, write some data, for our query to use, can be written through the console way, can also be through 190526-SpringBoot advanced article search Solr document to add and modify the case of this document using the pose

Initialize the Solr document as follows

{" id ":" 1 ", "content_id" : 1, "title" : "a dusty blog", "content" : "this is a gray blog content", "type" : 1, "create_at" : 1578912072, "Publish_at ":1578912072, "_version_":1655609540674060288}, {"id":" 1 ", "content_id":2, "title":" 1 ", "Content ":" This is a ash content", "type":1, "create_at":1578912072, "publish_at":1578912072, "_version_":1655609550229733376}, {" id ", "3", "content_id" : 3, "title" : "solrTemplate modification after!!!!!!" , "create_at":1578993153, "publish_at":1578993153, "type":0, "_version_":1655694325261008896}, { "id":"4", "content_id":4, "type":1, "create_at":0, "publish_at":0, "_version_":1655694325422489600}, { "id":"5", "content_id":5, "Title ":" addBatchByBean-1 ", "content":" new test document ", "type":1, "create_at":1578993153, "publish_at":1578993153, "_version_":1655694325129936896}, {"id":"6", "content_id":6, "title":" addBatchByBean2 ", "content":" Add another test document ", "type":1, "create_at":1578993153, "publish_at":1578993153, "_version_":1655694325136228352 }

II. The query

The POJOs for Solr documents are as follows. (Note that the primary key ID in Solr is of type String, and the following definition uses Integer. It is recommended to keep the same data type as Solr.)

@Data
public class DocDO implements Serializable {
    private static final long serialVersionUID = 7245059137561820707L;
    @Id
    @Field("id")
    private Integer id;
    @Field("content_id")
    private Integer contentId;
    @Field("title")
    private String title;
    @Field("content")
    private String content;
    @Field("type")
    private Integer type;
    @Field("create_at")
    private Long createAt;
    @Field("publish_at")
    private Long publishAt;
}

1. Primary key query

Support single query and batch query with three parameters, the first is the Collection to be queried, the second is the ID/ID Collection, and the third is the data type returned

private void queryById() {
    DocDO ans = solrTemplate.getById("yhh", 1, DocDO.class).get();
    System.out.println("queryById: " + ans);

    Collection<DocDO> list = solrTemplate.getByIds("yhh", Arrays.asList(1, 2), DocDO.class);
    System.out.println("queryByIds: " + list);
}

The output is as follows

queryById: DocDO(id=1, contentId=1, title= 1, content= 1, type=1, createAt=1578912072, type=1, createAt=1578912072, publishAt=1578912072) queryByIds: DocDO(id=1, contentId=1, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072)]]

2. Simple queries

For example, the simplest query is based on a field

Query Query = new SimpleQuery("title: new SimpleQuery "); Page<DocDO> ans = solrTemplate.query("yhh", query, DocDO.class); System.out.println("simpleQuery : " + ans.getContent());

Specify the query criteria directly in SimpleQuery, and the case above represents the document whose title is a gray

The output is as follows:

SimpleQuery: [DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072]]

Simple queries using the above posture OK, of course, is not very elegant to read; An alternative approach to building query Criteria based on Criteria is recommended

  • If you read the previous MongoDB tutorial series, you will see that MonodB also uses the Criteria to assemble the query Criteria, but note that these are not the same thing
query = new SimpleQuery(); Query. AddCriteria (new Criteria(" Content "). Contains (" Content ")); ans = solrTemplate.query("yhh", query, DocDO.class); System.out.println("simpleQuery : " + ans.getContent());

The output is as follows

simpleQuery : DocDO(id=1, contentId=1, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072)]]

Criteria allows you to build complex and read-friendly query conditions, as demonstrated below, with a case for a multi-condition query

// Query = new SimpleQuery(); Query. AddCriteria (Criteria. Where ("title"). Contains ("content_id"). ans = solrTemplate.query("yhh", query, DocDO.class); System.out.println("multiQuery: " + ans.getContent());

The output results are as follows. On the basis of the above, records with contentId less than 2 are scooped out

multiQuery: [DocDO(id=1, contentId=1, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072)]

3. The fq queries

Fq) are mainly used for filtering, quickly query, mainly with the aid of org. Springframework. Data. Solr. Core. Query. Query# addFilterQuery to add fq conditions

// FQ query query = new SimpleQuery(" Content: * a *"); query.addFilterQuery(FilterQuery.filter(Criteria.where("title").contains("blog"))); ans = solrTemplate.query("yhh", query, DocDO.class); System.out.println("simpleQueryAndFilter: " + ans.getContent());

The output results are as follows:

simpleQueryAndFilter: [DocDO(id=1, contentId=1, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072)]

4. FL specifies the query field

When we are only concerned with a subset of fields in a Solr document, consider specifying fl to get only the required fields; Through the org. Springframework. Data. Solr. Core. Query. SimpleQuery# addProjectionOnFields (Java. Lang. String…). To specify the name of the field to return

Private void QuerySpecialField () {SimpleQuery = new SimpleQuery(); query.addCriteria(Criteria.where("content_id").lessThanEqual(2)); / / fl query query. AddProjectionOnFields (" id ", "title", "content"); List<DocDO> ans = solrTemplate.query("yhh", query, DocDO.class).getContent(); System.out.println("querySpecialField: " + ans); }

The output is as follows

querySpecialField: DocDO(id=1, contentId=null, title= Blog, content= Blog, type=null, createAt=null, publishAt=null), DocDO(id=2, contentId=null, title= 0, content= 0, type=null, createAt=null, publishAt=null)]

Note that we specified that we only need to return id, title, and content, so the rest of the members in the return DO are null

5. Scope query

Criteria. Where (“content_id”). LessThanEqual (2), which indicates that the value of content_id is less than 2

/** * private void QueryRange () {Query Query = new SimpleQuery(); query.addCriteria(Criteria.where("content_id").between(1, 3)); query.addSort(Sort.by("content_id").ascending()); List<DocDO> ans = solrTemplate.query("yhh", query, DocDO.class).getContent(); System.out.println("queryRange: " + ans); }

The output is as follows. Note that between is a closed interval

queryRange: DocDO(id=1, contentId=1, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=3, content= 1, type=1, createAt=1578912072, publishAt=1578912072), ContentId =3, title=solrTemplate, content=null, type=0, createAt=1578997659, publishAt=1578997659)]

If you don’t want a closed interval, you can overload between

query = new SimpleQuery(); $addCriteria(Criteria. Where ("content_id"). BETWEEN (1, 3, false, false)); query.addSort(Sort.by("content_id").ascending()); ans = solrTemplate.query("yhh", query, DocDO.class).getContent(); System.out.println("queryRange: " + ans);

The output results are as follows

QueryRange: [DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072]]

6. The sorting

In the above case, we have used Sort, mainly Sort to specify the Sort fields and how to Sort them. Since id is actually a string in Solr, sorting by id is actually done by string collation (even though id is an int in our POJO).

Private void QueryAndSort () {private void QueryAndSort () {// Sort Query = new SimpleQuery(); Query. AddCriteria (new Criteria(" Content "). Contains (" Content ")); / / inverted query. AddSort (Sort) by (" content_id "). The item first-just ()); Page<DocDO> ans = solrTemplate.query("yhh", query, DocDO.class); System.out.println("queryAndSort: " + ans.getContent()); }

The output is as follows

queryAndSort: DocDO(id=1, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=2, contentId=2, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072), DocDO(id=1, publishAt=1578912072), ContentId =1, title= 1, content= 1, type=1, createAt=1578912072, publishAt=1578912072)]

7. Paging queries

Paging queries are common, especially when the volume of data is large, so be sure to add a paging condition

One query case is as follows, query all data, and set the paging condition, query second and third data (counting starts from 0).

/** * Paging */ private void QueryPageSize () {Query Query = new SimpleQuery("*:*"); query.addSort(Sort.by("content_id").ascending()); $setOffset(2L); $setOffset(2L); // Query. SetRows (2); Page<DocDO> ans = solrTemplate.queryForPage("yhh", query, DocDO.class); Long TotalDocNum = Ans.getTotalElements (); List<DocDO> docList = ans.getContent(); System.out.println("queryPageSize: totalDocNum=" + totalDocNum + " docList=" + docList); }

In the return result, in addition to looking up the documents that returned the query, we will also give the number of documents that meet the criteria, which can be obtained from Page#getTotalElements,

The output results of the above case are as follows

queryPageSize: TotalDocNum =6 doClist =[doDo (id=3, contentId=3, title=solrTemplate), content=null, type=0, creatEat =1578997946, publishAt=1578997946), DocDO(id=4, contentId=4, title=null, content=null, type=1, createAt=0, publishAt=0)]

8. Group queries

Grouping is a little different from the previous query, mainly in the processing of the results and the fact that the grouping parameter must specify paging information

Private void QueryGroup () {Query Query = new SimpleQuery("*:*"); // Pageeable must not be NULL if offset/limit is specified. GroupOptions groupOptions = new GroupOptions().addGroupByField("type").setOffset(0).setLimit(10); query.setGroupOptions(groupOptions); GroupPage<DocDO> ans = solrTemplate.queryForGroupPage("yhh", query, DocDO.class); GroupResult<DocDO> groupResult = ans.getGroupResult("type"); Page<GroupEntry<DocDO>> entries = groupResult.getGroupEntries(); System.out.println("============ query for group ============ "); For (groupTry <DocDO> sub: entries) {String groupValue = sub.getGroupValue(); Page<DocDO> contentList = sub.getResult(); System.out.println("queryGroup v=" + groupValue + " content=" + contentList.getContent()); } System.out.println("============ query for group ============ "); }

While the above case is relatively simple, there are a few caveat points, especially the retrieval of the return results, where the wrapper level is a little deeper

  • GroupOptions:

    • Offset /limit must be specified, and an exception is thrown when neither condition is present
    • When only offset is specified, limit defaults to 1
    • When only limit is specified, offset defaults to 0
  • The result processing

    • GroupPage#getGroupResult(field)Gets the contents of the group, where Field is a member of the specified group
    • traverseGroupResult#getGroupEntriesGets the list of documents corresponding to each group

The output is as follows

= = = = = = = = = = = = query for group = = = = = = = = = = = = queryGroup v = 1 content = [DocDO (id = 1, contentId = 1, blog title = one is gray, Type =1, createAt=1578912072, publishAt=1578912072), DocDO(id=2, contentId=2, title= 1), Type =1, createAt=1578912072, publishAt=1578912072), DocDO(id=5, contentId=5, Title = addBatchByBean-1, content= new test document, type=1, creatEat =1578997946, publishAt=1578997946), DocDO(id=6, ContentId =6, title= addBatchByBean-2, content= new test document, type=1, creatEat =1578997946, publishAt=1578997946), DocDO(id=4, contentId=4, title=null, content=null, type=1, createAt=0, PublishAt =0)] QueryGroup v=0 Content =[docDo (id=3, contentId=3, title= SolrTemplate), Content =null, Type =0, createAt=1578997946, publishAt=1578997946)] ============ query for group ============

III. The other

0 series of blog & engineering source code

Series of blog posts

  • 200114-SpringBoot series Solr document deletion
  • 190526-SpringBoot Advanced Search Solr for new and modified postures
  • 190510-SpringBoot Advanced Part Solr Environment Building and Simple Testing

Engineering source

  • Project: https://github.com/liuyueyi/spring-boot-demo
  • Source: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/140-search-solr

1. Grey Blog

Do not trust the book, the above content, purely a family of words, due to personal ability is limited, inevitably there are omissions and mistakes, such as bugs found or have better suggestions, welcome criticism, gratefully

The following a gray personal blog, record all study and work in the blog, welcome everyone to visit

  • A Grey Blog personal Blog https://blog.hhui.top
  • A Grey Blog-Spring feature Blog http://spring.hhui.top