Implementation and design of article review based on MongoDB

Implementation and design of article review based on MongoDB

Premise: This paper aims to learn the implementation idea of mongoDB for the system comment function, which is not a complete implementation of the system comment function.

Design

Structure of comment collection

_idmongoDB document default number
cidArticle id, generated by snowflake algorithm
contentComment content
publishdateComment release time
userIdCommentator
articleIdComment article ID
thumbupNumber of comments liked
parentId0 means comment article; If the comment is a comment, it is the commented comment c_id

thinking

Users can comment on articles and comments, similar to a tree structure. Therefore, there is a comment parent ID: parentId. When the user comments on an article, parentId=0; When the user comments on other people's comments, parentId = ID of the commented data

Is it better to check out the comments of the article at one time or individually?

A single query is better. In the article page, first query only the comments belonging to the article, that is, the comment data with parentId=0. Because not everyone wants to see the comments. If you want to see them, you can click on a separate query (using asynchronous loading), and the recursive efficiency of all the found methods is low, which may lead to poor system performance.

Considering the system performance and user experience, a single query is better.

Technology for operating mongoDB

Using spring data mongodb

realization

Import dependency

<!--spring data mongodb-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

I deploy mongodb in the docker container

ip:192.168.200.135

The port is the default port: 27017

Profile configuration

spring:
  data:
    mongodb:
      host: 192.168.200.135  #Connection ip
      port: 27017 #Port number
      database: commentDB #database

Create an article comment pojo entity class

package cn.jankin.pojo;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.util.Date;

/**
 * Comment entity
 */
@Document("comment")
public class Comment implements Serializable {
    @Id
    private String _id;  //mongodb default primary key to speed up data insertion
    private String cid;  //The snowflake generator generates a comment ID and mongoDB establishes an index
    private String articleid;
    private String content;
    private String userid;
    private String parentid;
    private Date publishdate;
    private Integer thumbup;
}

Note: I didn't default mongodb here_ id is used as the identification of the comment, but another attribute cid is assigned as the identification.

Reason: optimize the performance of mongodb and solve the possible data inconsistency.

Meaning: users may post comments every minute and second in the system, if the system adopts the default_ id as the comment id, we know that mongodb is the default_ The type of id is ObjectId, which is a 12 byte data composed of timestamp, machine identification code, mongodb instance process number and random sequence. If a mongodb cluster environment is built, when a large number of users publish comments, the generated objectids may be the same, which leads to the breaking of the uniqueness of comments.

Then, instead of using mongodb's default ObjectId, the system program can generate a unique id set to_ id, such as the id generated by the snowflake algorithm, isn't it?

Yes, but there are collections in mongodb_ id index. Only by indexing mongodb can you quickly query the specified document. When inserting, if the user-defined value is used_ id, which will greatly affect the insertion efficiency of mongodb documents, especially when the number of existing documents in the collection is extremely large. Therefore, the above practices will affect the performance of the system in the later stage, and are not recommended.

Second, it's better not to use the default unique id of mongodb, so cid was born. cid is the id generated by snowflake algorithm, which ensures the uniqueness of comments_ id still uses the default type to ensure the efficiency of insertion. We only need to build another cid index in mongodb to ensure the performance of cid query, which is a typical concept of space for time.

The process of building the project will not be repeated. Just start typing the code.

Functions required to analyze comments

1. Query comments through comment cid

2. Query comments through the article id, and top-level comments (comments of comment articles) are sorted by publishing time

3. Query the comments under a comment through the article id

3. Query comments by user id and sort by publishing time

4. Delete comments by id

5. Comment like and cancel like

6. Post comments

Note that the comment function is not modified. If you want to change it, you can only delete it and republish it.
For the missing functions, through the realization of the above functions, we can basically follow the gourd.

For the parameter verification of data, I use hibernate validator. You can use other methods, which does not belong to the content of this article.

restful is used to separate the front and rear ends.

We only implement the backend.

I operate mongoDB in two ways:

One is to use MongoDBTemplate to implement operations similar to those requiring column value growth and other functions;

One is to create a persistent interface, CommentRepository, which inherits the MongoDBRepository interface provided by Panasonic data mongodb, and splice methods to realize simple conditional query.

Here, I only give the method of operating mongoDB to obtain data. The operation of three-tier architecture and spring boot is not reflected in the code.

Start typing code

Start directly from the service layer. The presentation layer does not reflect it.

Create Service interface

package cn.jankin.service;

import cn.jankin.pojo.Comment;

import java.util.List;
import java.util.Map;

/**
 * Comment service interface
 */
public interface CommentService {

    /**
     * Get comment data through comment id
     * @param id Comment id
     * @return
     */
    Comment findById(String id);

    /**
     * Find the comments published by the user according to the user id and sort them according to the publishing time
     * @param userId
     * @param sortType
     * @return
     */
    List<Comment> findByUserIdOrderByPublishdate(String userId,String sortType);

    /**
     * Query the comments of the specified article. The comments without comments are sorted by the release time of the comments
     * @param articleId
     * @param sortType
     * @return
     */
    List<Comment> findByArticleIdOrderByPublishdate(String articleId,String sortType);

    /**
     * Modify comment data by comment id
     * @param comment
     */
    void updateById(Comment comment);

    /**
     * Delete comments by comment id
     * @param commentId
     */
    void deleteById(String commentId);

    /**
     * Implementation of like comment function
     * @param commentId Liked comment id
     * @param isThumbup true : give the thumbs-up; false: cancel liking
     */
    void thumbup(String commentId,Boolean isThumbup);


    /**
     * Post comments
     * @param comment
     */
    void save(Comment comment);
}

Function 1: query the comment findById according to the comment id.

service

 	/**
     * Identification by comment c_id query comment data
     * @param id Comment id
     * @return
     */
    @Override
    public Comment findById(String id) {
        Comment comment = commentRepositoty.findByCid(id);
        return comment;
    }

repository: implemented by conditional splicing method

  /**
     * Adoption of comments c_id query comment data
     * @param cid
     * @return
     */
    Comment findByCid(String cid);

Function 2: query comments through article id, top-level comments (comments of comment articles), sorted by release time

service

/**
     * Query the comments according to the article id and sort them by time
     * @param articleId
     * @param sortType
     * @return
     */
    @Override
    public List<Comment> findByArticleIdOrderByPublishdate(String articleId, String sortType) {
        List<Comment> list = null;
        //Judge sorting rules
        if(sortType.equals(SortType.ASC)){
            list = commentRepositoty.findByArticleidOrderByPublishdateAsc(articleId);
        }else{
            list = commentRepositoty.findByArticleidOrderByPublishdateDesc(articleId);
        }
        return list;
    }

There is a sortType parameter here, which is used to identify whether to sort in ascending or descending order.

package cn.jankin.entity;

/**
 * Sort type
 */
public class SortType {
    public final static String ASC = "1";  //Ascending order
    public final static String DESC = "-1";  //Descending order
}

In this way, when we need to change the front-end sorting parameters, we can directly use this class instead of changing it one class at a time. Design principle: closed for modification and open for expansion.

repository

/**
     * Query the comments according to the article id and sort them in positive order according to the release time
     * @param articleId
     * @return
     */
    List<Comment> findByArticleidOrderByPublishdateAsc(String articleId);

    /**
     * Query the comments according to the article id and sort them according to the release time
     * @param articleId
     * @return
     */
    List<Comment> findByArticleidOrderByPublishdateDesc(String articleId);

Function 3: query comments by user id and sort them by publishing time

Because it is not much different from the article id query method, I won't repeat it. However, the problem of login users should be considered. This is only a demo, and the user login function is not implemented.

Function 4: delete comments according to cid

service

/**
     * Delete the comment document with the specified comment id
     * @param commentId
     */
    @Override
    public void deleteById(String commentId) {
        commentRepositoty.deleteByCid(commentId);
    }

repository

 /**
     * By user identificationc_ ID delete comment
     * @param cid
     */
    void deleteByCid(String cid);

Function 5: comment, like and cancel like

/**
     * Users like and cancel like comments according to comment id
     * @param commentId Liked comment id
     * @param isThumbup true : give the thumbs-up; false: cancel liking
     */
    @Override
    public void thumbup(String commentId, Boolean isThumbup) {
        Query query = new Query(Criteria.where("cid").is(commentId)); //Set modification conditions
        Update update = new Update();
        if(isThumbup){ //Click like operation
            update.inc("thumbup",1);
        }else{  //Cancel like operation
            update.inc("thumbup",-1);
        }
        mongoTemplate.updateFirst(query,update,"comment");
    }

Function 6: publish comments

service

/**
     * Post comments
     * @param comment
     */
    @Override
    public void save(Comment comment) {
        //Generate id
        String id = idWorker.nextId()+"";
        comment.setCid(id);
        //Set publishing time
        comment.setPublishdate(new Date());
        //Set initial likes
        comment.setThumbup(0);
        //preservation
        commentRepositoty.save(comment);
    }

Keywords: MongoDB

Added by audiodef on Thu, 14 Oct 2021 07:05:01 +0300